From ae93e64fae4eba83e4b746e1f5473fa765812f52 Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 16:26:47 +0200 Subject: [PATCH 01/11] [net] remove deprecated TSocket::CreateAuthSocket() --- net/net/inc/TSocket.h | 17 --- net/net/src/TPSocket.cxx | 84 +------------- net/net/src/TSocket.cxx | 219 ++----------------------------------- net/net/src/TUDPSocket.cxx | 11 +- 4 files changed, 12 insertions(+), 319 deletions(-) diff --git a/net/net/inc/TSocket.h b/net/net/inc/TSocket.h index 3bea06d01a834..e346f340c4bf5 100644 --- a/net/net/inc/TSocket.h +++ b/net/net/inc/TSocket.h @@ -42,12 +42,6 @@ struct TSocketFriend { static Bool_t IsAuthenticated(const TSocket &s); static void SetSecContext(TSocket &s, TSecContext *ctx); static TSecContext *GetSecContext(const TSocket &s); - - static TSocket *CreateAuthSocket(const char *user, const char *host, - Int_t port, Int_t size = 0, - Int_t tcpwindowsize = -1, TSocket *s = nullptr, Int_t *err = nullptr); - static TSocket *CreateAuthSocket(const char *url, Int_t size = 0, - Int_t tcpwindowsize = -1, TSocket *s = nullptr, Int_t *err = nullptr); }; } // namespace ROOT::Deprecated @@ -187,17 +181,6 @@ friend struct ROOT::Deprecated::TSocketFriend; static ULong64_t GetSocketBytesSent(); static ULong64_t GetSocketBytesRecv(); - static TSocket *CreateAuthSocket(const char *user, const char *host, - Int_t port, Int_t size = 0, - Int_t tcpwindowsize = -1, TSocket *s = nullptr, Int_t *err = nullptr) - R__DEPRECATED(6, 42, "Socket authentication is deprecated. See README.AUTH for details.") - { return ROOT::Deprecated::TSocketFriend::CreateAuthSocket( - user, host, port, size, tcpwindowsize, s, err); } - static TSocket *CreateAuthSocket(const char *url, Int_t size = 0, - Int_t tcpwindowsize = -1, TSocket *s = nullptr, Int_t *err = nullptr) - R__DEPRECATED(6, 42, "Socket authentication is deprecated. See README.AUTH for details.") - { return ROOT::Deprecated::TSocketFriend::CreateAuthSocket(url, size, tcpwindowsize, s, err); } - static void NetError(const char *where, Int_t error); ClassDefOverride(TSocket,0) //This class implements client sockets diff --git a/net/net/src/TPSocket.cxx b/net/net/src/TPSocket.cxx index 5cef3c0c74623..1895140674716 100644 --- a/net/net/src/TPSocket.cxx +++ b/net/net/src/TPSocket.cxx @@ -107,50 +107,9 @@ TPSocket::TPSocket(const char *host, Int_t port, Int_t size, // to control the flow Bool_t valid = TSocket::IsValid(); - // check if we are called from CreateAuthSocket() - Bool_t authreq = kFALSE; - char *pauth = (char *)strstr(host, "?A"); - if (pauth) { - authreq = kTRUE; - } - // perhaps we can use fServType here ... to be checked Bool_t rootdSrv = (strstr(host,"rootd")) ? kTRUE : kFALSE; - // try authentication , if required - if (authreq) { - if (valid) { - if (!Authenticate(TUrl(host).GetUser())) { - if (rootdSrv && (fRemoteProtocol > 0 && fRemoteProtocol < 10)) { - // We failed because we are talking to an old - // server: we need to re-open the connection - // and communicate the size first - Int_t tcpw = (size > 1 ? -1 : tcpwindowsize); - TSocket *ns = new TSocket(host, port, tcpw); - if (ns->IsValid()) { - R__LOCKGUARD(gROOTMutex); - gROOT->GetListOfSockets()->Remove(ns); - fSocket = ns->GetDescriptor(); - fSize = size; - Init(tcpwindowsize); - } - if ((valid = IsValid())) { - if (!Authenticate(TUrl(host).GetUser())) { - TSocket::Close(); - valid = kFALSE; - } - } - } else { - TSocket::Close(); - valid = kFALSE; - } - } - } - // reset url to the original state - *pauth = '\0'; - SetUrl(host); - } - // open the sockets ... if (!rootdSrv || fRemoteProtocol > 9) { if (valid) { @@ -170,7 +129,7 @@ TPSocket::TPSocket(const char *host, Int_t port, Int_t size, /// sockets list which will make sure that any open sockets are properly /// closed on program termination. -TPSocket::TPSocket(const char *host, Int_t port, Int_t size, TSocket *sock) +TPSocket::TPSocket(const char *host, Int_t /* port */, Int_t size, TSocket *sock) { // To avoid uninitialization problems when Init is not called ... fSockets = 0; @@ -203,50 +162,9 @@ TPSocket::TPSocket(const char *host, Int_t port, Int_t size, TSocket *sock) // to control the flow Bool_t valid = sock->IsValid(); - // check if we are called from CreateAuthSocket() - Bool_t authreq = kFALSE; - char *pauth = (char *)strstr(host, "?A"); - if (pauth) { - authreq = kTRUE; - } - // perhaps we can use fServType here ... to be checked Bool_t rootdSrv = (strstr(host,"rootd")) ? kTRUE : kFALSE; - // try authentication , if required - if (authreq) { - if (valid) { - if (!Authenticate(TUrl(host).GetUser())) { - if (rootdSrv && (fRemoteProtocol > 0 && fRemoteProtocol < 10)) { - // We failed because we are talking to an old - // server: we need to re-open the connection - // and communicate the size first - Int_t tcpw = (size > 1 ? -1 : fTcpWindowSize); - TSocket *ns = new TSocket(host, port, tcpw); - if (ns->IsValid()) { - R__LOCKGUARD(gROOTMutex); - gROOT->GetListOfSockets()->Remove(ns); - fSocket = ns->GetDescriptor(); - fSize = size; - Init(fTcpWindowSize); - } - if ((valid = IsValid())) { - if (!Authenticate(TUrl(host).GetUser())) { - TSocket::Close(); - valid = kFALSE; - } - } - } else { - TSocket::Close(); - valid = kFALSE; - } - } - } - // reset url to the original state - *pauth = '\0'; - SetUrl(host); - } - // open the sockets ... if (!rootdSrv || fRemoteProtocol > 9) { if (valid) { diff --git a/net/net/src/TSocket.cxx b/net/net/src/TSocket.cxx index b76a47ee0f6ba..b4f00dab309f2 100644 --- a/net/net/src/TSocket.cxx +++ b/net/net/src/TSocket.cxx @@ -207,9 +207,17 @@ TSocket::TSocket(const char *host, const char *service, Int_t tcpwindowsize) } //////////////////////////////////////////////////////////////////////////////// -/// Create a socket; see CreateAuthSocket for the form of url. +/// Create a socket. The url parameter has the form +/// +/// [sockd://]host[:port][/service] +/// +/// where +/// [port] = is the remote port number +/// [service] = service name used to determine the port +/// (for backward compatibility, specification of +/// port as priority) +/// /// Connect to the specified port # on the remote host. -/// If user is specified in url, try authentication as user. /// Use tcpwindowsize to specify the size of the receive buffer, it has /// to be specified here to make sure the window scale option is set (for /// tcpwindowsize > 65KB and for platforms supporting window scaling). @@ -1254,213 +1262,6 @@ Bool_t TSocket::Authenticate(const char *user) return rc; } -//////////////////////////////////////////////////////////////////////////////// -/// Creates a socket or a parallel socket and authenticates to the -/// remote server. -/// -/// url: [[proto][p][auth]://][user@]host[:port][/service] -/// -/// where proto = "sockd", "rootd" -/// indicates the type of remote server; -/// if missing "sockd" is assumed ("sockd" indicates -/// any remote server session using TServerSocket) -/// [auth] = "up" or "k" to force UsrPwd or Krb5 authentication -/// [port] = is the remote port number -/// [service] = service name used to determine the port -/// (for backward compatibility, specification of -/// port as priority) -/// -/// An already opened connection can be used by passing its socket -/// in opensock. -/// -/// If 'err' is defined, '*err' on return from a failed call contains an error -/// code (see NetErrors.h). -/// -/// Example: -/// -/// TSocket::CreateAuthSocket("pk://qwerty@machine.fq.dn:5052",3) -/// -/// creates an authenticated parallel socket of size 3 to a sockd -/// server running on remote machine machine.fq.dn on port 5052; -/// authentication will attempt protocol Kerberos first. -/// -/// NB: may hang if the remote server is not of the correct type; -/// at present TSocket has no way to find out the type of the -/// remote server automatically -/// -/// Returns pointer to an authenticated socket or 0 if creation or -/// authentication is unsuccessful. - -TSocket *ROOT::Deprecated::TSocketFriend::CreateAuthSocket( - const char *url, Int_t size, Int_t tcpwindowsize, TSocket *opensock, Int_t *err) -{ - R__LOCKGUARD2(gSocketAuthMutex); - - // Url to be passed to chosen constructor - TString eurl(url); - - // Parse protocol, if any - Bool_t parallel = kFALSE; - TString proto(TUrl(url).GetProtocol()); - TString protosave = proto; - - // Get rid of authentication suffix - TString asfx = ""; - if (proto.EndsWith("up") || proto.EndsWith("ug")) { - asfx = proto; - asfx.Remove(0,proto.Length()-2); - proto.Resize(proto.Length()-2); - } else if (proto.EndsWith("s") || proto.EndsWith("k") || - proto.EndsWith("g") || proto.EndsWith("h")) { - asfx = proto; - asfx.Remove(0,proto.Length()-1); - proto.Resize(proto.Length()-1); - } - - // Find out if parallel (force if rootd) - if ((proto.EndsWith("p") || size > 1) || - proto.BeginsWith("root") ) { - parallel = kTRUE; - if (proto.EndsWith("p")) - proto.Resize(proto.Length()-1); - } - - // Force "sockd" if the rest is not recognized - if (!proto.BeginsWith("sock") && - !proto.BeginsWith("root")) - proto = "sockd"; - - // Substitute this for original proto in eurl - protosave += "://"; - proto += asfx; - proto += "://"; - eurl.ReplaceAll(protosave,proto); - - // Create the socket now - - TSocket *sock = 0; - if (!parallel) { - - // Simple socket - if (opensock && opensock->IsValid()) - sock = opensock; - else - sock = new TSocket(eurl, TUrl(url).GetPort(), tcpwindowsize); - - // Authenticate now - if (sock && sock->IsValid()) { - if (!sock->Authenticate(TUrl(url).GetUser())) { - // Nothing to do except setting the error code (if required) and sock to NULL - if (err) { - *err = (Int_t)kErrAuthNotOK; - if (sock->TestBit(TSocket::kBrokenConn)) *err = (Int_t)kErrConnectionRefused; - } - sock->Close(); - delete sock; - sock = 0; - } - } - - } else { - - // Tell TPSocket that we want authentication, which has to - // be done using the original socket before creation of set - // of parallel sockets - if (eurl.Contains("?")) - eurl.Resize(eurl.Index("?")); - eurl += "?A"; - - // Parallel socket - if (opensock && opensock->IsValid()) - sock = new TPSocket(eurl, TUrl(url).GetPort(), size, opensock); - else - sock = new TPSocket(eurl, TUrl(url).GetPort(), size, tcpwindowsize); - - // Cleanup if failure ... - if (sock && !ROOT::Deprecated::TSocketFriend::IsAuthenticated(*sock)) { - // Nothing to do except setting the error code (if required) and sock to NULL - if (err) { - *err = (Int_t)kErrAuthNotOK; - if (sock->TestBit(TSocket::kBrokenConn)) *err = (Int_t)kErrConnectionRefused; - } - if (sock->IsValid()) - // And except when the sock is valid; this typically - // happens when talking to a old server, because the - // the parallel socket system is open before authentication - delete sock; - sock = 0; - } - } - - return sock; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Creates a socket or a parallel socket and authenticates to the -/// remote server specified in 'url' on remote 'port' as 'user'. -/// -/// url: [[proto][auth]://]host -/// -/// where proto = "sockd", "rootd" -/// indicates the type of remote server -/// if missing "sockd" is assumed ("sockd" indicates -/// any remote server session using TServerSocket) -/// [auth] = "up" or "k" to force UsrPwd or Krb5 authentication -/// -/// An already opened connection can be used by passing its socket -/// in opensock. -/// -/// If 'err' is defined, '*err' on return from a failed call contains an error -/// code (see NetErrors.h). -/// -/// Example: -/// -/// TSocket::CreateAuthSocket("qwerty","pk://machine.fq.dn:5052",3) -/// -/// creates an authenticated parallel socket of size 3 to a sockd -/// server running on remote machine machine.fq.dn on port 5052; -/// authentication will attempt protocol Kerberos first. -/// -/// NB: may hang if the remote server is not of the correct type; -/// at present TSocket has no way to find out the type of the -/// remote server automatically -/// -/// Returns pointer to an authenticated socket or 0 if creation or -/// authentication is unsuccessful. - -TSocket *ROOT::Deprecated::TSocketFriend::CreateAuthSocket( - const char *user, const char *url, Int_t port, Int_t size, Int_t tcpwindowsize, TSocket *opensock, Int_t *err) -{ - R__LOCKGUARD2(gSocketAuthMutex); - - // Extended url to be passed to base call - TString eurl; - - // Add protocol, if any - if (TString(TUrl(url).GetProtocol()).Length() > 0) { - eurl += TString(TUrl(url).GetProtocol()); - eurl += TString("://"); - } - // Add user, if any - if (!user || strlen(user) > 0) { - eurl += TString(user); - eurl += TString("@"); - } - // Add host - eurl += TString(TUrl(url).GetHost()); - // Add port - eurl += TString(":"); - eurl += (port > 0 ? port : 0); - // Add options, if any - if (TString(TUrl(url).GetOptions()).Length() > 0) { - eurl += TString("/?"); - eurl += TString(TUrl(url).GetOptions()); - } - - // Create the socket and return it - return TSocketFriend::CreateAuthSocket(eurl,size,tcpwindowsize,opensock,err); -} - //////////////////////////////////////////////////////////////////////////////// /// Static method returning supported client protocol. diff --git a/net/net/src/TUDPSocket.cxx b/net/net/src/TUDPSocket.cxx index 4f51c60704c87..be4de72bfb4a4 100644 --- a/net/net/src/TUDPSocket.cxx +++ b/net/net/src/TUDPSocket.cxx @@ -169,16 +169,7 @@ TUDPSocket::TUDPSocket(const char *host, const char *service) } //////////////////////////////////////////////////////////////////////////////// -/// Create a socket; see CreateAuthSocket for the form of url. -/// Connect to the specified port # on the remote host. -/// If user is specified in url, try authentication as user. -/// Use tcpwindowsize to specify the size of the receive buffer, it has -/// to be specified here to make sure the window scale option is set (for -/// tcpwindowsize > 65KB and for platforms supporting window scaling). -/// Returns when connection has been accepted by remote side. Use IsValid() -/// to check the validity of the socket. Every socket is added to the TROOT -/// sockets list which will make sure that any open sockets are properly -/// closed on program termination. +/// Create a socket; see TSocket constructor. TUDPSocket::TUDPSocket(const char *url, Int_t port) : TNamed(TUrl(url).GetHost(), ""), fCompress(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal) From 87060b4a4c47cb0d30ec1b9abf5a2684b5abfe4a Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 16:31:38 +0200 Subject: [PATCH 02/11] [net] remove deprecated TSocket::IsAuthenticated() --- net/net/inc/TSocket.h | 4 ---- net/net/src/TPServerSocket.cxx | 6 ------ net/net/src/TSocket.cxx | 5 ----- 3 files changed, 15 deletions(-) diff --git a/net/net/inc/TSocket.h b/net/net/inc/TSocket.h index e346f340c4bf5..6692f9a35ced5 100644 --- a/net/net/inc/TSocket.h +++ b/net/net/inc/TSocket.h @@ -39,7 +39,6 @@ class TSocket; namespace ROOT::Deprecated { struct TSocketFriend { - static Bool_t IsAuthenticated(const TSocket &s); static void SetSecContext(TSocket &s, TSecContext *ctx); static TSecContext *GetSecContext(const TSocket &s); }; @@ -144,9 +143,6 @@ friend struct ROOT::Deprecated::TSocketFriend; Int_t GetTcpWindowSize() const { return fTcpWindowSize; } TTimeStamp GetLastUsage() { R__LOCKGUARD2(fLastUsageMtx); return fLastUsage; } const char *GetUrl() const { return fUrl.Data(); } - virtual Bool_t IsAuthenticated() const - R__DEPRECATED(6, 42, "TSocket::IsAuthenticated is deprecated") - { return ROOT::Deprecated::TSocketFriend::IsAuthenticated(*this); } virtual Bool_t IsValid() const { return fSocket < 0 ? kFALSE : kTRUE; } virtual Int_t Recv(TMessage *&mess); virtual Int_t Recv(Int_t &status, Int_t &kind); diff --git a/net/net/src/TPServerSocket.cxx b/net/net/src/TPServerSocket.cxx index 0bdce8fb50271..2de21d37a1860 100644 --- a/net/net/src/TPServerSocket.cxx +++ b/net/net/src/TPServerSocket.cxx @@ -137,12 +137,6 @@ TPSocket *TPServerSocket::Accept(UChar_t Opt) } - // Transmit authentication information, if any - if (ROOT::Deprecated::TSocketFriend::IsAuthenticated(*setupSocket)) { - ROOT::Deprecated::TSocketFriend::SetSecContext(*newPSocket, - ROOT::Deprecated::TSocketFriend::GetSecContext(*setupSocket)); - } - // clean up, if needed if (size > 0) delete setupSocket; diff --git a/net/net/src/TSocket.cxx b/net/net/src/TSocket.cxx index b4f00dab309f2..52637f9c3d130 100644 --- a/net/net/src/TSocket.cxx +++ b/net/net/src/TSocket.cxx @@ -39,11 +39,6 @@ TUnixSystem or TWinNTSystem). #include -Bool_t ROOT::Deprecated::TSocketFriend::IsAuthenticated(const TSocket &s) -{ - return s.fSecContext; -} - void ROOT::Deprecated::TSocketFriend::SetSecContext(TSocket &s, TSecContext *ctx) { s.fSecContext = ctx; From 5752a7dcd28bf8535314109ecf1db26cbf36fc14 Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 16:43:28 +0200 Subject: [PATCH 03/11] [net] remove unused TSocket::Authenticate() --- net/net/inc/TSocket.h | 3 +- net/net/inc/TUDPSocket.h | 2 +- net/net/src/TSocket.cxx | 130 --------------------------------------- 3 files changed, 2 insertions(+), 133 deletions(-) diff --git a/net/net/inc/TSocket.h b/net/net/inc/TSocket.h index 6692f9a35ced5..74a250e4ea02d 100644 --- a/net/net/inc/TSocket.h +++ b/net/net/inc/TSocket.h @@ -81,7 +81,7 @@ friend struct ROOT::Deprecated::TSocketFriend; EServiceType fServType; // remote service type Int_t fSocket; // socket descriptor Int_t fTcpWindowSize; // TCP window size (default 65535); - TString fUrl; // needs this for special authentication options + TString fUrl; // used to hold special authentication options TBits fBitsInfo; // bits array to mark TStreamerInfo classes already sent TList *fUUIDs; // list of TProcessIDs already sent through the socket @@ -98,7 +98,6 @@ friend struct ROOT::Deprecated::TSocketFriend; fServType(kSOCKD), fSocket(-1), fTcpWindowSize(0), fUrl(), fBitsInfo(), fUUIDs(nullptr), fLastUsageMtx(nullptr), fLastUsage() {} - Bool_t Authenticate(const char *user); void SetDescriptor(Int_t desc) { fSocket = desc; } void SendStreamerInfos(const TMessage &mess); Bool_t RecvStreamerInfos(TMessage *mess); diff --git a/net/net/inc/TUDPSocket.h b/net/net/inc/TUDPSocket.h index d29c09459ef05..c0e61e461aef1 100644 --- a/net/net/inc/TUDPSocket.h +++ b/net/net/inc/TUDPSocket.h @@ -56,7 +56,7 @@ friend class TServerSocket; TString fService; // name of service (matches remote port #) EServiceType fServType; // remote service type Int_t fSocket; // socket descriptor - TString fUrl; // needs this for special authentication options + TString fUrl; // address of the remote service TBits fBitsInfo; // bits array to mark TStreamerInfo classes already sent TList *fUUIDs; // list of TProcessIDs already sent through the socket diff --git a/net/net/src/TSocket.cxx b/net/net/src/TSocket.cxx index 52637f9c3d130..339eddf72f94f 100644 --- a/net/net/src/TSocket.cxx +++ b/net/net/src/TSocket.cxx @@ -1127,136 +1127,6 @@ void TSocket::SetCompressionSettings(Int_t settings) fCompress = settings; } -//////////////////////////////////////////////////////////////////////////////// -/// Authenticated the socket with specified user. - -Bool_t TSocket::Authenticate(const char *user) -{ - Bool_t rc = kFALSE; - - // Parse protocol name - TString sproto = TUrl(fUrl).GetProtocol(); - if (sproto.Contains("sockd")) { - fServType = kSOCKD; - } else if (sproto.Contains("rootd")) { - fServType = kROOTD; - } - if (gDebug > 2) - Info("Authenticate","Local protocol: %s",sproto.Data()); - - // Get server protocol level - Int_t kind = kROOTD_PROTOCOL; - // Warning: for backward compatibility reasons here we have to - // send exactly 4 bytes: for fgClientClientProtocol > 99 - // the space in the format must be dropped - if (fRemoteProtocol == -1) { - if (Send(Form(" %d", fgClientProtocol), kROOTD_PROTOCOL) < 0) { - return rc; - } - if (Recv(fRemoteProtocol, kind) < 0) { - return rc; - } - // - // If we are talking to an old rootd server we get a fatal - // error here and we need to reopen the connection, - // communicating first the size of the parallel socket - if (kind == kROOTD_ERR) { - fRemoteProtocol = 9; - return kFALSE; - } - } - - // Find out whether authentication is required - Bool_t runauth = kTRUE; - if (fRemoteProtocol > 1000) { - // Authentication not required by the remote server - runauth = kFALSE; - fRemoteProtocol %= 1000; - } - - // If authentication is required, we need to find out which library - // has to be loaded (preparation for near future, 9/7/05) - TString host = GetInetAddress().GetHostName(); - if (runauth) { - - // Default (future) - TString alib = "Xrd"; - if (fRemoteProtocol < 100) { - // Standard Authentication lib - alib = "Root"; - } - - // Load the plugin - TPluginHandler *h = - gROOT->GetPluginManager()->FindHandler("TVirtualAuth", alib); - if (!h || h->LoadPlugin() != 0) { - Error("Authenticate", - "could not load properly %s authentication plugin", alib.Data()); - return rc; - } - - // Get an instance of the interface class - auto auth = (ROOT::Deprecated::TVirtualAuth *)(h->ExecPlugin(0)); - if (!auth) { - Error("Authenticate", "could not instantiate the interface class"); - return rc; - } - if (gDebug > 1) - Info("Authenticate", "class for '%s' authentication loaded", alib.Data()); - - Option_t *opts = ""; - if (!(auth->Authenticate(this, host, user, opts))) { - Error("Authenticate", - "authentication attempt failed for %s@%s", user, host.Data()); - } else { - rc = kTRUE; - } - } else { - - // Communicate who we are and our target user - UserGroup_t *u = gSystem->GetUserInfo(); - if (u) { - if (Send(Form("%s %s", u->fUser.Data(), user), kROOTD_USER) < 0) - Warning("Authenticate", "problem sending kROOTD_USER (%s,%s)", u->fUser.Data(), user); - delete u; - } else - if (Send(Form("-1 %s", user), kROOTD_USER) < 0) - Warning("Authenticate", "problem sending kROOTD_USER (-1,%s)", user); - - rc = kFALSE; - - // Receive confirmation that everything went well - Int_t stat; - if (Recv(stat, kind) > 0) { - - if (kind == kROOTD_ERR) { - if (gDebug > 0) - TSocket::NetError("TSocket::Authenticate", stat); - } else if (kind == kROOTD_AUTH) { - - // Authentication was not required: create inactive - // security context for consistency - fSecContext = new ROOT::Deprecated::TSecContext(user, host, 0, -4, 0, 0); - if (gDebug > 3) - Info("Authenticate", "no authentication required remotely"); - - // Set return flag; - rc = 1; - } else { - if (gDebug > 0) - Info("Authenticate", "expected message type %d, received %d", - kROOTD_AUTH, kind); - } - } else { - if (gDebug > 0) - Info("Authenticate", "error receiving message"); - } - - } - - return rc; -} - //////////////////////////////////////////////////////////////////////////////// /// Static method returning supported client protocol. From b0c52b937d3299983b004e64e18eeed107a23a9b Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 16:44:47 +0200 Subject: [PATCH 04/11] [net] remove unused gSocketAuthMutex --- net/net/src/TSocket.cxx | 3 --- 1 file changed, 3 deletions(-) diff --git a/net/net/src/TSocket.cxx b/net/net/src/TSocket.cxx index 339eddf72f94f..04ae654abe46d 100644 --- a/net/net/src/TSocket.cxx +++ b/net/net/src/TSocket.cxx @@ -73,9 +73,6 @@ ULong64_t TSocket::fgBytesRecv = 0; // Int_t TSocket::fgClientProtocol = 17; // increase when client protocol changes -TVirtualMutex *gSocketAuthMutex = 0; - - //////////////////////////////////////////////////////////////////////////////// /// Create a socket. Connect to the named service at address addr. /// Use tcpwindowsize to specify the size of the receive buffer, it has From d24d3f1f3522c3c8949039f59ff650c7b1796359 Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 16:58:24 +0200 Subject: [PATCH 05/11] [net] remove deprecated TUDPSocket::[Get|Set]SecContext() --- net/net/inc/TUDPSocket.h | 9 +-------- net/net/src/TUDPSocket.cxx | 8 -------- 2 files changed, 1 insertion(+), 16 deletions(-) diff --git a/net/net/inc/TUDPSocket.h b/net/net/inc/TUDPSocket.h index c0e61e461aef1..084d552a7bfc1 100644 --- a/net/net/inc/TUDPSocket.h +++ b/net/net/inc/TUDPSocket.h @@ -28,7 +28,6 @@ #include "TBits.h" #include "TInetAddress.h" #include "MessageTypes.h" -#include "TSecContext.h" #include "TTimeStamp.h" #include "TVirtualMutex.h" #include "TSocket.h" @@ -51,8 +50,6 @@ friend class TServerSocket; Int_t fCompress; // Compression level and algorithm TInetAddress fLocalAddress; // local internet address and port # Int_t fRemoteProtocol; // protocol of remote daemon - ROOT::Deprecated::TSecContext *fSecContext; // after a successful Authenticate call - // points to related security context TString fService; // name of service (matches remote port #) EServiceType fServType; // remote service type Int_t fSocket; // socket descriptor @@ -67,7 +64,7 @@ friend class TServerSocket; static ULong64_t fgBytesSent; // total bytes sent by all socket objects TUDPSocket() : fAddress(), fBytesRecv(0), fBytesSent(0), fCompress(0), - fLocalAddress(), fRemoteProtocol(), fSecContext(nullptr), fService(), + fLocalAddress(), fRemoteProtocol(), fService(), fServType(kSOCKD), fSocket(-1), fUrl(), fBitsInfo(), fUUIDs(nullptr), fLastUsageMtx(nullptr), fLastUsage() { } @@ -110,8 +107,6 @@ friend class TServerSocket; Int_t GetErrorCode() const; virtual Int_t GetOption(ESockOptions opt, Int_t &val); Int_t GetRemoteProtocol() const { return fRemoteProtocol; } - ROOT::Deprecated::TSecContext *GetSecContext() const - R__DEPRECATED(6, 42, "TUDPSocket::GetSecContext is deprecated") { return fSecContext; } TTimeStamp GetLastUsage() { R__LOCKGUARD2(fLastUsageMtx); return fLastUsage; } const char *GetUrl() const { return fUrl; } @@ -136,8 +131,6 @@ friend class TServerSocket; void SetCompressionSettings(Int_t settings = ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault); virtual Int_t SetOption(ESockOptions opt, Int_t val); void SetRemoteProtocol(Int_t rproto) { fRemoteProtocol = rproto; } - void SetSecContext(ROOT::Deprecated::TSecContext *ctx) - R__DEPRECATED(6, 42, "TUDPSocket::SetSecContext is deprecated"){ fSecContext = ctx; } void SetService(const char *service) { fService = service; } void SetServType(Int_t st) { fServType = (EServiceType)st; } void SetUrl(const char *url) { fUrl = url; } diff --git a/net/net/src/TUDPSocket.cxx b/net/net/src/TUDPSocket.cxx index be4de72bfb4a4..2611494f79dd7 100644 --- a/net/net/src/TUDPSocket.cxx +++ b/net/net/src/TUDPSocket.cxx @@ -59,7 +59,6 @@ TUDPSocket::TUDPSocket(TInetAddress addr, const char *service) R__ASSERT(gSystem); fService = service; - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; if (fService.Contains("root")) @@ -103,7 +102,6 @@ TUDPSocket::TUDPSocket(TInetAddress addr, Int_t port) R__ASSERT(gSystem); fService = gSystem->GetServiceByPort(port); - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; if (fService.Contains("root")) @@ -144,7 +142,6 @@ TUDPSocket::TUDPSocket(const char *host, const char *service) R__ASSERT(gSystem); fService = service; - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; if (fService.Contains("root")) @@ -181,7 +178,6 @@ TUDPSocket::TUDPSocket(const char *url, Int_t port) TString host(TUrl(fUrl).GetHost()); fService = gSystem->GetServiceByPort(port); - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; if (fUrl.Contains("root")) @@ -221,7 +217,6 @@ TUDPSocket::TUDPSocket(const char *sockpath) : TNamed(sockpath, ""), fUrl = sockpath; fService = "unix"; - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; fAddress.fPort = -1; @@ -249,7 +244,6 @@ TUDPSocket::TUDPSocket(Int_t desc) : TNamed("", ""), fCompress(ROOT::RCompressio R__ASSERT(gROOT); R__ASSERT(gSystem); - fSecContext = 0; fRemoteProtocol = 0; fService = (char *)kSOCKD; fServType = kSOCKD; @@ -282,7 +276,6 @@ TUDPSocket::TUDPSocket(Int_t desc, const char *sockpath) : TNamed(sockpath, ""), fUrl = sockpath; fService = "unix"; - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; fAddress.fPort = -1; @@ -315,7 +308,6 @@ TUDPSocket::TUDPSocket(const TUDPSocket &s) : TNamed(s) fBytesSent = s.fBytesSent; fBytesRecv = s.fBytesRecv; fCompress = s.fCompress; - fSecContext = s.fSecContext; fRemoteProtocol = s.fRemoteProtocol; fServType = s.fServType; fUUIDs = 0; From 9688c0d145fd8f288278f4194a7bdad528445386 Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 21:50:13 +0200 Subject: [PATCH 06/11] [net] remove deprecated TServerSocket accept options --- net/net/inc/TPServerSocket.h | 2 +- net/net/inc/TServerSocket.h | 7 +--- net/net/src/TPServerSocket.cxx | 4 +-- net/net/src/TServerSocket.cxx | 62 ++-------------------------------- 4 files changed, 6 insertions(+), 69 deletions(-) diff --git a/net/net/inc/TPServerSocket.h b/net/net/inc/TPServerSocket.h index 5272b6ad307c4..70f39d201df01 100644 --- a/net/net/inc/TPServerSocket.h +++ b/net/net/inc/TPServerSocket.h @@ -46,7 +46,7 @@ class TPServerSocket : public TServerSocket { virtual ~TPServerSocket() {} - TPSocket *Accept(UChar_t Opt = ROOT::Deprecated::kSrvNoAuth) override; + TPSocket *Accept(UChar_t opt = 0) override; ClassDefOverride(TPServerSocket,0) // Parallel server socket }; diff --git a/net/net/inc/TServerSocket.h b/net/net/inc/TServerSocket.h index 7a223b7723e89..6e03f732cf97d 100644 --- a/net/net/inc/TServerSocket.h +++ b/net/net/inc/TServerSocket.h @@ -54,7 +54,6 @@ class TServerSocket : public TSocket { TSeqCollection *fSecContexts; // List of TSecContext with cleanup info static ROOT::Deprecated::SrvAuth_t fgSrvAuthHook; static ROOT::Deprecated::SrvClup_t fgSrvAuthClupHook; - static UChar_t fgAcceptOpt; // Default accept options (DEPRECATED) TServerSocket() : fSecContexts(nullptr) {} TServerSocket(const TServerSocket &); @@ -70,7 +69,7 @@ class TServerSocket : public TSocket { Int_t backlog = kDefaultBacklog, Int_t tcpwindowsize = -1); virtual ~TServerSocket(); - virtual TSocket *Accept(UChar_t Opt = 0); + virtual TSocket *Accept(UChar_t opt = 0); TInetAddress GetLocalInetAddress() override; Int_t GetLocalPort() override; @@ -97,10 +96,6 @@ class TServerSocket : public TSocket { Int_t RecvRaw(void *, Int_t, ESendRecvOptions = kDefault) override { MayNotUse("RecvRaw(void *, Int_t, ESendRecvOptions)"); return 0; } - static UChar_t GetAcceptOptions() R__DEPRECATED(6, 42, "Socket authentication is deprecated"); - static void SetAcceptOptions(UChar_t Opt) R__DEPRECATED(6, 42, "Socket authentication is deprecated"); - static void ShowAcceptOptions() R__DEPRECATED(6, 42, "Socket authentication is deprecated"); - ClassDefOverride(TServerSocket, 0); //This class implements server sockets }; diff --git a/net/net/src/TPServerSocket.cxx b/net/net/src/TPServerSocket.cxx index 2de21d37a1860..acecb02efa681 100644 --- a/net/net/src/TPServerSocket.cxx +++ b/net/net/src/TPServerSocket.cxx @@ -93,7 +93,7 @@ TPServerSocket::TPServerSocket(const char *service, Bool_t reuse, Int_t backlog, /// In case of error 0 is returned and in case non-blocking I/O is /// enabled and no connections are available -1 is returned. -TPSocket *TPServerSocket::Accept(UChar_t Opt) +TPSocket *TPServerSocket::Accept(UChar_t opt) { TSocket *setupSocket = 0; TSocket **pSockets; @@ -102,7 +102,7 @@ TPSocket *TPServerSocket::Accept(UChar_t Opt) Int_t size, port; // wait for the incoming connections to the server and accept them - setupSocket = TServerSocket::Accept(Opt); + setupSocket = TServerSocket::Accept(opt); if (setupSocket == 0) return 0; diff --git a/net/net/src/TServerSocket.cxx b/net/net/src/TServerSocket.cxx index 2a38ddbf2ae33..b7e5f5431d28a 100644 --- a/net/net/src/TServerSocket.cxx +++ b/net/net/src/TServerSocket.cxx @@ -37,26 +37,8 @@ to the requester. The actual work is done via the TSystem class ROOT::Deprecated::SrvAuth_t TServerSocket::fgSrvAuthHook = 0; ROOT::Deprecated::SrvClup_t TServerSocket::fgSrvAuthClupHook = 0; -// Defaul options for accept -UChar_t TServerSocket::fgAcceptOpt = ROOT::Deprecated::kSrvNoAuth; - TVirtualMutex *gSrvAuthenticateMutex = 0; - -//////////////////////////////////////////////////////////////////////////////// -/// Kind of macro to parse input options -/// Modify opt according to modifier mod. - -static void SetAuthOpt(UChar_t &opt, UChar_t mod) -{ - R__LOCKGUARD2(gSrvAuthenticateMutex); - - if (!mod) return; - - if ((mod & ROOT::Deprecated::kSrvAuth)) opt |= ROOT::Deprecated::kSrvAuth; - if ((mod & ROOT::Deprecated::kSrvNoAuth)) opt &= ~ROOT::Deprecated::kSrvAuth; -} - //////////////////////////////////////////////////////////////////////////////// /// Create a server socket object for a named service. Set reuse to true /// to force reuse of the server socket (i.e. do not wait for the time @@ -193,8 +175,9 @@ TServerSocket::~TServerSocket() /// any open sockets are properly closed on program termination. /// In case of error 0 is returned and in case non-blocking I/O is /// enabled and no connections are available -1 is returned. +/// Note: opt used to pass authentication options but is currently unused. -TSocket *TServerSocket::Accept(UChar_t opt) +TSocket *TServerSocket::Accept(UChar_t /* opt */) { if (fSocket == -1) { return 0; } @@ -204,11 +187,6 @@ TSocket *TServerSocket::Accept(UChar_t opt) if (soc == -1) { delete socket; return 0; } if (soc == -2) { delete socket; return (TSocket*) -1; } - // Parse Opt - UChar_t acceptOpt = fgAcceptOpt; - SetAuthOpt(acceptOpt, opt); - Bool_t auth = (Bool_t)(acceptOpt & ROOT::Deprecated::kSrvAuth); - socket->fSocket = soc; socket->fSecContext = 0; socket->fService = fService; @@ -219,14 +197,6 @@ TSocket *TServerSocket::Accept(UChar_t opt) gROOT->GetListOfSockets()->Add(socket); } - // Perform authentication, if required - if (auth) { - if (!Authenticate(socket)) { - delete socket; - socket = 0; - } - } - return socket; } @@ -258,34 +228,6 @@ Int_t TServerSocket::GetLocalPort() return -1; } - -//////////////////////////////////////////////////////////////////////////////// -/// Return default options for Accept - -UChar_t TServerSocket::GetAcceptOptions() -{ - return fgAcceptOpt; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set default options for Accept according to modifier 'mod'. -/// Use: -/// kSrvAuth require client authentication -/// kSrvNoAuth do not require client authentication - -void TServerSocket::SetAcceptOptions(UChar_t mod) -{ - SetAuthOpt(fgAcceptOpt, mod); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Print default options for Accept. - -void TServerSocket::ShowAcceptOptions() -{ - ::Info("ShowAcceptOptions", "Use authentication: %s", (fgAcceptOpt & ROOT::Deprecated::kSrvAuth) ? "yes" : "no"); -} - //////////////////////////////////////////////////////////////////////////////// /// Check authentication request from the client on new /// open connection From 60299471b50e56e7d5dd7203d5e6770577210b27 Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 21:57:46 +0200 Subject: [PATCH 07/11] [net] remove deprecated server socket authentication --- net/net/inc/TServerSocket.h | 21 --------- net/net/src/TServerSocket.cxx | 83 ----------------------------------- 2 files changed, 104 deletions(-) diff --git a/net/net/inc/TServerSocket.h b/net/net/inc/TServerSocket.h index 6e03f732cf97d..65081a509288d 100644 --- a/net/net/inc/TServerSocket.h +++ b/net/net/inc/TServerSocket.h @@ -30,35 +30,14 @@ class TSeqCollection; -namespace ROOT::Deprecated { - -typedef Int_t (*SrvAuth_t)(TSocket *sock, const char *, const char *, - std::string&, Int_t &, Int_t &, std::string &, - TSeqCollection *); -typedef Int_t (*SrvClup_t)(TSeqCollection *); - -// These mask are globally available to manipulate the option to Accept -const UChar_t kSrvAuth = 0x1; // Require client authentication -const UChar_t kSrvNoAuth = (kSrvAuth<<4); // Force no client authentication - -} // namespace ROOT::Deprecated - -using SrvAuth_t R__DEPRECATED(6, 42, "Socket authentication is deprecated") = ROOT::Deprecated::SrvAuth_t; -using SrvClup_t R__DEPRECATED(6, 42, "Socket authentication is deprecated") = ROOT::Deprecated::SrvClup_t; -const UChar_t kSrvAuth R__DEPRECATED(6, 42, "Socket authentication is deprecated") = ROOT::Deprecated::kSrvAuth; -const UChar_t kSrvNoAuth R__DEPRECATED(6, 42, "Socket authentication is deprecated") = ROOT::Deprecated::kSrvNoAuth; - class TServerSocket : public TSocket { private: TSeqCollection *fSecContexts; // List of TSecContext with cleanup info - static ROOT::Deprecated::SrvAuth_t fgSrvAuthHook; - static ROOT::Deprecated::SrvClup_t fgSrvAuthClupHook; TServerSocket() : fSecContexts(nullptr) {} TServerSocket(const TServerSocket &); void operator=(const TServerSocket &); - Bool_t Authenticate(TSocket *); public: enum { kDefaultBacklog = 10 }; diff --git a/net/net/src/TServerSocket.cxx b/net/net/src/TServerSocket.cxx index b7e5f5431d28a..d31f9455234af 100644 --- a/net/net/src/TServerSocket.cxx +++ b/net/net/src/TServerSocket.cxx @@ -33,10 +33,6 @@ to the requester. The actual work is done via the TSystem class #include #include "TVirtualMutex.h" -// Hook to server authentication wrapper -ROOT::Deprecated::SrvAuth_t TServerSocket::fgSrvAuthHook = 0; -ROOT::Deprecated::SrvClup_t TServerSocket::fgSrvAuthClupHook = 0; - TVirtualMutex *gSrvAuthenticateMutex = 0; //////////////////////////////////////////////////////////////////////////////// @@ -152,10 +148,6 @@ TServerSocket::~TServerSocket() { R__LOCKGUARD2(gSrvAuthenticateMutex); if (fSecContexts) { - if (fgSrvAuthClupHook) { - // Cleanup the security contexts - (*fgSrvAuthClupHook)(fSecContexts); - } // Remove the list fSecContexts->Delete(); SafeDelete(fSecContexts); @@ -227,78 +219,3 @@ Int_t TServerSocket::GetLocalPort() } return -1; } - -//////////////////////////////////////////////////////////////////////////////// -/// Check authentication request from the client on new -/// open connection - -Bool_t TServerSocket::Authenticate(TSocket *sock) -{ - if (!fgSrvAuthHook) { - R__LOCKGUARD2(gSrvAuthenticateMutex); - - // Load libraries needed for (server) authentication ... - TString srvlib = "libSrvAuth"; - char *p = 0; - // The generic one - if ((p = gSystem->DynamicPathName(srvlib, kTRUE))) { - delete[] p; - if (gSystem->Load(srvlib) == -1) { - Error("Authenticate", "can't load %s",srvlib.Data()); - return kFALSE; - } - } else { - Error("Authenticate", "can't locate %s",srvlib.Data()); - return kFALSE; - } - // - // Locate SrvAuthenticate - Func_t f = gSystem->DynFindSymbol(srvlib,"SrvAuthenticate"); - if (f) - fgSrvAuthHook = (ROOT::Deprecated::SrvAuth_t)(f); - else { - Error("Authenticate", "can't find SrvAuthenticate"); - return kFALSE; - } - // - // Locate SrvAuthCleanup - f = gSystem->DynFindSymbol(srvlib,"SrvAuthCleanup"); - if (f) - fgSrvAuthClupHook = (ROOT::Deprecated::SrvClup_t)(f); - else { - Warning("Authenticate", "can't find SrvAuthCleanup"); - } - } - - TString confdir = TROOT::GetRootSys(); - if (!confdir.Length()) { - Error("Authenticate", "config dir undefined"); - return kFALSE; - } - - // dir for temporary files - TString tmpdir = TString(gSystem->TempDirectory()); - if (gSystem->AccessPathName(tmpdir, kWritePermission)) - tmpdir = TString("/tmp"); - - // Get Host name - TString openhost(sock->GetInetAddress().GetHostName()); - if (gDebug > 2) - Info("Authenticate","OpenHost = %s", openhost.Data()); - - // Run Authentication now - std::string user; - Int_t meth = -1; - Int_t auth = 0; - Int_t type = 0; - std::string ctkn = ""; - if (fgSrvAuthHook) - auth = (*fgSrvAuthHook)(sock, confdir, tmpdir, user, - meth, type, ctkn, fSecContexts); - - if (gDebug > 2) - Info("Authenticate","auth = %d, type= %d, ctkn= %s", - auth, type, ctkn.c_str()); - - return auth; -} From 2ca9e90fedb4ffbde2cc5aeedc158a90d4a2877b Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 22:09:32 +0200 Subject: [PATCH 08/11] [net] remove deprecated auth package and rpdutils --- etc/plugins/TVirtualAuth/P010_TRootAuth.C | 5 - net/CMakeLists.txt | 5 - net/auth/CMakeLists.txt | 35 - net/auth/doc/index.txt | 4 - net/auth/inc/AuthConst.h | 54 - net/auth/inc/LinkDefRoot.h | 20 - net/auth/inc/TAuthenticate.h | 226 - net/auth/inc/THostAuth.h | 119 - net/auth/inc/TRootAuth.h | 53 - net/auth/inc/TRootSecContext.h | 60 - net/auth/res/rsaaux.h | 96 - net/auth/res/rsadef.h | 122 - net/auth/res/rsafun.h | 84 - net/auth/res/rsalib.h | 62 - net/auth/src/TAuthenticate.cxx | 3427 --------------- net/auth/src/THostAuth.cxx | 681 --- net/auth/src/TRootAuth.cxx | 102 - net/auth/src/TRootSecContext.cxx | 260 -- net/auth/src/rsaaux.cxx | 1133 ----- net/auth/src/rsafun.cxx | 89 - net/auth/src/rsalib.cxx | 498 --- net/rpdutils/CMakeLists.txt | 68 - net/rpdutils/res/rpdconn.h | 220 - net/rpdutils/res/rpddefs.h | 42 - net/rpdutils/res/rpderr.h | 29 - net/rpdutils/res/rpdp.h | 188 - net/rpdutils/res/rpdpriv.h | 81 - net/rpdutils/src/DaemonUtils.cxx | 579 --- net/rpdutils/src/DaemonUtils.h | 53 - net/rpdutils/src/daemon.cxx | 198 - net/rpdutils/src/error.cxx | 125 - net/rpdutils/src/net.cxx | 586 --- net/rpdutils/src/netpar.cxx | 264 -- net/rpdutils/src/rpdconn.cxx | 1094 ----- net/rpdutils/src/rpdpriv.cxx | 384 -- net/rpdutils/src/rpdutils.cxx | 4633 --------------------- 36 files changed, 15679 deletions(-) delete mode 100644 etc/plugins/TVirtualAuth/P010_TRootAuth.C delete mode 100644 net/auth/CMakeLists.txt delete mode 100644 net/auth/doc/index.txt delete mode 100644 net/auth/inc/AuthConst.h delete mode 100644 net/auth/inc/LinkDefRoot.h delete mode 100644 net/auth/inc/TAuthenticate.h delete mode 100644 net/auth/inc/THostAuth.h delete mode 100644 net/auth/inc/TRootAuth.h delete mode 100644 net/auth/inc/TRootSecContext.h delete mode 100644 net/auth/res/rsaaux.h delete mode 100644 net/auth/res/rsadef.h delete mode 100644 net/auth/res/rsafun.h delete mode 100644 net/auth/res/rsalib.h delete mode 100644 net/auth/src/TAuthenticate.cxx delete mode 100644 net/auth/src/THostAuth.cxx delete mode 100644 net/auth/src/TRootAuth.cxx delete mode 100644 net/auth/src/TRootSecContext.cxx delete mode 100644 net/auth/src/rsaaux.cxx delete mode 100644 net/auth/src/rsafun.cxx delete mode 100644 net/auth/src/rsalib.cxx delete mode 100644 net/rpdutils/CMakeLists.txt delete mode 100644 net/rpdutils/res/rpdconn.h delete mode 100644 net/rpdutils/res/rpddefs.h delete mode 100644 net/rpdutils/res/rpderr.h delete mode 100644 net/rpdutils/res/rpdp.h delete mode 100644 net/rpdutils/res/rpdpriv.h delete mode 100644 net/rpdutils/src/DaemonUtils.cxx delete mode 100644 net/rpdutils/src/DaemonUtils.h delete mode 100644 net/rpdutils/src/daemon.cxx delete mode 100644 net/rpdutils/src/error.cxx delete mode 100644 net/rpdutils/src/net.cxx delete mode 100644 net/rpdutils/src/netpar.cxx delete mode 100644 net/rpdutils/src/rpdconn.cxx delete mode 100644 net/rpdutils/src/rpdpriv.cxx delete mode 100644 net/rpdutils/src/rpdutils.cxx diff --git a/etc/plugins/TVirtualAuth/P010_TRootAuth.C b/etc/plugins/TVirtualAuth/P010_TRootAuth.C deleted file mode 100644 index 099400ef945e5..0000000000000 --- a/etc/plugins/TVirtualAuth/P010_TRootAuth.C +++ /dev/null @@ -1,5 +0,0 @@ -void P010_TRootAuth() -{ - gPluginMgr->AddHandler("TVirtualAuth", "Root", "ROOT::Deprecated::TRootAuth", - "RootAuth", "ROOT::Deprecated::TRootAuth()"); -} diff --git a/net/CMakeLists.txt b/net/CMakeLists.txt index af04402cfd8f1..5a70324bcf0ac 100644 --- a/net/CMakeLists.txt +++ b/net/CMakeLists.txt @@ -5,11 +5,6 @@ # For the list of contributors see $ROOTSYS/README/CREDITS. add_subdirectory(net) -add_subdirectory(auth) - -if(NOT WIN32 AND ssl) - add_subdirectory(rpdutils) -endif() if(davix) add_subdirectory(davix) diff --git a/net/auth/CMakeLists.txt b/net/auth/CMakeLists.txt deleted file mode 100644 index 95f635cbb68bd..0000000000000 --- a/net/auth/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. -# All rights reserved. -# -# For the licensing terms see $ROOTSYS/LICENSE. -# For the list of contributors see $ROOTSYS/README/CREDITS. - -############################################################################ -# CMakeLists.txt file for building ROOT net/auth package -# @author Pere Mato, CERN -############################################################################ - -add_library(rsa STATIC src/rsaaux.cxx src/rsalib.cxx src/rsafun.cxx) -target_include_directories(rsa PUBLIC res) -set_property(TARGET rsa PROPERTY POSITION_INDEPENDENT_CODE ON) - -ROOT_STANDARD_LIBRARY_PACKAGE(RootAuth - HEADERS - AuthConst.h - TAuthenticate.h - THostAuth.h - TRootAuth.h - TRootSecContext.h - SOURCES - src/TAuthenticate.cxx - src/THostAuth.cxx - src/TRootAuth.cxx - src/TRootSecContext.cxx - LINKDEF - LinkDefRoot.h - DEPENDENCIES - Net - RIO -) - -target_link_libraries(RootAuth PRIVATE rsa $<$:crypt> $<$:crypt>) diff --git a/net/auth/doc/index.txt b/net/auth/doc/index.txt deleted file mode 100644 index 8da2e272b6189..0000000000000 --- a/net/auth/doc/index.txt +++ /dev/null @@ -1,4 +0,0 @@ -BEGIN_HTML -This directory contains the classes steering the authentication services available in ROOT. -See the authentication page for more details. -END_HTML diff --git a/net/auth/inc/AuthConst.h b/net/auth/inc/AuthConst.h deleted file mode 100644 index 066b938cf16fb..0000000000000 --- a/net/auth/inc/AuthConst.h +++ /dev/null @@ -1,54 +0,0 @@ -// @(#)root/auth:$Id$ -// Author: Gerardo Ganis 3/12/2003 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_AuthConst -#define ROOT_AuthConst - -////////////////////////////////////////////////////////////////////////// -// // -// AuthConst // -// // -// Const used in authentication business // -// // -////////////////////////////////////////////////////////////////////////// - -#include "RtypesCore.h" - -namespace ROOT::Deprecated { - -// Number of security levels and masks -const Int_t kMAXSEC = 6; -const Int_t kMAXSECBUF = 4096; -const Int_t kAUTH_REUSE_MSK = 0x1; -const Int_t kAUTH_CRYPT_MSK = 0x2; -const Int_t kAUTH_SSALT_MSK = 0x4; -const Int_t kAUTH_RSATY_MSK = 0x8; -const Int_t kMAXRSATRIES = 100; -const Int_t kPRIMELENGTH = 20; -const Int_t kPRIMEEXP = 40; - -} // namespace ROOT::Deprecated - -const Int_t kMAXSEC R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::kMAXSEC; -const Int_t kMAXSECBUF R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::kMAXSECBUF; -const Int_t kAUTH_REUSE_MSK R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = - ROOT::Deprecated::kAUTH_REUSE_MSK; -const Int_t kAUTH_CRYPT_MSK R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = - ROOT::Deprecated::kAUTH_CRYPT_MSK; -const Int_t kAUTH_SSALT_MSK R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = - ROOT::Deprecated::kAUTH_SSALT_MSK; -const Int_t kAUTH_RSATY_MSK R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = - ROOT::Deprecated::kAUTH_RSATY_MSK; -const Int_t kMAXRSATRIES R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::kMAXRSATRIES; -const Int_t kPRIMELENGTH R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::kPRIMELENGTH; -const Int_t kPRIMEEXP R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::kPRIMEEXP; - -#endif diff --git a/net/auth/inc/LinkDefRoot.h b/net/auth/inc/LinkDefRoot.h deleted file mode 100644 index 0fc34a9f1029d..0000000000000 --- a/net/auth/inc/LinkDefRoot.h +++ /dev/null @@ -1,20 +0,0 @@ -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifdef __CLING__ - -#pragma link off all globals; -#pragma link off all classes; -#pragma link off all functions; - -#pragma link C++ class ROOT::Deprecated::TAuthenticate; -#pragma link C++ class ROOT::Deprecated::THostAuth; -#pragma link C++ class ROOT::Deprecated::TRootAuth; -#pragma link C++ class ROOT::Deprecated::TRootSecContext; - -#endif diff --git a/net/auth/inc/TAuthenticate.h b/net/auth/inc/TAuthenticate.h deleted file mode 100644 index 6ab85d1907f1b..0000000000000 --- a/net/auth/inc/TAuthenticate.h +++ /dev/null @@ -1,226 +0,0 @@ -// @(#)root/auth:$Id$ -// Author: Fons Rademakers 26/11/2000 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_TAuthenticate -#define ROOT_TAuthenticate - - -////////////////////////////////////////////////////////////////////////// -// // -// TAuthenticate // -// // -// An authentication module for ROOT based network services, like rootd.// // -// // -////////////////////////////////////////////////////////////////////////// - -#include "TObject.h" -#include "TString.h" -#include "TList.h" -#include "TDatime.h" -#ifndef ROOT_rsafun -//#include "rsafun.h" -#endif -#include "AuthConst.h" - -class TPluginHandler; -class TSocket; -class TVirtualMutex; - -namespace ROOT::Deprecated { - -struct R__rsa_KEY; // opaque replacement for rsa_KEY -struct R__rsa_KEY_export; // opaque replacement for rsa_KEY_export -struct R__rsa_NUMBER; // opaque replacement for rsa_NUMBER - -R__EXTERN TVirtualMutex *gAuthenticateMutex; - -class TAuthenticate; -class THostAuth; -class TRootAuth; -class TRootSecContext; - -typedef Int_t (*CheckSecCtx_t)(const char *subj, ROOT::Deprecated::TRootSecContext *ctx); -typedef Int_t (*GlobusAuth_t)(ROOT::Deprecated::TAuthenticate *auth, TString &user, TString &det); -typedef Int_t (*Krb5Auth_t)(ROOT::Deprecated::TAuthenticate *auth, TString &user, TString &det, Int_t version); -typedef Int_t (*SecureAuth_t)(ROOT::Deprecated::TAuthenticate *auth, const char *user, const char *passwd, - const char *remote, TString &det, Int_t version); - -class TAuthenticate : public TObject { - -friend class ROOT::Deprecated::TRootAuth; -friend class ROOT::Deprecated::TRootSecContext; - -public: - enum ESecurity { -// clang++ 0, timeout in sec - static Int_t fgProcessID; // ID of the main thread as unique identifier - - static Bool_t CheckHost(const char *Host, const char *host); - - static void FileExpand(const char *fin, FILE *ftmp); - static void RemoveSecContext(TRootSecContext *ctx); - -public: - TAuthenticate(TSocket *sock, const char *remote, const char *proto, - const char *user = ""); - virtual ~TAuthenticate() {} - - Bool_t Authenticate(); - Int_t AuthExists(TString User, Int_t method, const char *Options, - Int_t *Message, Int_t *Rflag, CheckSecCtx_t funcheck); - void CatchTimeOut(); - Bool_t CheckNetrc(TString &user, TString &passwd); - Bool_t CheckNetrc(TString &user, TString &passwd, - Bool_t &pwhash, Bool_t srppwd); - THostAuth *GetHostAuth() const { return fHostAuth; } - const char *GetProtocol() const { return fProtocol; } - const char *GetRemoteHost() const { return fRemote; } - Int_t GetRSAKeyType() const { return fRSAKey; } - TRootSecContext *GetSecContext() const { return fSecContext; } - TSocket *GetSocket() const { return fSocket; } - const char *GetUser() const { return fUser; } - Int_t HasTimedOut() const { return fTimeOut; } - void SetRSAKeyType(Int_t key) { fRSAKey = key; } - void SetSecContext(TRootSecContext *ctx) { fSecContext = ctx; } - - static void AuthError(const char *where, Int_t error); - - static Int_t DecodeRSAPublic(const char *rsapubexport, R__rsa_NUMBER &n, - R__rsa_NUMBER &d, char **rsassl = nullptr); - - static TList *GetAuthInfo(); - static const char *GetAuthMethod(Int_t idx); - static Int_t GetAuthMethodIdx(const char *meth); - static Bool_t GetAuthReUse(); - static Int_t GetClientProtocol(); - static char *GetDefaultDetails(Int_t method, Int_t opt, const char *user); - static const char *GetDefaultUser(); - static TDatime GetGlobalExpDate(); - static Bool_t GetGlobalPwHash(); - static Bool_t GetGlobalSRPPwd(); - static const char *GetGlobalUser(); - static GlobusAuth_t GetGlobusAuthHook(); - static THostAuth *GetHostAuth(const char *host, const char *user="", - Option_t *opt = "R", Int_t *Exact = nullptr); - static const char *GetKrb5Principal(); - static Bool_t GetPromptUser(); - static Int_t GetRSAInit(); - static const char *GetRSAPubExport(Int_t key = 0); - static THostAuth *HasHostAuth(const char *host, const char *user, - Option_t *opt = "R"); - static void InitRandom(); - static void MergeHostAuthList(TList *Std, TList *New, Option_t *Opt = ""); - static char *PromptPasswd(const char *prompt = "Password: "); - static char *PromptUser(const char *remote); - static Int_t ReadRootAuthrc(); - static void RemoveHostAuth(THostAuth *ha, Option_t *opt = ""); - static Int_t SecureRecv(TSocket *Socket, Int_t dec, - Int_t KeyType, char **Out); - static Int_t SecureSend(TSocket *Socket, Int_t enc, - Int_t KeyType, const char *In); - static Int_t SendRSAPublicKey(TSocket *Socket, Int_t key = 0); - static void SetAuthReUse(Bool_t authreuse); - static void SetDefaultUser(const char *defaultuser); - static void SetGlobalExpDate(TDatime expdate); - static void SetGlobalPasswd(const char *passwd); - static void SetGlobalPwHash(Bool_t pwhash); - static void SetGlobalSRPPwd(Bool_t srppwd); - static void SetGlobalUser(const char *user); - static void SetGlobusAuthHook(GlobusAuth_t func); - static void SetKrb5AuthHook(Krb5Auth_t func); - static void SetPromptUser(Bool_t promptuser); - static void SetDefaultRSAKeyType(Int_t key); - static void SetRSAInit(Int_t init = 1); - static Int_t SetRSAPublic(const char *rsapubexport, Int_t klen); - static void SetSecureAuthHook(SecureAuth_t func); - static void SetTimeOut(Int_t to); - static void Show(Option_t *opt="S"); - - ClassDefOverride(TAuthenticate,0) // Class providing remote authentication service -}; - -} // namespace ROOT::Deprecated - -R__EXTERN TVirtualMutex *&gAuthenticateMutex R__DEPRECATED(6, 42, "the RootAuth library is deprecated"); - -using CheckSecCtx_t R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::CheckSecCtx_t; -using GlobusAuth_t R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::GlobusAuth_t; -using Krb5Auth_t R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::Krb5Auth_t; -using SecureAuth_t R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::SecureAuth_t; -using TAuthenticate R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::TAuthenticate; - -#endif diff --git a/net/auth/inc/THostAuth.h b/net/auth/inc/THostAuth.h deleted file mode 100644 index 1f324e88d53e4..0000000000000 --- a/net/auth/inc/THostAuth.h +++ /dev/null @@ -1,119 +0,0 @@ -// @(#)root/auth:$Id$ -// Author: G. Ganis 19/03/2003 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_THostAuth -#define ROOT_THostAuth - - -////////////////////////////////////////////////////////////////////////// -// // -// THostAuth // -// // -// Contains details about host-specific authentication methods and the // -// result of their application // -// Used by TAuthenticate // -// // -////////////////////////////////////////////////////////////////////////// - -#include "TObject.h" -#include "TString.h" -#include "TList.h" -#include "TRootSecContext.h" -#include "AuthConst.h" - -#include "TSecContext.h" // for kROOTTZERO. - -namespace ROOT::Deprecated { - -class THostAuth : public TObject { - -private: - TString fHost; // Host - Char_t fServer; // Server (kSOCKD,kROOTD) - TString fUser; // Username - Int_t fNumMethods; // Number of AuthMethods - Int_t fMethods[kMAXSEC]; // AuthMethods - TString fDetails[kMAXSEC]; // AuthDetails - Int_t fSuccess[kMAXSEC]; // Statistics of successful attempts / per method - Int_t fFailure[kMAXSEC]; // Statistics of failed attempts / per method - Bool_t fActive; // Flag used in cleaning/reset - - TList *fSecContexts; // List of TSecContexts related to this THostAuth - - void Create(const char *host, const char *user, Int_t nmeth = 0, - Int_t *authmeth = nullptr, char **details = nullptr); -public: - - THostAuth(); - THostAuth(const char *host, const char *user, - Int_t nmeth = 0, Int_t *authmeth = nullptr, char **details = nullptr); - THostAuth(const char *host, Int_t server, const char *user, - Int_t nmeth = 0, Int_t *authmeth = nullptr, char **details = nullptr); - THostAuth(const char *host, const char *user, Int_t authmeth, - const char *details); - THostAuth(const char *host, Int_t server, const char *user, Int_t authmeth, - const char *details); - THostAuth(THostAuth &ha); - - virtual ~THostAuth(); - - void AsString(TString &out) const; - - Int_t NumMethods() const { return fNumMethods; } - Int_t GetMethod(Int_t idx) const { return fMethods[idx]; } - Bool_t HasMethod(Int_t level, Int_t *pos = nullptr); - void AddMethod(Int_t level, const char *details = nullptr); - void RemoveMethod(Int_t level); - void ReOrder(Int_t nmet, Int_t *fmet); - void Update(THostAuth *ha); - void SetFirst(Int_t level); - void AddFirst(Int_t level, const char *details = nullptr); - void SetLast(Int_t level); - void CountFailure(Int_t level); - void CountSuccess(Int_t level); - Int_t GetFailure(Int_t idx) const { return fFailure[idx]; } - Int_t GetSuccess(Int_t idx) const { return fSuccess[idx]; } - Bool_t IsActive() const { return fActive; } - void DeActivate() { fActive = kFALSE; } - void Activate() { fActive = kTRUE; } - void Reset(); - - const char *GetDetails(Int_t level); - const char *GetDetailsByIdx(Int_t idx) const { return fDetails[idx]; } - void SetDetails(Int_t level, const char *details); - - const char *GetHost() const { return fHost; } - Int_t GetServer() const { return (Int_t)fServer; } - const char *GetUser() const { return fUser; } - - void SetHost(const char *host) { fHost = host; } - void SetServer(Int_t server) { fServer = (Char_t)server; } - void SetUser(const char *user) { fUser = user; } - - TList *Established() const { return fSecContexts; } - void SetEstablished(TList *nl) { fSecContexts = nl; } - - void Print(Option_t *option = "") const override; - void PrintEstablished() const; - - TRootSecContext *CreateSecContext(const char *user, const char *host, Int_t meth, - Int_t offset, const char *details, - const char *token, TDatime expdate = kROOTTZERO, - void *ctx = nullptr, Int_t key = -1); - - ClassDefOverride(THostAuth,1) // Class providing host specific authentication information -}; - -} // namespace ROOT::Deprecated - -using THostAuth R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::THostAuth; - -#endif diff --git a/net/auth/inc/TRootAuth.h b/net/auth/inc/TRootAuth.h deleted file mode 100644 index e9c96c8aa6954..0000000000000 --- a/net/auth/inc/TRootAuth.h +++ /dev/null @@ -1,53 +0,0 @@ -// @(#)root/auth:$Id$ -// Author: Gerardo Ganis 08/07/05 - -/************************************************************************* - * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_TRootAuth -#define ROOT_TRootAuth - - -////////////////////////////////////////////////////////////////////////// -// // -// TRootAuth // -// // -// TVirtualAuth implementation based on the old client authentication // -// code. // -// // -////////////////////////////////////////////////////////////////////////// - -#include "TVirtualAuth.h" -#include "Rtypes.h" - -class TSocket; - -namespace ROOT::Deprecated { - -class TSecContext; - -class TRootAuth : public TVirtualAuth { - -public: - TRootAuth() {} - virtual ~TRootAuth() {} - - TSecContext *Authenticate(TSocket *, const char *host, - const char *user, Option_t *options = "") override; - Int_t ClientVersion() override; - void ErrorMsg(const char *where, Int_t ecode = -1) override; - const char *Name() override { return "Root"; } - - ClassDefOverride(TRootAuth,0) // client auth interface -}; - -} // namespace ROOT::Deprecated - -using TRootAuth R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::TRootAuth; - -#endif diff --git a/net/auth/inc/TRootSecContext.h b/net/auth/inc/TRootSecContext.h deleted file mode 100644 index 7cb0ca5306291..0000000000000 --- a/net/auth/inc/TRootSecContext.h +++ /dev/null @@ -1,60 +0,0 @@ -// @(#)root/auth:$Id$ -// Author: G. Ganis 08/07/2005 - -/************************************************************************* - * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_TRootSecContext -#define ROOT_TRootSecContext - - -////////////////////////////////////////////////////////////////////////// -// // -// TRootSecContext // -// // -// Special implementation of TSecContext // -// // -////////////////////////////////////////////////////////////////////////// - -#include "TAuthenticate.h" -#include "TSecContext.h" - -namespace ROOT::Deprecated { - -class TRootSecContext : public TSecContext { - -private: - Int_t fRSAKey; // Type of RSA key used - - Bool_t CleanupSecContext(Bool_t all) override; - -public: - - TRootSecContext(const char *url, Int_t meth, Int_t offset, - const char *id, const char *token, - TDatime expdate = kROOTTZERO, void *ctx = nullptr, Int_t key = 1); - TRootSecContext(const char *user, const char *host, Int_t meth, Int_t offset, - const char *id, const char *token, - TDatime expdate = kROOTTZERO, void *ctx = nullptr, Int_t key = 1); - virtual ~TRootSecContext(); - - const char *AsString(TString &out) override; - - void DeActivate(Option_t *opt = "CR") override; - Int_t GetRSAKey() const { return fRSAKey; } - - void Print(Option_t *option = "F") const override; - - ClassDefOverride(TRootSecContext,0) // Class providing host specific authentication information -}; - -} - -using TRootSecContext R__DEPRECATED(6, 42, "the RootAuth library is deprecated") = ROOT::Deprecated::TRootSecContext; - -#endif diff --git a/net/auth/res/rsaaux.h b/net/auth/res/rsaaux.h deleted file mode 100644 index 823a4a0a3617e..0000000000000 --- a/net/auth/res/rsaaux.h +++ /dev/null @@ -1,96 +0,0 @@ -/* @(#)root/auth:$Id$ */ -/* Author: Martin Nicolay 22/11/1988 */ - -/****************************************************************************** -Copyright (C) 2006 Martin Nicolay - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later -version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free -Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, -MA 02110-1301 USA -******************************************************************************/ - -/******************************************************************************* -* * -* Simple RSA public key code. * -* Adaptation in library for ROOT by G. Ganis, July 2003 * -* (gerardo.ganis@cern.ch) * -* * -* Header used by internal rsa functions * -* * -*******************************************************************************/ - -#ifndef _RSAAUX_H -#define _RSAAUX_H - -#include "rsadef.h" - -extern rsa_NUMBER a_one,a_two; - -/* - * Prototypes - */ - -void a_add(rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*); -void a_assign(rsa_NUMBER*, rsa_NUMBER*); -int a_cmp(rsa_NUMBER*, rsa_NUMBER*); -void a_div(rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*); -void a_div2(rsa_NUMBER*); -void a_ggt(rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*); -void a_imult(rsa_NUMBER*, rsa_INT, rsa_NUMBER*); -void a_mult(rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*); -void a_sub(rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*); -void m_init(rsa_NUMBER*, rsa_NUMBER*); -void m_add(rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*); -void m_mult(rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*); -void m_exp(rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*); -int n_bits(rsa_NUMBER*, int); -void n_div(rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*); -int n_cmp(rsa_INT*, rsa_INT*, int); -int n_mult(rsa_INT*, rsa_INT, rsa_INT*, int); -int n_sub(rsa_INT*, rsa_INT*, rsa_INT*, int, int); -int n_bitlen(rsa_NUMBER*); - - - -/****************** - * prim.h * - ******************/ - -int p_prim(rsa_NUMBER*, int); -void inv(rsa_NUMBER*, rsa_NUMBER*, rsa_NUMBER*); - - -/****************** - * rnd.h * - ******************/ - -void gen_number(int, rsa_NUMBER*); -void init_rnd(void); - - -/****************** - * aux.h * - ******************/ - -void do_crypt(char *, char *, int, rsa_NUMBER *); - -/* -int get_clear(char *, FILE *); -int get_enc(char *, FILE *); -int put_clear(char *, FILE *); -int put_enc(char *, FILE *); -*/ - -#endif diff --git a/net/auth/res/rsadef.h b/net/auth/res/rsadef.h deleted file mode 100644 index 8f0254f375256..0000000000000 --- a/net/auth/res/rsadef.h +++ /dev/null @@ -1,122 +0,0 @@ -/* @(#)root/auth:$Id$ */ -/* Author: Martin Nicolay 22/11/1988 */ - -/****************************************************************************** -Copyright (C) 2006 Martin Nicolay - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later -version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free -Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, -MA 02110-1301 USA -******************************************************************************/ - -/******************************************************************************* -* * -* Simple RSA public key code. * -* Adaptation in library for ROOT by G. Ganis, July 2003 * -* (gerardo.ganis@cern.ch) * -* * -* Header used by internal rsa functions * -* * -*******************************************************************************/ - -#ifndef _RSADEF_H -#define _RSADEF_H - -typedef unsigned short rsa_INT; /* muss MAXINT fassen */ -typedef unsigned long rsa_LONG; /* muss (MAXINT+1)^2 -1 fassen */ - -/* - * (MAXINT+1)-adic Zahlen - */ - -/* - * MAXINT Maximale Zahl pro Element (muss int sein) - * MAXBIT Maximales Bit von MAXINT - * LOWBITS Anzahl der consekutiven low Bits von MAXINT - * HIGHBIT Hoechsten Bit von MAXINT - * TOINT muss (INT)( (x) % MAXINT) ergeben - * MAXLEN Laenge der INT Array in jeder NUMBER - */ - -#define rsa_MAXINT 0xFFFF - -#if rsa_MAXINT == 99 -#define rsa_MAXBIT 7 -#define rsa_LOWBITS 2 -#endif -#if rsa_MAXINT == 9 -#define rsa_MAXBIT 4 -#define rsa_LOWBITS 1 -#endif -#if rsa_MAXINT == 1 -#define rsa_MAXBIT 1 -#endif -#if rsa_MAXINT == 0xFF -#define rsa_MAXBIT 8 -#define rsa_TOINT(x) ((rsa_INT)(x)) /* ACHTUNG !!!!! */ -#endif -#if rsa_MAXINT == 0xFFFF -#define rsa_MAXBIT 16 -#define rsa_TOINT(x) ((rsa_INT)(x)) /* ACHTUNG !!!!! */ -#endif - -#ifndef rsa_MAXBIT -#include "<< ERROR: rsa_MAXBIT must be defined >>" -#endif -#ifndef rsa_LOWBITS -#if rsa_MAXINT == (1 << rsa_MAXBIT) - 1 -#define rsa_LOWBITS rsa_MAXBIT -#else -#include "<< ERROR: rsa_LOWBITS must be defined >>" -#endif -#endif - -#define rsa_MAXLEN (300*8/(rsa_MAXBIT + 1)) -#define rsa_STRLEN (rsa_MAXLEN*rsa_MAXBIT/4) -#define rsa_HIGHBIT (1 << (rsa_MAXBIT-1) ) - -#if rsa_LOWBITS == rsa_MAXBIT -#define rsa_DIVMAX1(x) ((x) >> rsa_MAXBIT) -#define rsa_MODMAX1(x) ((x) & rsa_MAXINT) -#define rsa_MULMAX1(x) ((x) << rsa_MAXBIT) -#else -#define rsa_DIVMAX1(x) ((x) / (rsa_MAXINT+1)) -#define rsa_MODMAX1(x) ((x) % (rsa_MAXINT+1)) -#define rsa_MULMAX1(x) ((x) * (unsigned)(rsa_MAXINT+1)) -#endif - -#ifndef rsa_TOINT -#define rsa_TOINT(x) ((rsa_INT)rsa_MODMAX1(x)) -#endif - -typedef struct { - int n_len; /* Hoechster benutzter Index */ - rsa_INT n_part[rsa_MAXLEN]; -} rsa_NUMBER; - -#define rsa_NUM0P ((rsa_NUMBER *)0) /* Abkuerzung */ - -/* Key structures */ -typedef struct { - rsa_NUMBER n; /* modulus */ - rsa_NUMBER e; /* private or public exponent */ -} rsa_KEY; -typedef struct { - int len; /* length of 'data' in bytes */ - char *keys; /* 'HEX[n]#HEX[d]\0' */ -} rsa_KEY_export; - - -#endif diff --git a/net/auth/res/rsafun.h b/net/auth/res/rsafun.h deleted file mode 100644 index 4bf99869b2965..0000000000000 --- a/net/auth/res/rsafun.h +++ /dev/null @@ -1,84 +0,0 @@ -/* @(#)root/auth:$Id$ */ -/* Author: Martin Nicolay 22/11/1988 */ - -/****************************************************************************** -Copyright (C) 2006 Martin Nicolay - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later -version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free -Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, -MA 02110-1301 USA -******************************************************************************/ - -/******************************************************************************* -* * -* Simple RSA public key code. * -* Adaptation in library for ROOT by G. Ganis, July 2003 * -* (gerardo.ganis@cern.ch) * -* * -* Header used by internal rsa functions * -* * -*******************************************************************************/ - -#include - -#ifndef ROOT_rsafun -#define ROOT_rsafun - -#include "rsadef.h" - - -typedef rsa_NUMBER (*RSA_genprim_t)(int, int); -typedef int (*RSA_genrsa_t)(rsa_NUMBER, rsa_NUMBER, rsa_NUMBER *, rsa_NUMBER *, rsa_NUMBER *); -typedef int (*RSA_encode_t)(char *, int, rsa_NUMBER, rsa_NUMBER); -typedef int (*RSA_decode_t)(char *, int, rsa_NUMBER, rsa_NUMBER); -typedef int (*RSA_num_sput_t)(rsa_NUMBER*, char*, int ); -typedef int (*RSA_num_fput_t)(rsa_NUMBER*, FILE* ); -typedef int (*RSA_num_sget_t)(rsa_NUMBER*, char* ); -typedef int (*RSA_num_fget_t)(rsa_NUMBER*, FILE* ); -typedef void (*RSA_assign_t)(rsa_NUMBER *, rsa_NUMBER *); -typedef int (*RSA_cmp_t)(rsa_NUMBER *, rsa_NUMBER *); - - -class TRSA_fun { - -private: - static RSA_genprim_t fg_rsa_genprim; - static RSA_genrsa_t fg_rsa_genrsa; - static RSA_encode_t fg_rsa_encode; - static RSA_decode_t fg_rsa_decode; - static RSA_num_sput_t fg_rsa_num_sput; - static RSA_num_fput_t fg_rsa_num_fput; - static RSA_num_sget_t fg_rsa_num_sget; - static RSA_num_fget_t fg_rsa_num_fget; - static RSA_assign_t fg_rsa_assign; - static RSA_cmp_t fg_rsa_cmp; - -public: - static RSA_genprim_t RSA_genprim(); - static RSA_genrsa_t RSA_genrsa(); - static RSA_encode_t RSA_encode(); - static RSA_decode_t RSA_decode(); - static RSA_num_sput_t RSA_num_sput(); - static RSA_num_fput_t RSA_num_fput(); - static RSA_num_sget_t RSA_num_sget(); - static RSA_num_fget_t RSA_num_fget(); - static RSA_assign_t RSA_assign(); - static RSA_cmp_t RSA_cmp(); - - TRSA_fun(RSA_genprim_t, RSA_genrsa_t, RSA_encode_t, RSA_decode_t, - RSA_num_sput_t, RSA_num_fput_t, RSA_num_sget_t, RSA_num_fget_t, RSA_assign_t, RSA_cmp_t); -}; - -#endif diff --git a/net/auth/res/rsalib.h b/net/auth/res/rsalib.h deleted file mode 100644 index b1a463e7804e5..0000000000000 --- a/net/auth/res/rsalib.h +++ /dev/null @@ -1,62 +0,0 @@ -/* @(#)root/auth:$Id$ */ -/* Author: Martin Nicolay 22/11/1988 */ - -/****************************************************************************** -Copyright (C) 2006 Martin Nicolay - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later -version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free -Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, -MA 02110-1301 USA -******************************************************************************/ - -/******************************************************************************* -* * -* Simple RSA public key code. * -* Adaptation in library for ROOT by G. Ganis, July 2003 * -* (gerardo.ganis@cern.ch) * -* * -* Header used by internal rsa functions * -* * -*******************************************************************************/ - -#ifndef _RSALIB_H -#define _RSALIB_H - -#include "rsadef.h" - -#include - -rsa_NUMBER rsa_genprim(int, int); -int rsa_genrsa(rsa_NUMBER, rsa_NUMBER, rsa_NUMBER *, rsa_NUMBER *, rsa_NUMBER *); -int rsa_encode(char *, int, rsa_NUMBER, rsa_NUMBER); -int rsa_decode(char *, int, rsa_NUMBER, rsa_NUMBER); - -int rsa_encode_size(rsa_NUMBER); - -/****************** - * nio.h * - ******************/ - -int rsa_cmp( rsa_NUMBER*, rsa_NUMBER* ); -void rsa_assign( rsa_NUMBER*, rsa_NUMBER* ); - -int rsa_num_sput( rsa_NUMBER*, char*, int ); -int rsa_num_fput( rsa_NUMBER*, FILE* ); -int rsa_num_sget( rsa_NUMBER*, char* ); -int rsa_num_fget( rsa_NUMBER*, FILE* ); - -#endif - - diff --git a/net/auth/src/TAuthenticate.cxx b/net/auth/src/TAuthenticate.cxx deleted file mode 100644 index 17f020c054677..0000000000000 --- a/net/auth/src/TAuthenticate.cxx +++ /dev/null @@ -1,3427 +0,0 @@ -// @(#)root/auth:$Id: f2cfa663e232707e1201467b5805ff1d13575326 $ -// Author: Fons Rademakers 26/11/2000 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// TAuthenticate // -// // -// An authentication module for ROOT based network services, like rootd // // -// // -////////////////////////////////////////////////////////////////////////// - -#include "RConfigure.h" - -#include "TAuthenticate.h" -#include "TApplication.h" -#include "THostAuth.h" -#include "TRootSecContext.h" -#include "TPluginManager.h" -#include "TMessage.h" -#include "TSystem.h" -#include "TError.h" -#include "Getline.h" -#include "TROOT.h" -#include "TEnv.h" -#include "TList.h" -#include "NetErrors.h" -#include "TRegexp.h" -#include "TSocket.h" -#include "TVirtualMutex.h" -#include "TTimer.h" -#include "strlcpy.h" -#include "snprintf.h" - -#include "rsafun.h" - -#ifndef R__LYNXOS -#include -#endif -#include -#include -#include -#if !defined(R__WIN32) && !defined(R__MACOSX) && !defined(R__FBSD) && \ - !defined(R__OBSD) -#include -#endif -#ifdef WIN32 -# include -#endif /* WIN32 */ -#if defined(R__LINUX) || defined(R__FBSD) || defined(R__OBSD) -# include -#endif -#include -#ifndef WIN32 -# include -#endif /* WIN32 */ - -#if defined(R__MACOSX) -extern "C" char *crypt(const char *, const char *); -#endif - -#ifdef R__SSL -// SSL specific headers -# include -# include -# include -# include -# include -# include -# include -#endif - -#ifdef R__SSL - static BF_KEY fgBFKey; // Blowfish symmetric key -#endif - -namespace ROOT::Deprecated { - -struct R__rsa_KEY: rsa_KEY { R__rsa_KEY(): rsa_KEY() {} }; -struct R__rsa_KEY_export: rsa_KEY_export {}; -struct R__rsa_NUMBER: rsa_NUMBER {}; - -// Statics initialization -TList *TAuthenticate::fgAuthInfo = 0; -TString TAuthenticate::fgAuthMeth[] = { "UsrPwd", "Unsupported", "Unsupported", - "Unsupported", "Unsupported", "Unsupported" }; -Bool_t TAuthenticate::fgAuthReUse; -TString TAuthenticate::fgDefaultUser; -TDatime TAuthenticate::fgExpDate; -TDatime TAuthenticate::fgLastAuthrc; // Time of last reading of fgRootAuthrc -TString TAuthenticate::fgPasswd; -TPluginHandler *TAuthenticate::fgPasswdDialog = (TPluginHandler *)(-1); -Bool_t TAuthenticate::fgPromptUser; -Bool_t TAuthenticate::fgPwHash; -Bool_t TAuthenticate::fgReadHomeAuthrc = kTRUE; // on/off search for $HOME/.rootauthrc -TString TAuthenticate::fgRootAuthrc; // Path to last rootauthrc-like file read -Int_t TAuthenticate::fgRSAKey = -1; // Default RSA key type to be used -Int_t TAuthenticate::fgRSAInit = 0; -R__rsa_KEY TAuthenticate::fgRSAPriKey; -R__rsa_KEY_export R__fgRSAPubExport[2] = {{}, {}}; -R__rsa_KEY_export* TAuthenticate::fgRSAPubExport = R__fgRSAPubExport; -R__rsa_KEY TAuthenticate::fgRSAPubKey; -SecureAuth_t TAuthenticate::fgSecAuthHook; -TString TAuthenticate::fgUser; -Bool_t TAuthenticate::fgUsrPwdCrypt; -Int_t TAuthenticate::fgLastError = -1; -Int_t TAuthenticate::fgAuthTO = -2; // Timeout value - -// ID of the main thread as unique identifier -Int_t TAuthenticate::fgProcessID = -1; - -TVirtualMutex *gAuthenticateMutex = 0; - -} // namespace ROOT::Deprecated - -TVirtualMutex *&gAuthenticateMutex = ROOT::Deprecated::gAuthenticateMutex; - -// Standard version of Sec Context match checking -static Int_t StdCheckSecCtx(const char *, ROOT::Deprecated::TRootSecContext *); - - - -//////////////////////////////////////////////////////////////////////////////// -/// rand() implementation using /udev/random or /dev/random, if available - -static int auth_rand() -{ -#ifndef WIN32 - int frnd = open("/dev/urandom", O_RDONLY); - if (frnd < 0) frnd = open("/dev/random", O_RDONLY); - int r; - if (frnd >= 0) { - ssize_t rs = read(frnd, (void *) &r, sizeof(int)); - close(frnd); - if (r < 0) r = -r; - if (rs == sizeof(int)) return r; - } - Printf("+++ERROR+++ : auth_rand: neither /dev/urandom nor /dev/random are available or readable!"); - struct timeval tv; - if (gettimeofday(&tv,0) == 0) { - int t1, t2; - memcpy((void *)&t1, (void *)&tv.tv_sec, sizeof(int)); - memcpy((void *)&t2, (void *)&tv.tv_usec, sizeof(int)); - r = t1 + t2; - if (r < 0) r = -r; - return r; - } - return -1; -#else - // No special random device available: use rand() - return rand(); -#endif -} - -//////////////////////////////////////////////////////////////////////////////// -/// Create authentication object. - -ROOT::Deprecated::TAuthenticate::TAuthenticate(TSocket *sock, const char *remote, const char *proto, const char *user) -{ - if (gDebug > 2 && gAuthenticateMutex) - Info("Authenticate", "locking mutex (pid: %d)",gSystem->GetPid()); - R__LOCKGUARD2(gAuthenticateMutex); - - // Use the ID of the starting thread as unique identifier - if (fgProcessID < 0) - fgProcessID = gSystem->GetPid(); - - if (fgAuthTO == -2) - fgAuthTO = gEnv->GetValue("Auth.Timeout",-1); - - fSocket = sock; - fRemote = remote; - fHostAuth = 0; - fVersion = 5; // The latest, by default - fSecContext = 0; - - if (gDebug > 2) - Info("TAuthenticate", "Enter: local host: %s, user is: %s (proto: %s)", - gSystem->HostName(), user, proto); - - // Set protocol string. - // Check if version should be different ... - char *pdd; - Int_t servtype = TSocket::kSOCKD; - if (proto && strlen(proto) > 0) { - char *sproto = StrDup(proto); - if ((pdd = strstr(sproto, ":")) != 0) { - int rproto = atoi(pdd + 1); - *pdd = '\0'; - if (strstr(sproto, "root") != 0) { - if (rproto < 12 ) { - fVersion = 4; - if (rproto < 11 ) { - fVersion = 3; - if (rproto < 9 ) { - fVersion = 2; - if (rproto < 8) { - fVersion = 1; - if (rproto < 6) - fVersion = 0; - } - } - } - } - servtype = TSocket::kROOTD; - } - if (gDebug > 3) - Info("TAuthenticate", - "service: %s (remote protocol: %d): fVersion: %d", sproto, - rproto, fVersion); - } - fProtocol = sproto; - delete [] sproto; - } - - // Check or get user name - fUser = ""; - TString checkUser; - if (user && strlen(user) > 0) { - fUser = user; - checkUser = user; - } else { - UserGroup_t *u = gSystem->GetUserInfo(); - if (u) - checkUser = u->fUser; - delete u; - } - fPasswd = ""; - fPwHash = kFALSE; - - // Type of RSA key - if (fgRSAKey < 0) { - fgRSAKey = 0; // Default key -#ifdef R__SSL - // Another choice possible: check user preferences - if (gEnv->GetValue("RSA.KeyType",0) == 1) - fgRSAKey = 1; -#endif - } - // This is the key actually used: we propose the default - // to the server, and behave according to its reply - fRSAKey = fgRSAKey; - if (gDebug > 3) - Info("TAuthenticate","RSA key: default type %d", fgRSAKey); - - // RSA key generation (one per session) - if (!fgRSAInit) { - GenRSAKeys(); - fgRSAInit = 1; - } - - // Check and save the host FQDN ... - TString fqdn; - TInetAddress addr = gSystem->GetHostByName(fRemote); - if (addr.IsValid()) - fqdn = addr.GetHostName(); - TString fqdnsrv; - fqdnsrv.Form("%s:%d",fqdn.Data(),servtype); - - // Read directives from files; re-read if files have changed - TAuthenticate::ReadRootAuthrc(); - - if (gDebug > 3) { - Info("TAuthenticate", - "number of HostAuth Instantiations in memory: %d", - GetAuthInfo()->GetSize()); - TAuthenticate::Show("H"); - TAuthenticate::Show("P"); - } - - // Check the list of auth info for already loaded info about this host - fHostAuth = GetHostAuth(fqdnsrv, checkUser); - - // - // If generic THostAuth (i.e. with wild card or user == any) - // make a personalized memory copy of this THostAuth - if (strchr(fHostAuth->GetHost(),'*') || strchr(fHostAuth->GetHost(),'*') || - fHostAuth->GetServer() == -1 ) { - fHostAuth = new THostAuth(*fHostAuth); - fHostAuth->SetHost(fqdn); - fHostAuth->SetUser(checkUser); - fHostAuth->SetServer(servtype); - } - - // If a specific method has been requested via the protocol - // set it as first - Int_t sec = -1; - TString tmp = fProtocol; - tmp.ReplaceAll("root",4,"",0); - tmp.ReplaceAll("sock",4,"",0); - if (!strncmp(tmp.Data(),"up",2)) - sec = 0; - else if (!strncmp(tmp.Data(),"s",1)) - sec = 1; - else if (!strncmp(tmp.Data(),"k",1)) - sec = 2; - else if (!strncmp(tmp.Data(),"g",1)) - sec = 3; - else if (!strncmp(tmp.Data(),"h",1)) - sec = 4; - else if (!strncmp(tmp.Data(),"ug",2)) - sec = 5; - if (sec > -1 && sec < kMAXSEC) { - if (fHostAuth->HasMethod(sec)) { - fHostAuth->SetFirst(sec); - } else { - char *dtmp = GetDefaultDetails(sec, 1, checkUser); - TString det(dtmp); - fHostAuth->AddFirst(sec, det); - if (dtmp) - delete [] dtmp; - } - } - - // This is what we have in memory - if (gDebug > 3) { - TIter next(fHostAuth->Established()); - TRootSecContext *ctx; - while ((ctx = (TRootSecContext *) next())) - ctx->Print("0"); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Called in connection with a timer timeout - -void ROOT::Deprecated::TAuthenticate::CatchTimeOut() -{ - Info("CatchTimeOut", "%d sec timeout expired (protocol: %s)", - fgAuthTO, fgAuthMeth[fSecurity].Data()); - - fTimeOut = 1; - if (fSocket) - fSocket->Close("force"); - - return; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Authenticate to remote rootd server. Return kTRUE if -/// authentication succeeded. - -Bool_t ROOT::Deprecated::TAuthenticate::Authenticate() -{ - if (gDebug > 2 && gAuthenticateMutex) - Info("Authenticate", "locking mutex (pid: %d)",gSystem->GetPid()); - R__LOCKGUARD2(gAuthenticateMutex); - - Bool_t rc = kFALSE; - Int_t st = -1; - Int_t remMeth = 0, rMth[kMAXSEC], tMth[kMAXSEC] = {0}; - Int_t meth = 0; - char noSupport[80] = { 0 }; - char triedMeth[80] = { 0 }; - Int_t ntry = 0; - - TString user, passwd; - Bool_t pwhash; - - if (gDebug > 2) - Info("Authenticate", "enter: fUser: %s", fUser.Data()); - - // - // Setup timeout timer, if required - TTimer *alarm = 0; - if (fgAuthTO > 0) { - alarm = new TTimer(0, kFALSE); - alarm->SetInterruptSyscalls(); - // The method CatchTimeOut will be called at timeout - alarm->Connect("Timeout()", "TAuthenticate", this, "CatchTimeOut()"); - } - -negotia: - st = -1; - tMth[meth] = 1; - ntry++; - if (gDebug > 2) - Info("Authenticate", "try #: %d", ntry); - - user = ""; - passwd = ""; - pwhash = kFALSE; - - // Security level from the list (if not in cleanup mode ...) - fSecurity = (ESecurity) fHostAuth->GetMethod(meth); - fDetails = fHostAuth->GetDetails((Int_t) fSecurity); - if (gDebug > 2) - Info("Authenticate", - "trying authentication: method:%d, default details:%s", - fSecurity, fDetails.Data()); - - // Keep track of tried methods in a list - if (triedMeth[0] != '\0') - (void) strlcat(triedMeth, " ", sizeof(triedMeth) - 1); - - (void) strlcat(triedMeth, fgAuthMeth[fSecurity].Data(), sizeof(triedMeth) - 1); - - // Set environments - SetEnvironment(); - - // - // Reset timeout variables and start timer - fTimeOut = 0; - if (fgAuthTO > 0 && alarm) { - alarm->Start(fgAuthTO*1000, kTRUE); - } - - // Auth calls depend of fSec - if (fSecurity == kClear) { - - rc = kFALSE; - - // UsrPwd Authentication - user = fgDefaultUser; - if (user != "") - CheckNetrc(user, passwd, pwhash, kFALSE); - if (passwd == "") { - if (fgPromptUser) { - char *u = PromptUser(fRemote); - user = u; - delete[] u; - } - rc = GetUserPasswd(user, passwd, pwhash, kFALSE); - } - fUser = user; - fPasswd = passwd; - - if (!rc) { - - if (fUser != "root") - st = ClearAuth(user, passwd, pwhash); - } else { - Error("Authenticate", - "unable to get user name for UsrPwd authentication"); - } - - } - - // Stop timer - if (alarm) alarm->Stop(); - - // Flag timeout condition - st = (fTimeOut > 0) ? -3 : st; - - // - // Analyse the result now ... - // Type of action after the analysis: - // 0 = return, 1 = negotiation, 2 = send kROOTD_BYE + 3, - // 3 = print failure and return - Int_t action = 0; - Int_t nmet = fHostAuth->NumMethods(); - Int_t remloc = nmet - ntry; - if (gDebug > 0) - Info("Authenticate","remloc: %d, ntry: %d, meth: %d, fSecurity: %d", - remloc, ntry, meth, fSecurity); - Int_t kind, stat; - switch (st) { - - case 1: - // - // Success - fHostAuth->CountSuccess((Int_t)fSecurity); - if (gDebug > 2) - fSecContext->Print(); - if (fSecContext->IsActive()) - fSecContext->AddForCleanup(fSocket->GetPort(), - fSocket->GetRemoteProtocol(),fSocket->GetServType()); - rc = kTRUE; - break; - - case 0: - // - // Failure - fHostAuth->CountFailure((Int_t)fSecurity); - if (fVersion < 2) { - // - // Negotiation not supported by old daemons ... - if (gDebug > 2) - Info("Authenticate", - "negotiation not supported remotely: try next method, if any"); - if (meth < nmet - 1) { - meth++; - action = 1; - } else { - action = 2; - } - rc = kFALSE; - break; - } - // - // Attempt negotiation ... - if (fSocket->Recv(stat, kind) < 0) { - action = 0; - rc = kFALSE; - } - if (gDebug > 2) - Info("Authenticate", - "after failed attempt: kind= %d, stat= %d", kind, stat); - if (kind == kROOTD_ERR) { - action = 2; - rc = kFALSE; - } else if (kind == kROOTD_NEGOTIA) { - if (stat > 0) { - int len = 3 * stat; - char *answer = new char[len]; - int nrec = fSocket->Recv(answer, len, kind); // returns user - if (nrec < 0) { - delete[] answer; // delete buffer while it exit switch() scope - action = 0; - rc = kFALSE; - break; - } - if (kind != kMESS_STRING) - Warning("Authenticate", - "strings with accepted methods not received (%d:%d)", - kind, nrec); - remMeth = - sscanf(answer, "%d %d %d %d %d %d", &rMth[0], &rMth[1], - &rMth[2], &rMth[3], &rMth[4], &rMth[5]); - if (gDebug > 0 && remloc > 0) - Info("Authenticate", - "remotely allowed methods not yet tried: %s", - answer); - delete[] answer; - } else if (stat == 0) { - Info("Authenticate", - "no more methods accepted remotely to be tried"); - action = 3; - rc = kFALSE; - break; - } - // If no more local methods, return - if (remloc < 1) { - action = 2; - rc = kFALSE; - break; - } - // Look if a non-tried method matches - int i, j; - std::string available{}; - Bool_t methfound = kFALSE; - for (i = 0; i < remMeth; i++) { - for (j = 0; j < nmet; j++) { - if (fHostAuth->GetMethod(j) == rMth[i] && tMth[j] == 0) { - meth = j; - action = 1; - methfound = kTRUE; - break; - } - if (i == 0) - available += " " + std::to_string(fHostAuth->GetMethod(j)); - } - if (methfound) break; - } - if (methfound) break; - // - // No method left to be tried: notify and exit - if (gDebug > 0) - Warning("Authenticate", "no match with those locally available: %s", available.c_str()); - action = 2; - rc = kFALSE; - break; - } else { // unknown message code at this stage - action = 3; - rc = kFALSE; - break; - } - break; - - case -1: - // - // Method not supported - fHostAuth->CountFailure((Int_t)fSecurity); - if (gDebug > 2) - Info("Authenticate", - "method not even started: insufficient or wrong info: %s", - "try with next method, if any"); - fHostAuth->RemoveMethod(fSecurity); - nmet--; - if (nmet > 0) { - action = 1; - } else - action = 2; - - break; - - case -2: - // - // Remote host does not accepts connections from local host - fHostAuth->CountFailure((Int_t)fSecurity); - if (fVersion <= 2) - if (gDebug > 2) - Warning("Authenticate", - "status code -2 not expected from old daemons"); - rc = kFALSE; - break; - - case -3: - // - // Timeout: we set the method as last one, should the caller - // decide to retry, if it will attempt first something else. - // (We can not retry directly, because the server will not be - // synchronized ...) - fHostAuth->CountFailure((Int_t)fSecurity); - if (gDebug > 2) - Info("Authenticate", "got a timeout"); - fHostAuth->SetLast(fSecurity); - if (meth < nmet - 1) { - fTimeOut = 2; - } else - fTimeOut = 1; - rc = kFALSE; - break; - - default: - fHostAuth->CountFailure((Int_t)fSecurity); - if (gDebug > 2) - Info("Authenticate", "unknown status code: %d - assume failure",st); - rc = kFALSE; - action = 0; - break; - } - - switch (action) { - case 1: - goto negotia; - // No break but we go away anyhow - case 2: - fSocket->Send("0", kROOTD_BYE); - // fallthrough - case 3: - if (strlen(noSupport) > 0) - Info("Authenticate", "attempted methods %s are not supported" - " by remote server version", noSupport); - Info("Authenticate", - "failure: list of attempted methods: %s", triedMeth); - AuthError("Authenticate",-1); - rc = kFALSE; - break; - default: - break; - } - - // Cleanup timer - SafeDelete(alarm); - - return rc; - -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set default authentication environment. The values are inferred -/// from fSecurity and fDetails. - -void ROOT::Deprecated::TAuthenticate::SetEnvironment() -{ - R__LOCKGUARD2(gAuthenticateMutex); - - if (gDebug > 2) - Info("SetEnvironment", - "setting environment: fSecurity:%d, fDetails:%s", fSecurity, - fDetails.Data()); - - // Defaults - fgDefaultUser = fgUser; - fgAuthReUse = kTRUE; - fgPromptUser = kFALSE; - - // Decode fDetails, is non empty ... - if (fDetails != "") { - char usdef[kMAXPATHLEN] = { 0 }; - char pt[5] = { 0 }, ru[5] = { 0 }; - Int_t hh = 0, mm = 0; - char us[kMAXPATHLEN] = {0}, cp[kMAXPATHLEN] = {0}; - const char *ptr; - - TString usrPromptDef = TString(GetAuthMethod(fSecurity)) + ".LoginPrompt"; - if ((ptr = strstr(fDetails, "pt:")) != 0) { - sscanf(ptr + 3, "%4s %8191s", pt, usdef); - } else { - if (!strncasecmp(gEnv->GetValue(usrPromptDef,""),"no",2) || - !strncmp(gEnv->GetValue(usrPromptDef,""),"0",1)) - strncpy(pt,"0",2); - else - strncpy(pt,"1",2); - } - TString usrReUseDef = TString(GetAuthMethod(fSecurity)) + ".ReUse"; - if ((ptr = strstr(fDetails, "ru:")) != 0) { - sscanf(ptr + 3, "%4s %8191s", ru, usdef); - } else { - if (!strncasecmp(gEnv->GetValue(usrReUseDef,""),"no",2) || - !strncmp(gEnv->GetValue(usrReUseDef,""),"0",1)) - strncpy(ru,"0",2); - else - strncpy(ru,"1",2); - } - TString usrValidDef = TString(GetAuthMethod(fSecurity)) + ".Valid"; - TString hours(gEnv->GetValue(usrValidDef,"24:00")); - Int_t pd = 0; - if ((pd = hours.Index(":")) > -1) { - TString minutes = hours; - hours.Resize(pd); - minutes.Replace(0,pd+1,""); - hh = atoi(hours.Data()); - mm = atoi(minutes.Data()); - } else { - hh = atoi(hours.Data()); - mm = 0; - } - - // Now action depends on method ... - if (fSecurity == kClear) { - if ((ptr = strstr(fDetails, "us:")) != 0) - sscanf(ptr + 3, "%8191s %8191s", us, usdef); - if ((ptr = strstr(fDetails, "cp:")) != 0) - sscanf(ptr + 3, "%8191s %8191s", cp, usdef); - if (gDebug > 2) - Info("SetEnvironment", "details:%s, pt:%s, ru:%s, us:%s cp:%s", - fDetails.Data(), pt, ru, us, cp); - } else { - if ((ptr = strstr(fDetails, "us:")) != 0) - sscanf(ptr + 3, "%8191s %8191s", us, usdef); - if (gDebug > 2) - Info("SetEnvironment", "details:%s, pt:%s, ru:%s, us:%s", - fDetails.Data(), pt, ru, us); - } - - // Set Prompt flag - if (!strncasecmp(pt, "yes",3) || !strncmp(pt, "1", 1)) - fgPromptUser = kTRUE; - - // Set Expiring date - fgExpDate = TDatime(); - fgExpDate.Set(fgExpDate.Convert() + hh*3600 + mm*60); - - // UnSet Crypt flag for UsrPwd, if requested - if (fSecurity == kClear) { - fgUsrPwdCrypt = kTRUE; - if (!strncmp(cp, "no", 2) || !strncmp(cp, "0", 1)) - fgUsrPwdCrypt = kFALSE; - } - // Build UserDefaults - usdef[0] = '\0'; - // give highest priority to command-line specification - if (fUser == "") { - if (strlen(us) > 0) snprintf(usdef, kMAXPATHLEN, "%s", us); - } else { - snprintf(usdef, kMAXPATHLEN, "%s", fUser.Data()); - } - - if (strlen(usdef) > 0) { - fgDefaultUser = usdef; - } else { - if (fgUser != "") { - fgDefaultUser = fgUser; - } else { - UserGroup_t *u = gSystem->GetUserInfo(); - if (u) - fgDefaultUser = u->fUser; - delete u; - } - } - if (fgDefaultUser == "anonymous" || fgDefaultUser == "rootd" || - fgUser != "" || fUser != "") { - // when set by user don't prompt for it anymore - fgPromptUser = kFALSE; - } - - if (gDebug > 2) - Info("SetEnvironment", "usdef:%s", fgDefaultUser.Data()); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Try to get user name and passwd from several sources. - -Bool_t ROOT::Deprecated::TAuthenticate::GetUserPasswd(TString &user, TString &passwd, Bool_t &pwhash, Bool_t srppwd) -{ - if (srppwd) { - Error("GetUserPasswd", "SRP no longer supported by ROOT"); - return 1; - } - - if (gDebug > 3) - Info("GetUserPasswd", "Enter: User: '%s' Hash:%d SRP:%d", - user.Data(),(Int_t)pwhash,(Int_t)false); - - // Get user and passwd set via static functions SetUser and SetPasswd. - if (user == "" && fgUser != "") - user = fgUser; - - if (fgUser != "" && user == fgUser) { - if (passwd == "" && fgPasswd != "") { - passwd = fgPasswd; - pwhash = fgPwHash; - } - } - - if (gDebug > 3) - Info("GetUserPasswd", "In memory: User: '%s' Hash:%d", - user.Data(),(Int_t)pwhash); - - // Check system info for user if still not defined - if (user == "") { - UserGroup_t *u = gSystem->GetUserInfo(); - if (u) - user = u->fUser; - delete u; - if (gDebug > 3) - Info("GetUserPasswd", "In memory: User: '%s' Hash:%d", - user.Data(),(Int_t)pwhash); - } - - // Check ~/.rootnetrc and ~/.netrc files if user was not set via - // the static SetUser() method. - if (user == "" || passwd == "") { - if (gDebug > 3) - Info("GetUserPasswd", "Checking .netrc family ..."); - CheckNetrc(user, passwd, pwhash, /* srppwd */ false); - } - if (gDebug > 3) - Info("GetUserPasswd", "From .netrc family: User: '%s' Hash:%d", - user.Data(),(Int_t)pwhash); - - // If user also not set via ~/.rootnetrc or ~/.netrc ask user. - if (user == "") { - char *p = PromptUser(fRemote); - user = p; - delete [] p; - if (user == "") { - Error("GetUserPasswd", "user name not set"); - return 1; - } - } - - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Try to get user name and passwd from the ~/.rootnetrc or -/// ~/.netrc files. For more info see the version with 4 arguments. -/// This version is maintained for backward compatability reasons. - -Bool_t ROOT::Deprecated::TAuthenticate::CheckNetrc(TString &user, TString &passwd) -{ - Bool_t hash = false; - return CheckNetrc(user, passwd, hash, /* srppwd */ false); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Try to get user name and passwd from the ~/.rootnetrc or -/// ~/.netrc files. First ~/.rootnetrc is tried, after that ~/.netrc. -/// These files will only be used when their access masks are 0600. -/// Returns kTRUE if user and passwd were found for the machine -/// specified in the URL. If kFALSE, user and passwd are "". -/// The boolean pwhash is set to kTRUE if the returned passwd is to -/// be understood as password hash, i.e. if the 'password-hash' keyword -/// is found in the 'machine' lines; not implemented for 'secure' -/// and the .netrc file. -/// The format of these files are: -/// -/// # this is a comment line -/// machine `` login `` password `` -/// machine `` login `` password-hash `` -/// -/// and in addition ~/.rootnetrc also supports: -/// -/// secure `` login `` password `` -/// -/// `` may be a domain name or contain the wild card '*'. -/// -/// for the secure protocols. All lines must start in the first column. - -Bool_t ROOT::Deprecated::TAuthenticate::CheckNetrc(TString &user, TString &passwd, Bool_t &pwhash, Bool_t srppwd) -{ - if (srppwd) { - Error("CheckNetrc", "SRP no longer supported by ROOT"); - return 1; - } - - Bool_t result = kFALSE; - Bool_t first = kTRUE; - TString remote = fRemote; - - passwd = ""; - pwhash = kFALSE; - - TString temp_rootnet = ".rootnetrc"; - const char *net = - gSystem->PrependPathName(gSystem->HomeDirectory(), temp_rootnet); - - // Determine FQDN of the host ... - TInetAddress addr = gSystem->GetHostByName(fRemote); - if (addr.IsValid()) - remote = addr.GetHostName(); - -again: - // Only use file when its access rights are 0600 - FileStat_t buf; - if (gSystem->GetPathInfo(net, buf) == 0) { -#ifdef WIN32 - // Since Win32 does not have proper protections use file always - bool mode0600 = true; -#else - bool mode0600 = (buf.fMode & 0777) == (kS_IRUSR | kS_IWUSR); -#endif - if (R_ISREG(buf.fMode) && !R_ISDIR(buf.fMode) && mode0600) { - FILE *fd = fopen(net, "r"); - char line[256]; - while (fgets(line, sizeof(line), fd) != 0) { - if (line[0] == '#') - continue; - char word[6][64]; - int nword = sscanf(line, "%63s %63s %63s %63s %63s %63s", - word[0], word[1], word[2], word[3], word[4], word[5]); - if (nword != 6) - continue; - if (strcmp(word[0], "machine")) - continue; - if (strcmp(word[2], "login")) - continue; - if (strcmp(word[4], "password") && strcmp(word[4], "password-hash")) - continue; - - // Treat the host name found in file as a regular expression - // with '*' as a wild card - TString href(word[1]); - href.ReplaceAll("*",".*"); - TRegexp rg(href); - if (remote.Index(rg) != kNPOS) { - if (user == "") { - user = word[3]; - passwd = word[5]; - if (!strcmp(word[4], "password-hash")) - pwhash = kTRUE; - result = kTRUE; - break; - } else { - if (!strcmp(word[3], user.Data())) { - passwd = word[5]; - if (!strcmp(word[4], "password-hash")) - pwhash = kTRUE; - result = kTRUE; - break; - } - } - } - } - fclose(fd); - } else - Warning("CheckNetrc", - "file %s exists but has not 0600 permission", net); - } - - if (first && !result) { - TString temp_net = ".netrc"; - net = gSystem->PrependPathName(gSystem->HomeDirectory(), temp_net); - first = kFALSE; - goto again; - } - - return result; - } - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the global user. - -const char *ROOT::Deprecated::TAuthenticate::GetGlobalUser() -{ - return fgUser; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the global password hash flag. - -Bool_t ROOT::Deprecated::TAuthenticate::GetGlobalPwHash() -{ - return fgPwHash; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the global SRP password flag. - -Bool_t ROOT::Deprecated::TAuthenticate::GetGlobalSRPPwd() -{ - return false; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning default expiring date for new validity contexts - -TDatime ROOT::Deprecated::TAuthenticate::GetGlobalExpDate() -{ - return fgExpDate; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the default user information. - -const char *ROOT::Deprecated::TAuthenticate::GetDefaultUser() -{ - return fgDefaultUser; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the principal to be used to init Krb5 tickets. - -const char *ROOT::Deprecated::TAuthenticate::GetKrb5Principal() -{ - ::Error("Krb5Auth", "Kerberos5 is no longer supported by ROOT"); - return nullptr; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the authentication reuse settings. - -Bool_t ROOT::Deprecated::TAuthenticate::GetAuthReUse() -{ - return fgAuthReUse; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the prompt user settings. - -Bool_t ROOT::Deprecated::TAuthenticate::GetPromptUser() -{ - return fgPromptUser; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the method corresponding to idx. - -const char *ROOT::Deprecated::TAuthenticate::GetAuthMethod(Int_t idx) -{ - R__LOCKGUARD2(gAuthenticateMutex); - - if (idx < 0 || idx > kMAXSEC-1) { - ::Error("Authenticate::GetAuthMethod", "idx out of bounds (%d)", idx); - idx = 0; - } - return fgAuthMeth[idx]; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the method index (which can be used to find -/// the method in GetAuthMethod()). Returns -1 in case meth is not found. - -Int_t ROOT::Deprecated::TAuthenticate::GetAuthMethodIdx(const char *meth) -{ - R__LOCKGUARD2(gAuthenticateMutex); - - if (meth && meth[0]) { - for (Int_t i = 0; i < kMAXSEC; i++) { - if (!fgAuthMeth[i].CompareTo(meth, TString::kIgnoreCase)) - return i; - } - } - - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method to prompt for the user name to be used for authentication -/// to rootd. User is asked to type user name. -/// Returns user name (which must be deleted by caller) or 0. -/// If non-interactive run returns default user. - -char *ROOT::Deprecated::TAuthenticate::PromptUser(const char *remote) -{ - R__LOCKGUARD2(gAuthenticateMutex); - - const char *user; - if (fgDefaultUser != "") - user = fgDefaultUser; - else - user = gSystem->Getenv("USER"); -#ifdef R__WIN32 - if (!user) - user = gSystem->Getenv("USERNAME"); -#endif - if (isatty(0) == 0 || isatty(1) == 0) { - ::Warning("TAuthenticate::PromptUser", - "not tty: cannot prompt for user, returning default"); - if (strlen(user)) - return StrDup(user); - else - return StrDup("None"); - } - - const char *usrIn = Getline(Form("Name (%s:%s): ", remote, user)); - if (usrIn[0]) { - TString usr(usrIn); - usr.Remove(usr.Length() - 1); // get rid of \n - if (!usr.IsNull()) - return StrDup(usr); - else - return StrDup(user); - } - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method to prompt for the user's passwd to be used for -/// authentication to rootd. Uses non-echoing command line -/// to get passwd. Returns passwd (which must de deleted by caller) or 0. -/// If non-interactive run returns -1 - -char *ROOT::Deprecated::TAuthenticate::PromptPasswd(const char *prompt) -{ - if (isatty(0) == 0 || isatty(1) == 0) { - ::Warning("TAuthenticate::PromptPasswd", - "not tty: cannot prompt for passwd, returning -1"); - static char noint[4] = {"-1"}; - return StrDup(noint); - } - - char buf[128] = ""; - const char *pw = buf; - // Get the plugin for the passwd dialog box, if needed - if (!gROOT->IsBatch() && (fgPasswdDialog == (TPluginHandler *)(-1)) && - gEnv->GetValue("Auth.UsePasswdDialogBox", 1) == 1) { - if ((fgPasswdDialog = - gROOT->GetPluginManager()->FindHandler("TGPasswdDialog"))) { - if (fgPasswdDialog->LoadPlugin() == -1) { - fgPasswdDialog = 0; - ::Warning("TAuthenticate", - "could not load plugin for the password dialog box"); - } - } - } - if (fgPasswdDialog && (fgPasswdDialog != (TPluginHandler *)(-1))) { - - // Use graphic dialog - fgPasswdDialog->ExecPlugin(3, prompt, buf, 128); - - // Wait until the user is done - while (gROOT->IsInterrupted()) - gSystem->DispatchOneEvent(kFALSE); - - } else { - Gl_config("noecho", 1); - pw = Getline(prompt); - Gl_config("noecho", 0); - } - - // Final checks - if (pw[0]) { - TString spw(pw); - if (spw.EndsWith("\n")) - spw.Remove(spw.Length() - 1); // get rid of \n - char *rpw = StrDup(spw.Data()); - return rpw; - } - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the globus authorization hook (no longer supported) - -ROOT::Deprecated::GlobusAuth_t ROOT::Deprecated::TAuthenticate::GetGlobusAuthHook() -{ - return nullptr; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the RSA public keys. - -const char *ROOT::Deprecated::TAuthenticate::GetRSAPubExport(Int_t key) -{ - key = (key >= 0 && key <= 1) ? key : 0; - return fgRSAPubExport[key].keys; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the RSA initialization flag. - -Int_t ROOT::Deprecated::TAuthenticate::GetRSAInit() -{ - return fgRSAInit; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method setting the default type of RSA key. - -void ROOT::Deprecated::TAuthenticate::SetDefaultRSAKeyType(Int_t key) -{ - if (key >= 0 && key <= 1) - fgRSAKey = key; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method setting RSA initialization flag. - -void ROOT::Deprecated::TAuthenticate::SetRSAInit(Int_t init) -{ - fgRSAInit = init; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning the list with authentication details. - -TList *ROOT::Deprecated::TAuthenticate::GetAuthInfo() -{ - R__LOCKGUARD2(gAuthenticateMutex); - - if (!fgAuthInfo) - fgAuthInfo = new TList; - return fgAuthInfo; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Print error string depending on error code. - -void ROOT::Deprecated::TAuthenticate::AuthError(const char *where, Int_t err) -{ - R__LOCKGUARD2(gAuthenticateMutex); - - // Make sure it is in range - err = (err < kErrError) ? ((err > -1) ? err : -1) : kErrError; - - Int_t erc = err; - Bool_t forceprint = kFALSE; - TString lasterr = ""; - if (err == -1) { - forceprint = kTRUE; - erc = fgLastError; - lasterr = "(last error only; re-run with gDebug > 0 for more details)"; - } - - if (erc > -1) - if (gDebug > 0 || forceprint) { - if (gRootdErrStr[erc]) - ::Error(Form("TAuthenticate::%s", where), "%s %s", - gRootdErrStr[erc], lasterr.Data()); - else - ::Error(Form("TAuthenticate::%s", where), - "unknown error code: server must be running a newer ROOT version %s", - lasterr.Data()); - } - - // Update last error code - fgLastError = err; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set global user name to be used for authentication to rootd. - -void ROOT::Deprecated::TAuthenticate::SetGlobalUser(const char *user) -{ - R__LOCKGUARD2(gAuthenticateMutex); - - if (fgUser != "") - fgUser = ""; - - if (user && user[0]) - fgUser = user; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set global passwd to be used for authentication to rootd. - -void ROOT::Deprecated::TAuthenticate::SetGlobalPasswd(const char *passwd) -{ - R__LOCKGUARD2(gAuthenticateMutex); - - if (fgPasswd != "") - fgPasswd = ""; - - if (passwd && passwd[0]) - fgPasswd = passwd; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set global passwd hash flag to be used for authentication to rootd. - -void ROOT::Deprecated::TAuthenticate::SetGlobalPwHash(Bool_t pwhash) -{ - fgPwHash = pwhash; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set global SRP passwd flag to be used for authentication to rootd. - -void ROOT::Deprecated::TAuthenticate::SetGlobalSRPPwd(Bool_t) -{ - ::Error("SetGlobalSRPPwd", "SRP no longer supported by ROOT"); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set default expiring date for new validity contexts - -void ROOT::Deprecated::TAuthenticate::SetGlobalExpDate(TDatime expdate) -{ - fgExpDate = expdate; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set default user name. - -void ROOT::Deprecated::TAuthenticate::SetDefaultUser(const char *defaultuser) -{ - if (fgDefaultUser != "") - fgDefaultUser = ""; - - if (defaultuser && defaultuser[0]) - fgDefaultUser = defaultuser; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set timeout (active if > 0) - -void ROOT::Deprecated::TAuthenticate::SetTimeOut(Int_t to) -{ - fgAuthTO = (to <= 0) ? -1 : to; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set global AuthReUse flag - -void ROOT::Deprecated::TAuthenticate::SetAuthReUse(Bool_t authreuse) -{ - fgAuthReUse = authreuse; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set global PromptUser flag - -void ROOT::Deprecated::TAuthenticate::SetPromptUser(Bool_t promptuser) -{ - fgPromptUser = promptuser; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set secure authorization function. - -void ROOT::Deprecated::TAuthenticate::SetSecureAuthHook(SecureAuth_t func) -{ - fgSecAuthHook = func; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set kerberos5 authorization function. Automatically called when -/// libKrb5Auth is loaded. - -void ROOT::Deprecated::TAuthenticate::SetKrb5AuthHook(Krb5Auth_t) -{ - ::Error("Krb5Auth", "Kerberos5 is no longer supported by ROOT"); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set Globus authorization function. Automatically called when -/// libGlobusAuth is loaded. - -void ROOT::Deprecated::TAuthenticate::SetGlobusAuthHook(GlobusAuth_t) -{ - ::Error("GlobusAuth", "Globus is no longer supported by ROOT"); -} - -//////////////////////////////////////////////////////////////////////////////// -/// SSH client authentication code (no longer supported) - -Int_t ROOT::Deprecated::TAuthenticate::SshAuth(TString & /* user */) -{ - ::Error("SshAuth", "SSH is no longer supported by ROOT"); - return 1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Method returning the user to be used for the ssh login (no longer supported) - -const char *ROOT::Deprecated::TAuthenticate::GetSshUser(TString /* user */) const -{ - ::Error("GetSshUser", "SSH is no longer supported by ROOT"); - return nullptr; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check if 'host' matches 'href': -/// this means either equal or "containing" it, even with wild cards * -/// in the first field (in the case 'href' is a name, ie not IP address) -/// Returns kTRUE if the two matches. - -Bool_t ROOT::Deprecated::TAuthenticate::CheckHost(const char *host, const char *href) -{ - R__LOCKGUARD2(gAuthenticateMutex); - - Bool_t retval = kTRUE; - - // Both strings should have been defined - if (!host || !href) - return kFALSE; - - // 'href' == '*' indicates any 'host' ... - if (!strcmp(href,"*")) - return kTRUE; - - // If 'href' contains at a letter or an hyphen it is assumed to be - // a host name. Otherwise a name. - // Check also for wild cards - Bool_t name = kFALSE; - TRegexp rename("[+a-zA-Z]"); - Int_t len; - if (rename.Index(href,&len) != -1 || strstr(href,"-")) - name = kTRUE; - - // Check also for wild cards - Bool_t wild = kFALSE; - if (strstr(href,"*")) - wild = kTRUE; - - // Now build the regular expression for final checking - TRegexp rehost(href,wild); - - // host to check - TString theHost(host); - if (!name) { - TInetAddress addr = gSystem->GetHostByName(host); - theHost = addr.GetHostAddress(); - if (gDebug > 2) - ::Info("TAuthenticate::CheckHost", "checking host IP: %s", theHost.Data()); - } - - // Check 'host' against 'rehost' - Ssiz_t pos = rehost.Index(theHost,&len); - if (pos == -1) - retval = kFALSE; - - // If IP and no wilds, it should match either - // the beginning or the end of the string - if (!wild) { - if (pos > 0 && pos != (Ssiz_t)(theHost.Length()-strlen(href))) - retval = kFALSE; - } - - return retval; -} - -//////////////////////////////////////////////////////////////////////////////// -/// RFIO authentication (no longer supported) - -Int_t ROOT::Deprecated::TAuthenticate::RfioAuth(TString &) -{ - ::Error("RfioAuth", "RfioAuth is no longer supported by ROOT"); - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// UsrPwd client authentication code. -/// Returns 0 in case authentication failed -/// 1 in case of success - -Int_t ROOT::Deprecated::TAuthenticate::ClearAuth(TString &user, TString &passwd, Bool_t &pwdhash) -{ - R__LOCKGUARD2(gAuthenticateMutex); - - if (gDebug > 2) - Info("ClearAuth", "enter: user: %s (passwd hashed?: %d)", - user.Data(),(Int_t)pwdhash); - - Int_t reuse = fgAuthReUse; - Int_t prompt = fgPromptUser; - Int_t cryptopt = fgUsrPwdCrypt; - Int_t needsalt = 1; - if (pwdhash) - needsalt = 0; - fDetails = TString::Format("pt:%d ru:%d cp:%d us:", - fgPromptUser, fgAuthReUse, fgUsrPwdCrypt) + user; - if (gDebug > 2) - Info("ClearAuth", "ru:%d pt:%d cp:%d ns:%d rk:%d", - fgAuthReUse,fgPromptUser,fgUsrPwdCrypt,needsalt,fgRSAKey); -#ifdef R__WIN32 - needsalt = 0; -#endif - Int_t stat, kind; - - if (fVersion > 1) { - - // - // New protocol - // - Int_t anon = 0; - TString salt = ""; - TString pashash = ""; - - // Get effective user (fro remote checks in $HOME/.rhosts) - UserGroup_t *pw = gSystem->GetUserInfo(gSystem->GetEffectiveUid()); - TString effUser; - if (pw) { - effUser = TString(pw->fUser); - delete pw; - } else - effUser = user; - - // Create options string - int opt = (reuse * kAUTH_REUSE_MSK) + (cryptopt * kAUTH_CRYPT_MSK) + - (needsalt * kAUTH_SSALT_MSK) + (fRSAKey * kAUTH_RSATY_MSK); - TString options; - options.Form("%d %ld %s %ld %s", opt, - (Long_t)user.Length(), user.Data(), - (Long_t)effUser.Length(), effUser.Data()); - - // Check established authentications - kind = kROOTD_USER; - stat = reuse; - Int_t rc = 0; - if ((rc = AuthExists(user, (Int_t) TAuthenticate::kClear, options, - &kind, &stat, &StdCheckSecCtx)) == 1) { - // A valid authentication exists: we are done ... - return 1; - } - if (rc == -2) { - return rc; - } - if (stat == kErrNotAllowed && kind == kROOTD_ERR) { - return 0; - } - - if (kind == kROOTD_AUTH && stat == -1) { - if (gDebug > 3) - Info("ClearAuth", "anonymous user"); - anon = 1; - cryptopt = 0; - reuse = 0; - needsalt = 0; - } - - // The random tag in hex representation - // Protection against reply attacks - char ctag[11] = {0}; - if (anon == 0 && cryptopt == 1) { - - // Check that we got the right thing .. - if (kind != kROOTD_RSAKEY || stat < 1 || stat > 2 ) { - // Check for errors - if (kind != kROOTD_ERR) { - Warning("ClearAuth", - "problems recvn RSA key flag: got message %d, flag: %d", - kind, stat); - } - return 0; - } - if (gDebug > 3) - Info("ClearAuth", "get key request ..."); - - // Save type of key - fRSAKey = stat - 1; - - // Send the key securely - if (SendRSAPublicKey(fSocket,fRSAKey) < 0) - return 0; - - int slen = 0; - if (needsalt) { - // Receive password salt - char *tmpsalt = 0; - if ((slen = SecureRecv(fSocket, 1, fRSAKey, &tmpsalt)) == -1) { - Warning("ClearAuth", "problems secure-receiving salt -" - " may result in corrupted salt"); - Warning("ClearAuth", "switch off reuse for this session"); - delete [] tmpsalt; - return 0; - } - if (slen) { - // Extract random tag, if there - if (slen > 9) { - int ltmp = slen; - while (ltmp && tmpsalt[ltmp-1] != '#') ltmp--; - if (ltmp) { - if (tmpsalt[ltmp-1] == '#' && - tmpsalt[ltmp-10] == '#') { - strlcpy(ctag,&tmpsalt[ltmp-10],11); - // We drop the random tag - ltmp -= 10; - tmpsalt[ltmp] = 0; - // Update salt length - slen -= 10; - } - } - if (!tmpsalt[0]) { - // No salt left - needsalt = 0; - slen = 0; - } - } - if (slen) - salt = TString(tmpsalt); - } - delete [] tmpsalt; - if (gDebug > 2) - Info("ClearAuth", "got salt: '%s' (len: %d)", salt.Data(), slen); - } else { - if (gDebug > 2) - Info("ClearAuth", "Salt not required"); - char *tmptag = 0; - if (SecureRecv(fSocket, 1, fRSAKey, &tmptag) == -1) { - Warning("ClearAuth", "problems secure-receiving rndmtag -" - " may result in corrupted rndmtag"); - } - if (tmptag) { - strlcpy(ctag, tmptag, 11); - delete [] tmptag; - } - } - // We may not have got a salt (if the server may not access it - // or if it needs the full password, like for AFS ...) - if (!slen) - needsalt = 0; - } - // Now get the password either from prompt or from memory, if saved already - if (anon == 1) { - - if (fgPasswd.Contains("@")) { - // Anonymous like login with user chosen passwd ... - passwd = fgPasswd; - } else { - // Anonymous like login with automatic passwd generation ... - TString localuser; - pw = gSystem->GetUserInfo(); - if (pw) { - char *u = StrDup(pw->fUser); - localuser = u; - delete[] u; - } - delete pw; - static TString localFQDN; - if (localFQDN == "") { - TInetAddress addr = gSystem->GetHostByName(gSystem->HostName()); - if (addr.IsValid()) - localFQDN = addr.GetHostName(); - } - passwd.Form("%s@%s", localuser.Data(), localFQDN.Data()); - if (gDebug > 2) - Info("ClearAuth", - "automatically generated anonymous passwd: %s", - passwd.Data()); - } - - } else { - - if (prompt == 1 || pashash.Length() == 0) { - - if (passwd == "") { - TString xp; - xp.Form("%s@%s password: ", user.Data(),fRemote.Data()); - char *pwd = PromptPasswd(xp); - passwd = TString(pwd); - delete [] pwd; - if (passwd == "") { - Error("ClearAuth", "password not set"); - fSocket->Send("-1", kROOTD_PASS); // Needs this for consistency - return 0; - } - } - if (needsalt && !pwdhash) { -#ifndef R__WIN32 - pashash = TString(crypt(passwd, salt)); - if (!pashash.BeginsWith(salt)) { - // not the right version of the crypt function: - // do not send hash - pashash = passwd; - } -#else - pashash = passwd; -#endif - } else { - pashash = passwd; - } - } - - } - - // Store password for later use - fgUser = fUser; - fgPwHash = kFALSE; - fPwHash = kFALSE; - fgPasswd = passwd; - fPasswd = passwd; - - // Send it to server - if (anon == 0 && cryptopt == 1) { - - // Needs to send this for consistency - if (fSocket->Send("\0", kROOTD_PASS) < 0) - return 0; - - // Add the random tag received from the server - // (if any); makes packets non re-usable - if (strlen(ctag)) - pashash += ctag; - - if (SecureSend(fSocket, 1, fRSAKey, pashash.Data()) == -1) { - Warning("ClearAuth", "problems secure-sending pass hash" - " - may result in authentication failure"); - return 0; - } - } else { - - // Standard technique: invert passwd - if (passwd != "") { - for (int i = 0; i < passwd.Length(); i++) { - char inv = ~passwd(i); - passwd.Replace(i, 1, inv); - } - } - if (fSocket->Send(passwd.Data(), kROOTD_PASS) < 0) - return 0; - } - - Int_t nrec = 0; - // Receive username used for login - if ((nrec = fSocket->Recv(stat, kind)) < 0 ) // returns user - return 0; - if (gDebug > 3) - Info("ClearAuth", "after kROOTD_PASS: kind= %d, stat= %d", kind, - stat); - - // Check for errors - if (kind == kROOTD_ERR) { - AuthError("ClearAuth", stat); - fgPasswd = ""; - return 0; - } - - if (kind != kROOTD_PASS || stat < 1) - Warning("ClearAuth", - "problems recvn (user,offset) length (%d:%d bytes:%d)", - kind, stat, nrec); - - // Get user and offset - char answer[256]; - int reclen = (stat+1 > 256) ? 256 : stat+1; - if ((nrec = fSocket->Recv(answer, reclen, kind)) < 0) - return 0; - if (kind != kMESS_STRING) - Warning("ClearAuth", - "username and offset not received (%d:%d)", kind, - nrec); - - // Parse answer - char lUser[128]; - Int_t offset = -1; - sscanf(answer, "%127s %d", lUser, &offset); - if (gDebug > 3) - Info("ClearAuth", - "received from server: user: %s, offset: %d (%s)", lUser, - offset, answer); - - // Return username - user = lUser; - - char *token = 0; - if (reuse == 1 && offset > -1) { - // Receive token - if (cryptopt == 1) { - if (SecureRecv(fSocket, 1, fRSAKey, &token) == -1) { - Warning("ClearAuth", - "problems secure-receiving token -" - " may result in corrupted token"); - return 0; - } - } else { - Int_t tlen = 9; - token = new char[tlen]; - if (fSocket->Recv(token, tlen, kind) < 0) { - delete [] token; - return 0; - } - if (kind != kMESS_STRING) - Warning("ClearAuth", "token not received (%d:%d)", kind, - nrec); - // Invert token - for (int i = 0; i < (int) strlen(token); i++) { - token[i] = ~token[i]; - } - - } - if (gDebug > 3) - Info("ClearAuth", "received from server: token: '%s' ", - token); - } - TPwdCtx *pwdctx = new TPwdCtx(fPasswd,fPwHash); - // Create SecContext object - fSecContext = fHostAuth->CreateSecContext((const char *)lUser, fRemote, - kClear, offset, fDetails, (const char *)token, - fgExpDate, (void *)pwdctx, fRSAKey); - - // Release allocated memory ... - if (token) - delete [] token; - - // This from remote login - if (fSocket->Recv(stat, kind) < 0) - return 0; - - - if (kind == kROOTD_AUTH && stat >= 1) { - fgPasswd = ""; - if (kind == kROOTD_ERR) - AuthError("ClearAuth", stat); - return 0; - } - - } else { - - // Old Protocol - - // Send username - if (fSocket->Send(user.Data(), kROOTD_USER) < 0) - return 0; - - // Get replay from server - if (fSocket->Recv(stat, kind) < 0) - return 0; - - // This check should guarantee backward compatibility with a private - // version of rootd used by CDF - if (kind == kROOTD_AUTH && stat == 1) { - fSecContext = - fHostAuth->CreateSecContext(user,fRemote,kClear,-1,fDetails,0); - return 1; - } - - if (kind == kROOTD_ERR) { - TString server = "sockd"; - if (fProtocol.Contains("root")) - server = "rootd"; - if (stat == kErrConnectionRefused) { - if (gDebug > 0) - Error("ClearAuth", - "%s@%s does not accept connections from %s@%s", - server.Data(),fRemote.Data(), - fUser.Data(),gSystem->HostName()); - return -2; - } else if (stat == kErrNotAllowed) { - if (gDebug > 0) - Error("ClearAuth", - "%s@%s does not accept %s authentication from %s@%s", - server.Data(),fRemote.Data(), - TAuthenticate::fgAuthMeth[0].Data(), - fUser.Data(),gSystem->HostName()); - } else - AuthError("ClearAuth", stat); - return 0; - } - // Prepare passwd to send - badpass1: - if (passwd == "") { - TString xp; - xp.Form("%s@%s password: ", user.Data(),fRemote.Data()); - char *p = PromptPasswd(xp); - passwd = p; - delete [] p; - if (passwd == "") - Error("ClearAuth", "password not set"); - } - if (fUser == "anonymous" || fUser == "rootd") { - if (!passwd.Contains("@")) { - Warning("ClearAuth", - "please use passwd of form: user@host.do.main"); - passwd = ""; - goto badpass1; - } - } - - fgPasswd = passwd; - fPasswd = passwd; - - // Invert passwd - if (passwd != "") { - for (int i = 0; i < passwd.Length(); i++) { - char inv = ~passwd(i); - passwd.Replace(i, 1, inv); - } - } - // Send it over the net - if (fSocket->Send(passwd, kROOTD_PASS) < 0) - return 0; - - // Get result of attempt - if (fSocket->Recv(stat, kind) < 0) // returns user - return 0; - if (gDebug > 3) - Info("ClearAuth", "after kROOTD_PASS: kind= %d, stat= %d", kind, - stat); - - if (kind == kROOTD_AUTH && stat == 1) { - fSecContext = - fHostAuth->CreateSecContext(user,fRemote,kClear,-1,fDetails,0); - return 1; - } else { - if (kind == kROOTD_ERR) - AuthError("ClearAuth", stat); - return 0; - } - } - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Sets fUser=user and search fgAuthInfo for the entry pertaining to -/// (host,user), setting fHostAuth accordingly. -/// If no entry is found fHostAuth is not changed - -ROOT::Deprecated::THostAuth * -ROOT::Deprecated::TAuthenticate::GetHostAuth(const char *host, const char *user, Option_t */*opt*/, Int_t *exact) -{ - if (exact) - *exact = 0; - - if (gDebug > 2) - ::Info("TAuthenticate::GetHostAuth", "enter ... %s ... %s", host, user); - - // Strip off the servertype, if any - Int_t srvtyp = -1; - TString hostname = host; - if (hostname.Contains(":")) { - char *ps = (char *)strstr(host,":"); - if (ps) - srvtyp = atoi(ps+1); - hostname.Remove(hostname.Index(":")); - } - TString hostFQDN = hostname; - if (strncmp(host,"default",7) && !hostFQDN.Contains("*")) { - TInetAddress addr = gSystem->GetHostByName(hostFQDN); - if (addr.IsValid()) - hostFQDN = addr.GetHostName(); - } - TString usr = user; - if (!usr.Length()) - usr = "*"; - THostAuth *rHA = 0; - - // Check list of auth info for already loaded info about this host - TIter *next = new TIter(GetAuthInfo()); - - THostAuth *ai; - Bool_t notFound = kTRUE; - Bool_t serverOK = kTRUE; - while ((ai = (THostAuth *) (*next)())) { - if (gDebug > 3) - ai->Print("Authenticate::GetHostAuth"); - - // server - if (!(serverOK = (ai->GetServer() == -1) || - (ai->GetServer() == srvtyp))) - continue; - - // Use default entry if existing and nothing more specific is found - if (!strcmp(ai->GetHost(),"default") && serverOK && notFound) - rHA = ai; - - // Check - if (CheckHost(hostFQDN,ai->GetHost()) && - CheckHost(usr,ai->GetUser()) && serverOK) { - rHA = ai; - notFound = kFALSE; - } - - if (hostFQDN == ai->GetHost() && - usr == ai->GetUser() && srvtyp == ai->GetServer() ) { - rHA = ai; - if (exact) - *exact = 1; - break; - } - } - SafeDelete(next); - return rHA; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Checks if a THostAuth with exact match for {host,user} exists -/// in the fgAuthInfo list -/// Returns pointer to it or 0 - -ROOT::Deprecated::THostAuth * -ROOT::Deprecated::TAuthenticate::HasHostAuth(const char *host, const char *user, Option_t */*opt*/) -{ - if (gDebug > 2) - ::Info("TAuthenticate::HasHostAuth", "enter ... %s ... %s", host, user); - - // Strip off the servertype, if any - Int_t srvtyp = -1; - TString hostFQDN = host; - if (hostFQDN.Contains(":")) { - char *ps = (char *)strstr(host,":"); - if (ps) - srvtyp = atoi(ps+1); - hostFQDN.Remove(hostFQDN.Index(":")); - } - if (strncmp(host,"default",7) && !hostFQDN.Contains("*")) { - TInetAddress addr = gSystem->GetHostByName(hostFQDN); - if (addr.IsValid()) - hostFQDN = addr.GetHostName(); - } - - TIter *next = new TIter(GetAuthInfo()); - THostAuth *ai; - while ((ai = (THostAuth *) (*next)())) { - - if (hostFQDN == ai->GetHost() && - !strcmp(user, ai->GetUser()) && srvtyp == ai->GetServer()) { - SafeDelete(next); - return ai; - } - } - SafeDelete(next); - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Expands include directives found in fexp files -/// The expanded, temporary file, is pointed to by 'ftmp' -/// and should be already open. To be called recursively. - -void ROOT::Deprecated::TAuthenticate::FileExpand(const char *fexp, FILE *ftmp) -{ - FILE *fin; - char line[kMAXPATHLEN]; - char cinc[20], fileinc[kMAXPATHLEN]; - - if (gDebug > 2) - ::Info("TAuthenticate::FileExpand", "enter ... '%s' ... 0x%zx", fexp, (size_t)ftmp); - - fin = fopen(fexp, "r"); - if (fin == 0) - return; - - while (fgets(line, sizeof(line), fin) != 0) { - // Skip comment lines - if (line[0] == '#') - continue; - if (line[strlen(line) - 1] == '\n') - line[strlen(line) - 1] = '\0'; - if (gDebug > 2) - ::Info("TAuthenticate::FileExpand", "read line ... '%s'", line); - int nw = sscanf(line, "%19s %8191s", cinc, fileinc); - if (nw < 1) - continue; // Not enough info in this line - if (strcmp(cinc, "include") != 0) { - // copy line in temporary file - fprintf(ftmp, "%s\n", line); - } else { - - // Drop quotes or double quotes, if any - TString ln(line); - ln.ReplaceAll("\"",1,"",0); - ln.ReplaceAll("'",1,"",0); - sscanf(ln.Data(), "%19s %8191s", cinc, fileinc); - - // support environment directories ... - if (fileinc[0] == '$') { - TString finc(fileinc); - TString edir(fileinc); - if (edir.Contains("/")) { - edir.Remove(edir.Index("/")); - edir.Remove(0,1); - if (gSystem->Getenv(edir.Data())) { - finc.Remove(0,1); - finc.ReplaceAll(edir.Data(),gSystem->Getenv(edir.Data())); - fileinc[0] = '\0'; - strncpy(fileinc,finc.Data(),kMAXPATHLEN); - fileinc[kMAXPATHLEN-1] = '\0'; - } - } - } - - // open (expand) file in temporary file ... - if (fileinc[0] == '~') { - // needs to expand - int flen = - strlen(fileinc) + strlen(gSystem->HomeDirectory()) + 10; - char *ffull = new char[flen]; - snprintf(ffull, flen, "%s/%s", gSystem->HomeDirectory(), fileinc + 1); - if (strlen(ffull) < kMAXPATHLEN - 1) strlcpy(fileinc, ffull,kMAXPATHLEN); - delete [] ffull; - } - // Check if file exist and can be read ... ignore if not ... - if (!gSystem->AccessPathName(fileinc, kReadPermission)) { - FileExpand(fileinc, ftmp); - } else { - ::Warning("TAuthenticate::FileExpand", - "file specified by 'include' cannot be open or read (%s)", - fileinc); - } - } - } - fclose(fin); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Determine default authentication details for method 'sec' and user 'usr'. -/// Checks .rootrc family files. Returned string must be deleted by the user. - -char *ROOT::Deprecated::TAuthenticate::GetDefaultDetails(int sec, int opt, const char *usr) -{ - char temp[kMAXPATHLEN] = { 0 }; - const char copt[2][5] = { "no", "yes" }; - - if (gDebug > 2) - ::Info("TAuthenticate::GetDefaultDetails", - "enter ... %d ...pt:%d ... '%s'", sec, opt, usr); - - if (opt < 0 || opt > 1) - opt = 1; - - // UsrPwd - if (sec == TAuthenticate::kClear) { - if (!usr[0] || !strncmp(usr,"*",1)) - usr = gEnv->GetValue("UsrPwd.Login", ""); - snprintf(temp, kMAXPATHLEN, "pt:%s ru:%s cp:%s us:%s", - gEnv->GetValue("UsrPwd.LoginPrompt", copt[opt]), - gEnv->GetValue("UsrPwd.ReUse", "1"), - gEnv->GetValue("UsrPwd.Crypt", "1"), usr); - } - - if (gDebug > 2) - ::Info("TAuthenticate::GetDefaultDetails", "returning ... %s", temp); - - return StrDup(temp); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Remove THostAuth instance from the list - -void ROOT::Deprecated::TAuthenticate::RemoveHostAuth(THostAuth * ha, Option_t */*opt*/) -{ - GetAuthInfo()->Remove(ha); - // ... destroy it - delete ha; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Print info about the authentication sector. -/// If 'opt' contains 's' or 'S' prints information about established TSecContext, -/// else prints information about THostAuth - -void ROOT::Deprecated::TAuthenticate::Show(Option_t *opt) -{ - TString sopt(opt); - - if (sopt.Contains("s", TString::kIgnoreCase)) { - - // Print established security contexts - TIter next(ROOT::Deprecated::Internal::GetListOfSecContexts(*gROOT)); - TSecContext *sc = 0; - while ((sc = (TSecContext *)next())) - sc->Print(); - - } else { - - ::Info("::Print", " +--------------------------- BEGIN --------------------------------+"); - ::Info("::Print", " + +"); - ::Info("::Print", " + List fgAuthInfo has %4d members +", - GetAuthInfo()->GetSize()); - ::Info("::Print", " + +"); - ::Info("::Print", " +------------------------------------------------------------------+"); - TIter next(GetAuthInfo()); - THostAuth *ai; - while ((ai = (THostAuth *)next())) { - ai->Print(); - ai->PrintEstablished(); - } - ::Info("::Print", " +---------------------------- END ---------------------------------+"); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check if we have a valid established sec context in memory -/// Retrieves relevant info and negotiates with server. -/// options = "Opt,strlen(username),username.Data()" -/// message = kROOTD_USER, ... - -Int_t ROOT::Deprecated::TAuthenticate::AuthExists(TString username, Int_t method, const char *options, - Int_t *message, Int_t *rflag, - CheckSecCtx_t checksecctx) -{ - // Welcome message, if requested ... - if (gDebug > 2) - Info("AuthExists","%d: enter: msg: %d options: '%s'", - method,*message, options); - - // Look for an existing security context matching this request - Bool_t notHA = kFALSE; - - // First in the local list - TIter next(fHostAuth->Established()); - TRootSecContext *secctx; - while ((secctx = (TRootSecContext *)next())) { - if (secctx->GetMethod() == method) { - if (fRemote == secctx->GetHost()) { - if (checksecctx && - (*checksecctx)(username,secctx) == 1) - break; - } - } - } - - // If nothing found, try the all list - if (!secctx) { - next = TIter(ROOT::Deprecated::Internal::GetListOfSecContexts(*gROOT)); - while ((secctx = (TRootSecContext *)next())) { - if (secctx->GetMethod() == method) { - if (fRemote == secctx->GetHost()) { - if (checksecctx && - (*checksecctx)(username,secctx) == 1) { - notHA = kTRUE; - break; - } - } - } - } - } - - // If we have been given a valid sec context retrieve some info - Int_t offset = -1; - TString token; - if (secctx) { - offset = secctx->GetOffSet(); - token = secctx->GetToken(); - if (gDebug > 2) - Info("AuthExists", - "found valid TSecContext: offset: %d token: '%s'", - offset, token.Data()); - } - - // Prepare string to be sent to the server - TString sstr; - sstr.Form("%d %d %s", fgProcessID, offset, options); - - // Send message - if (fSocket->Send(sstr, *message) < 0) - return -2; - - Int_t reuse = *rflag; - if (reuse == 1 && offset > -1) { - - // Receive result of checking offset - // But only for recent servers - // NB: not backward compatible with dev version 4.00.02: switch - // off 'reuse' for such servers to avoid hanging at this point. - Int_t rproto = fSocket->GetRemoteProtocol(); - Bool_t oldsrv = ((fProtocol.BeginsWith("root") && rproto == 9)); - Int_t stat = 1, kind; - if (!oldsrv) { - if (fSocket->Recv(stat, kind) < 0) - return -2; - if (kind != kROOTD_AUTH) - Warning("AuthExists","protocol error: expecting %d got %d" - " (value: %d)",kROOTD_AUTH,kind,stat); - } - - if (stat > 0) { - if (gDebug > 2) - Info("AuthExists","offset OK"); - - Int_t rsaKey = secctx->GetRSAKey(); - if (gDebug > 2) - Info("AuthExists", "key type: %d", rsaKey); - - if (rsaKey > -1) { - - // Recent servers send a random tag in stat - // It has to be signed too - if (stat > 1) { - // Create hex from tag - char tag[9] = {0}; - snprintf(tag, 9, "%08x",stat); - // Add to token - token += tag; - } - - // Send token encrypted - if (SecureSend(fSocket, 1, rsaKey, token) == -1) { - Warning("AuthExists", "problems secure-sending token %s", - "- may trigger problems in proofing Id "); - return -2; - } - } else { - // Send inverted - for (int i = 0; i < token.Length(); i++) { - char inv = ~token(i); - token.Replace(i, 1, inv); - } - if (fSocket->Send(token, kMESS_STRING) < 0) - return -2; - } - } else { - if (gDebug > 0) - Info("AuthExists","offset not OK - rerun authentication"); - // If the sec context was not valid, deactivate it ... - if (secctx) - secctx->DeActivate(""); - } - } - - Int_t stat, kind; - if (fSocket->Recv(stat, kind) < 0) - return -2; - if (gDebug > 3) - Info("AuthExists","%d: after msg %d: kind= %d, stat= %d", - method,*message, kind, stat); - - // Return flags - *message = kind; - *rflag = stat; - - if (kind == kROOTD_ERR) { - TString server = "sockd"; - if (fSocket->GetServType() == TSocket::kROOTD) - server = "rootd"; - if (stat == kErrConnectionRefused) { - Error("AuthExists","%s@%s does not accept connections from %s@%s", - server.Data(),fRemote.Data(),fUser.Data(),gSystem->HostName()); - return -2; - } else if (stat == kErrNotAllowed) { - if (gDebug > 0) - Info("AuthExists", - "%s@%s does not accept %s authentication from %s@%s", - server.Data(),fRemote.Data(), fgAuthMeth[method].Data(), - fUser.Data(),gSystem->HostName()); - } else - AuthError("AuthExists", stat); - - // If the sec context was not valid, deactivate it ... - if (secctx) - secctx->DeActivate(""); - return 0; - } - - if (kind == kROOTD_AUTH && stat >= 1) { - if (!secctx) - secctx = - fHostAuth->CreateSecContext(fUser,fRemote,method,-stat,fDetails,0); - if (gDebug > 3) { - if (stat == 1) - Info("AuthExists", "valid authentication exists"); - if (stat == 2) - Info("AuthExists", "valid authentication exists: offset changed"); - if (stat == 3) - Info("AuthExists", "remote access authorized by /etc/hosts.equiv"); - if (stat == 4) - Info("AuthExists", "no authentication required remotely"); - } - - if (stat == 2) { - int newOffSet; - // Receive new offset ... - if (fSocket->Recv(newOffSet, kind) < 0) - return -2; - // ... and save it - secctx->SetOffSet(newOffSet); - } - - fSecContext = secctx; - // Add it to local list for later use (if not already there) - if (notHA) - fHostAuth->Established()->Add(secctx); - return 1; - } - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Initialize random machine using seed from /dev/urandom -/// (or current time if /dev/urandom not available). - -void ROOT::Deprecated::TAuthenticate::InitRandom() -{ - static Bool_t notinit = kTRUE; - - if (notinit) { - const char *randdev = "/dev/urandom"; - Int_t fd; - UInt_t seed; - if ((fd = open(randdev, O_RDONLY)) != -1) { - if (gDebug > 2) - ::Info("InitRandom", "taking seed from %s", randdev); - if (read(fd, &seed, sizeof(seed)) != sizeof(seed)) - ::Warning("InitRandom", "could not read seed from %s", randdev); - close(fd); - } else { - if (gDebug > 2) - ::Info("InitRandom", "%s not available: using time()", randdev); - seed = time(0); //better use times() + win32 equivalent - } - srand(seed); - notinit = kFALSE; - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Generate a valid pair of private/public RSA keys to protect for -/// authentication token exchange - -Int_t ROOT::Deprecated::TAuthenticate::GenRSAKeys() -{ - if (gDebug > 2) - Info("GenRSAKeys", "enter"); - - if (fgRSAInit == 1) { - if (gDebug > 2) - Info("GenRSAKeys", "Keys prviously generated - return"); - } - - // This is for dynamic loads ... - TString lib = "libRsa"; - - // This is the local RSA implementation - if (!TRSA_fun::RSA_genprim()) { - char *p; - if ((p = gSystem->DynamicPathName(lib, kTRUE))) { - delete [] p; - gSystem->Load(lib); - } - } - - // Init random machine - TAuthenticate::InitRandom(); - -#ifdef R__SSL - if (fgRSAKey == 1) { - // Generate also the SSL key - if (gDebug > 2) - Info("GenRSAKeys","SSL: Generate Blowfish key"); - - // Init SSL ... - SSL_library_init(); - - // ... and its error strings - SSL_load_error_strings(); - - // Load Ciphers - OpenSSL_add_all_ciphers(); - - // Number of bits for key - Int_t nbits = gEnv->GetValue("SSL.BFBits",256); - - // Minimum is 128 - nbits = (nbits >= 128) ? nbits : 128; - - // Max to limit size of buffers to 15912 (internal limitation) - nbits = (nbits <= 15912) ? nbits : 15912; - - // Closer Number of chars - Int_t klen = nbits / 8 ; - - // Init random engine - char *rbuf = GetRandString(0,klen); - RAND_seed(rbuf,strlen(rbuf)); - - // This is what we export - fgRSAPubExport[1].len = klen; - fgRSAPubExport[1].keys = rbuf; - if (gDebug > 2) - Info("GenRSAKeys","SSL: BF key length: %d", fgRSAPubExport[1].len); - - // Now set the key locally in BF form - BF_set_key(&fgBFKey, klen, (const unsigned char *)rbuf); - } -#endif - - // Sometimes some bunch is not decrypted correctly - // That's why we make retries to make sure that encryption/decryption - // works as expected - Bool_t notOk = 1; - rsa_NUMBER p1, p2, rsa_n, rsa_e, rsa_d; - Int_t l_n = 0, l_d = 0; - char buf_n[rsa_STRLEN], buf_e[rsa_STRLEN], buf_d[rsa_STRLEN]; -#if R__RSADE - Int_t l_e; - char buf[rsa_STRLEN]; -#endif - - Int_t nAttempts = 0; - Int_t thePrimeLen = kPRIMELENGTH; - Int_t thePrimeExp = kPRIMEEXP; // Prime probability = 1-0.5^thePrimeExp - while (notOk && nAttempts < kMAXRSATRIES) { - - nAttempts++; - if (gDebug > 2 && nAttempts > 1) { - Info("GenRSAKeys", "retry no. %d",nAttempts); - srand(auth_rand()); - } - - // Valid pair of primes - p1 = TRSA_fun::RSA_genprim()(thePrimeLen, thePrimeExp); - p2 = TRSA_fun::RSA_genprim()(thePrimeLen+1, thePrimeExp); - - // Retry if equal - Int_t nPrimes = 0; - while (TRSA_fun::RSA_cmp()(&p1, &p2) == 0 && nPrimes < kMAXRSATRIES) { - nPrimes++; - if (gDebug > 2) - Info("GenRSAKeys", "equal primes: regenerate (%d times)",nPrimes); - srand(auth_rand()); - p1 = TRSA_fun::RSA_genprim()(thePrimeLen, thePrimeExp); - p2 = TRSA_fun::RSA_genprim()(thePrimeLen+1, thePrimeExp); - } -#if R__RSADEB - if (gDebug > 3) { - TRSA_fun::RSA_num_sput()(&p1, buf, rsa_STRLEN); - Info("GenRSAKeys", "local: p1: '%s' ", buf); - TRSA_fun::RSA_num_sput()(&p2, buf, rsa_STRLEN); - Info("GenRSAKeys", "local: p2: '%s' ", buf); - } -#endif - // Generate keys - if (TRSA_fun::RSA_genrsa()(p1, p2, &rsa_n, &rsa_e, &rsa_d)) { - if (gDebug > 2 && nAttempts > 1) - Info("GenRSAKeys"," genrsa: unable to generate keys (%d)", - nAttempts); - continue; - } - - // Get equivalent strings and determine their lengths - TRSA_fun::RSA_num_sput()(&rsa_n, buf_n, rsa_STRLEN); - l_n = strlen(buf_n); - TRSA_fun::RSA_num_sput()(&rsa_e, buf_e, rsa_STRLEN); -#if R__RSADEB - l_e = strlen(buf_e); -#endif - TRSA_fun::RSA_num_sput()(&rsa_d, buf_d, rsa_STRLEN); - l_d = strlen(buf_d); - -#if R__RSADEB - if (gDebug > 3) { - Info("GenRSAKeys", "local: n: '%s' length: %d", buf_n, l_n); - Info("GenRSAKeys", "local: e: '%s' length: %d", buf_e, l_e); - Info("GenRSAKeys", "local: d: '%s' length: %d", buf_d, l_d); - } -#endif - if (TRSA_fun::RSA_cmp()(&rsa_n, &rsa_e) <= 0) - continue; - if (TRSA_fun::RSA_cmp()(&rsa_n, &rsa_d) <= 0) - continue; - - // Now we try the keys - char test[2 * rsa_STRLEN] = "ThisIsTheStringTest01203456-+/"; - Int_t lTes = 31; - char *tdum = GetRandString(0, lTes - 1); - strlcpy(test, tdum, lTes+1); - delete [] tdum; - char buf[2 * rsa_STRLEN]; - if (gDebug > 3) - Info("GenRSAKeys", "local: test string: '%s' ", test); - - // Private/Public - strlcpy(buf, test, lTes+1); - - // Try encryption with private key - int lout = TRSA_fun::RSA_encode()(buf, lTes, rsa_n, rsa_e); - if (gDebug > 3) - Info("GenRSAKeys", - "local: length of crypted string: %d bytes", lout); - - // Try decryption with public key - TRSA_fun::RSA_decode()(buf, lout, rsa_n, rsa_d); - buf[lTes] = 0; - if (gDebug > 3) - Info("GenRSAKeys", "local: after private/public : '%s' ", buf); - - if (strncmp(test, buf, lTes)) - continue; - - // Public/Private - strlcpy(buf, test, lTes+1); - - // Try encryption with public key - lout = TRSA_fun::RSA_encode()(buf, lTes, rsa_n, rsa_d); - if (gDebug > 3) - Info("GenRSAKeys", "local: length of crypted string: %d bytes ", - lout); - - // Try decryption with private key - TRSA_fun::RSA_decode()(buf, lout, rsa_n, rsa_e); - buf[lTes] = 0; - if (gDebug > 3) - Info("GenRSAKeys", "local: after public/private : '%s' ", buf); - - if (strncmp(test, buf, lTes)) - continue; - - notOk = 0; - } - - // Save Private key - TRSA_fun::RSA_assign()(&fgRSAPriKey.n, &rsa_n); - TRSA_fun::RSA_assign()(&fgRSAPriKey.e, &rsa_e); - - // Save Public key - TRSA_fun::RSA_assign()(&fgRSAPubKey.n, &rsa_n); - TRSA_fun::RSA_assign()(&fgRSAPubKey.e, &rsa_d); - -#if R__RSADEB - if (gDebug > 2) { - // Determine their lengths - Info("GenRSAKeys", "local: generated keys are:"); - Info("GenRSAKeys", "local: n: '%s' length: %d", buf_n, l_n); - Info("GenRSAKeys", "local: e: '%s' length: %d", buf_e, l_e); - Info("GenRSAKeys", "local: d: '%s' length: %d", buf_d, l_d); - } -#endif - // Export form - if (fgRSAPubExport[0].keys) { - delete [] fgRSAPubExport[0].keys; - fgRSAPubExport[0].len = 0; - } - fgRSAPubExport[0].len = l_n + l_d + 4; - fgRSAPubExport[0].keys = new char[fgRSAPubExport[0].len]; - - fgRSAPubExport[0].keys[0] = '#'; - memcpy(fgRSAPubExport[0].keys + 1, buf_n, l_n); - fgRSAPubExport[0].keys[l_n + 1] = '#'; - memcpy(fgRSAPubExport[0].keys + l_n + 2, buf_d, l_d); - fgRSAPubExport[0].keys[l_n + l_d + 2] = '#'; - fgRSAPubExport[0].keys[l_n + l_d + 3] = 0; -#if R__RSADEB - if (gDebug > 2) - Info("GenRSAKeys", "local: export pub: '%s'", fgRSAPubExport[0].keys); -#else - if (gDebug > 2) - Info("GenRSAKeys", "local: export pub length: %d bytes", fgRSAPubExport[0].len); -#endif - - // Set availability flag - fgRSAInit = 1; - - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Allocates and fills a 0 terminated buffer of length len+1 with -/// len random characters. -/// Returns pointer to the buffer (to be deleted by the caller) -/// opt = 0 any non dangerous char -/// 1 letters and numbers (upper and lower case) -/// 2 hex characters (upper and lower case) - -char *ROOT::Deprecated::TAuthenticate::GetRandString(Int_t opt, Int_t len) -{ - unsigned int iimx[4][4] = { - {0x0, 0xffffff08, 0xafffffff, 0x2ffffffe}, // opt = 0 - {0x0, 0x3ff0000, 0x7fffffe, 0x7fffffe}, // opt = 1 - {0x0, 0x3ff0000, 0x7e, 0x7e}, // opt = 2 - {0x0, 0x3ffc000, 0x7fffffe, 0x7fffffe} // opt = 3 - }; - - const char *cOpt[4] = { "Any", "LetNum", "Hex", "Crypt" }; - - // Default option 0 - if (opt < 0 || opt > 2) { - opt = 0; - if (gDebug > 2) - Info("GetRandString", "unknown option: %d : assume 0", opt); - } - if (gDebug > 2) - Info("GetRandString", "enter ... len: %d %s", len, cOpt[opt]); - - // Allocate buffer - char *buf = new char[len + 1]; - - // Init random machine (if needed) - TAuthenticate::InitRandom(); - - // randomize - Int_t k = 0; - Int_t i, j, l, m, frnd; - while (k < len) { - frnd = auth_rand(); - for (m = 7; m < 32; m += 7) { - i = 0x7F & (frnd >> m); - j = i / 32; - l = i - j * 32; - if ((iimx[opt][j] & (1 << l))) { - buf[k] = i; - k++; - } - if (k == len) - break; - } - } - - // null terminated - buf[len] = 0; - if (gDebug > 3) - Info("GetRandString", "got '%s' ", buf); - - return buf; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Encode null terminated str using the session private key indicated by enc -/// and sends it over the network -/// Returns number of bytes sent, or -1 in case of error. -/// enc = 1 for private encoding, enc = 2 for public encoding - -Int_t ROOT::Deprecated::TAuthenticate::SecureSend(TSocket *sock, Int_t enc, Int_t key, const char *str) -{ - char buftmp[kMAXSECBUF]; - char buflen[20]; - - if (gDebug > 2) - ::Info("TAuthenticate::SecureSend", "local: enter ... (enc: %d)", enc); - - Int_t slen = strlen(str) + 1; - Int_t ttmp = 0; - Int_t nsen = -1; - - if (key == 0) { - strlcpy(buftmp, str, slen+1); - - if (enc == 1) - ttmp = TRSA_fun::RSA_encode()(buftmp, slen, fgRSAPriKey.n, - fgRSAPriKey.e); - else if (enc == 2) - ttmp = TRSA_fun::RSA_encode()(buftmp, slen, fgRSAPubKey.n, - fgRSAPubKey.e); - else - return nsen; - } else if (key == 1) { - -#ifdef R__SSL - ttmp = strlen(str); - if ((ttmp % 8) > 0) // It should be a multiple of 8! - ttmp = ((ttmp + 8)/8) * 8; - unsigned char iv[8]; - memset((void *)&iv[0],0,8); - BF_cbc_encrypt((const unsigned char *)str, (unsigned char *)buftmp, - strlen(str), &fgBFKey, iv, BF_ENCRYPT); -#else - if (gDebug > 0) - ::Info("TAuthenticate::SecureSend","not compiled with SSL support:" - " you should not have got here!"); -#endif - } else { - if (gDebug > 0) - ::Info("TAuthenticate::SecureSend","unknown key type (%d)",key); - return nsen; - } - - snprintf(buflen,20,"%d",ttmp); - if (sock->Send(buflen, kROOTD_ENCRYPT) < 0) - return -1; - nsen = sock->SendRaw(buftmp, ttmp); - if (gDebug > 3) - ::Info("TAuthenticate::SecureSend", - "local: sent %d bytes (expected: %d)", nsen,ttmp); - - return nsen; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive str from sock and decode it using key indicated by key type -/// Return number of received bytes or -1 in case of error. -/// dec = 1 for private decoding, dec = 2 for public decoding - -Int_t ROOT::Deprecated::TAuthenticate::SecureRecv(TSocket *sock, Int_t dec, Int_t key, char **str) -{ - - char buftmp[kMAXSECBUF]; - char buflen[20]; - - Int_t nrec = -1; - // We must get a pointer ... - if (!str) - return nrec; - - Int_t kind; - if (sock->Recv(buflen, 20, kind) < 0) - return -1; - Int_t len = atoi(buflen); - if (gDebug > 3) - ::Info("TAuthenticate::SecureRecv", "got len '%s' %d (msg kind: %d)", - buflen, len, kind); - if (len == 0) { - return len; - } - if (len < 0 || len > kMAXSECBUF) { - return nrec; - } - - // Receive buffer - if ((nrec = sock->RecvRaw(buftmp, len)) < 0) - return nrec; - if (key == 0) { - if (dec == 1) - TRSA_fun::RSA_decode()(buftmp, len, fgRSAPriKey.n, fgRSAPriKey.e); - else if (dec == 2) - TRSA_fun::RSA_decode()(buftmp, len, fgRSAPubKey.n, fgRSAPubKey.e); - else - return -1; - - // Prepare output - const size_t strSize = strlen(buftmp) + 1; - *str = new char[strSize]; - if (*str == nullptr) { - if (gDebug > 0) - ::Info("TAuthenticate::SecureRecv","Memory allocation error size (%ld)", (long) strSize); - return -1; - } - strlcpy(*str, buftmp, strSize); - - } else if (key == 1) { -#ifdef R__SSL - unsigned char iv[8]; - memset((void *)&iv[0],0,8); - *str = new char[nrec + 1]; - BF_cbc_encrypt((const unsigned char *)buftmp, (unsigned char *)(*str), - nrec, &fgBFKey, iv, BF_DECRYPT); - (*str)[nrec] = '\0'; -#else - if (gDebug > 0) - ::Info("TAuthenticate::SecureRecv","not compiled with SSL support:" - " you should not have got here!"); -#endif - } else { - if (gDebug > 0) - ::Info("TAuthenticate::SecureRecv","unknown key type (%d)",key); - return -1; - } - - nrec= strlen(*str); - - return nrec; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Store RSA public keys from export string rsaPubExport. - -Int_t ROOT::Deprecated::TAuthenticate::DecodeRSAPublic(const char *rsaPubExport, R__rsa_NUMBER &rsa_n, - R__rsa_NUMBER &rsa_d, char **rsassl) -{ - if (!rsaPubExport) - return -1; - - if (gDebug > 2) - ::Info("TAuthenticate::DecodeRSAPublic", - "enter: string length: %ld bytes", (Long_t)strlen(rsaPubExport)); - - char str[kMAXPATHLEN] = { 0 }; - Int_t klen = strlen(rsaPubExport); - if (klen > kMAXPATHLEN - 1) { - ::Info("TAuthenticate::DecodeRSAPublic", - "key too long (%d): truncate to %d",klen,kMAXPATHLEN); - klen = kMAXPATHLEN - 1; - } - memcpy(str, rsaPubExport, klen); - str[klen] ='\0'; - - Int_t keytype = -1; - - if (klen > 0) { - - // Skip spaces at beginning, if any - int k = 0; - while (str[k] == 32) k++; - - if (str[k] == '#') { - - keytype = 0; - - // The format is ### - char *pd1 = strstr(str, "#"); - char *pd2 = pd1 ? strstr(pd1 + 1, "#") : (char *)0; - char *pd3 = pd2 ? strstr(pd2 + 1, "#") : (char *)0; - if (pd1 && pd2 && pd3) { - // Get ... - int l1 = (int) (pd2 - pd1 - 1); - char *rsa_n_exp = new char[l1 + 1]; - strlcpy(rsa_n_exp, pd1 + 1, l1+1); - if (gDebug > 2) - ::Info("TAuthenticate::DecodeRSAPublic", - "got %ld bytes for rsa_n_exp", (Long_t)strlen(rsa_n_exp)); - // Now - int l2 = (int) (pd3 - pd2 - 1); - char *rsa_d_exp = new char[l2 + 1]; - strlcpy(rsa_d_exp, pd2 + 1, 13); - if (gDebug > 2) - ::Info("TAuthenticate::DecodeRSAPublic", - "got %ld bytes for rsa_d_exp", (Long_t)strlen(rsa_d_exp)); - - TRSA_fun::RSA_num_sget()(&rsa_n, rsa_n_exp); - TRSA_fun::RSA_num_sget()(&rsa_d, rsa_d_exp); - - delete[] rsa_n_exp; - delete[] rsa_d_exp; - - } else - ::Info("TAuthenticate::DecodeRSAPublic","bad format for input string"); -#ifdef R__SSL - } else { - // try SSL - keytype = 1; - - RSA *rsatmp; - - // Bio for exporting the pub key - BIO *bpub = BIO_new(BIO_s_mem()); - - // Write key from kbuf to BIO - BIO_write(bpub,(void *)str,strlen(str)); - - // Read pub key from BIO - if (!(rsatmp = PEM_read_bio_RSAPublicKey(bpub, 0, 0, 0))) { - if (gDebug > 0) - ::Info("TAuthenticate::DecodeRSAPublic", - "unable to read pub key from bio"); - } else - if (rsassl) - *rsassl = (char *)rsatmp; - else - ::Info("TAuthenticate::DecodeRSAPublic", - "no space allocated for output variable"); - BIO_free(bpub); - } -#else - } else { - if (rsassl) { } // To avoid compiler complains - if (gDebug > 0) - ::Info("TAuthenticate::DecodeRSAPublic","not compiled with SSL support:" - " you should not have got here!"); - } -#endif - } - - return keytype; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Store RSA public keys from export string rsaPubExport. -/// Returns type of stored key, or -1 is not recognized - -Int_t ROOT::Deprecated::TAuthenticate::SetRSAPublic(const char *rsaPubExport, Int_t klen) -{ - if (gDebug > 2) - ::Info("TAuthenticate::SetRSAPublic", - "enter: string length %ld bytes", (Long_t)strlen(rsaPubExport)); - - Int_t rsakey = -1; - if (!rsaPubExport) - return rsakey; - - if (klen > 0) { - - // Skip spaces at beginning, if any - int k0 = 0; - while (rsaPubExport[k0] == 32) k0++; - int k2 = klen - 1; - - // Parse rsaPubExport - // Type 0 is in the form - // - // #< gt 10 exa chars >#< gt 10 exa chars ># - // - rsakey = 1; - if (rsaPubExport[k0] == '#' && rsaPubExport[k2] == '#') { - char *p0 = (char *)&rsaPubExport[k0]; - char *p2 = (char *)&rsaPubExport[k2]; - char *p1 = strchr(p0+1,'#'); - if (p1 > p0 && p1 < p2) { - Int_t l01 = (Int_t)(p1-p0)-1; - Int_t l12 = (Int_t)(p2-p1)-1; - if (l01 >= kPRIMELENGTH*2 && l12 >= kPRIMELENGTH*2) { - // Require exadecimal chars in between - char *c = p0+1; - while (c < p1 && ((*c < 58 && *c > 47) || (*c < 91 && *c > 64))) - c++; - if (c == p1) { - c++; - while (c < p2 && ((*c < 58 && *c > 47) || (*c < 91 && *c > 64))) - c++; - if (c == p2) - rsakey = 0; - } - } - } - } - if (gDebug > 3) - ::Info("TAuthenticate::SetRSAPublic"," Key type: %d",rsakey); - if (rsakey == 0) { - - // Decode input string - R__rsa_NUMBER rsa_n, rsa_d; - rsakey = TAuthenticate::DecodeRSAPublic(rsaPubExport,rsa_n,rsa_d); - - // Save Public key - TRSA_fun::RSA_assign()(&fgRSAPubKey.n, &rsa_n); - TRSA_fun::RSA_assign()(&fgRSAPubKey.e, &rsa_d); - - } else { - rsakey = 1; -#ifdef R__SSL - // Now set the key locally in BF form - BF_set_key(&fgBFKey, klen, (const unsigned char *)rsaPubExport); -#else - if (gDebug > 0) - ::Info("TAuthenticate::SetRSAPublic", - "not compiled with SSL support:" - " you should not have got here!"); -#endif - } - } - - return rsakey; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receives server RSA Public key -/// Sends local RSA public key encoded - -Int_t ROOT::Deprecated::TAuthenticate::SendRSAPublicKey(TSocket *socket, Int_t key) -{ - // Receive server public key - char serverPubKey[kMAXSECBUF]; - int kind, nr = 0; - if ((nr = socket->Recv(serverPubKey, kMAXSECBUF, kind)) < 0) - return nr; - if (gDebug > 3) - ::Info("TAuthenticate::SendRSAPublicKey", - "received key from server %ld bytes", (Long_t)strlen(serverPubKey)); - - // Decode it - R__rsa_NUMBER rsa_n, rsa_d; -#ifdef R__SSL - char *tmprsa = nullptr; - if (TAuthenticate::DecodeRSAPublic(serverPubKey,rsa_n,rsa_d, - &tmprsa) != key) { - if (tmprsa) - RSA_free((RSA *)tmprsa); - return -1; - } - RSA *RSASSLServer = (RSA *)tmprsa; -#else - if (TAuthenticate::DecodeRSAPublic(serverPubKey,rsa_n,rsa_d) != key) - return -1; -#endif - - // Send local public key, encodes - char buftmp[kMAXSECBUF] = {0}; - char buflen[20] = {0}; - Int_t slen = fgRSAPubExport[key].len; - Int_t ttmp = 0; - if (key == 0) { - strlcpy(buftmp, fgRSAPubExport[key].keys, sizeof(buftmp)); - ttmp = TRSA_fun::RSA_encode()(buftmp, slen, rsa_n, rsa_d); // NOLINT: rsa_n, rsa_d are initialized - snprintf(buflen, sizeof(buflen), "%d", ttmp); - } else if (key == 1) { -#ifdef R__SSL - Int_t lcmax = RSA_size(RSASSLServer) - 11; - Int_t kk = 0; - Int_t ke = 0; - Int_t ns = slen; - while (ns > 0) { - Int_t lc = (ns > lcmax) ? lcmax : ns ; - if ((ttmp = RSA_public_encrypt(lc, - (unsigned char *)&fgRSAPubExport[key].keys[kk], - (unsigned char *)&buftmp[ke], - RSASSLServer,RSA_PKCS1_PADDING)) < 0) { - char errstr[120]; - ERR_error_string(ERR_get_error(), errstr); - ::Info("TAuthenticate::SendRSAPublicKey","SSL: error: '%s' ",errstr); - } - kk += lc; - ke += ttmp; - ns -= lc; - } - ttmp = ke; - snprintf(buflen, 20, "%d", ttmp); -#else - if (gDebug > 0) - ::Info("TAuthenticate::SendRSAPublicKey","not compiled with SSL support:" - " you should not have got here!"); - return -1; -#endif - } else { - if (gDebug > 0) - ::Info("TAuthenticate::SendRSAPublicKey","unknown key type (%d)",key); -#ifdef R__SSL - if (RSASSLServer) - RSA_free(RSASSLServer); -#endif - return -1; - } - - // Send length first - if ((nr = socket->Send(buflen, kROOTD_ENCRYPT)) < 0) - return nr; - // Send Key. second ... - Int_t nsen = socket->SendRaw(buftmp, ttmp); - if (gDebug > 3) - ::Info("TAuthenticate::SendRSAPublicKey", - "local: sent %d bytes (expected: %d)", nsen,ttmp); -#ifdef R__SSL - if (RSASSLServer) - RSA_free(RSASSLServer); -#endif - return nsen; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Read authentication directives from $ROOTAUTHRC, $HOME/.rootauthrc or -/// `/system.rootauthrc` and create related THostAuth objects. -/// Files are read only if they changed since last reading - -Int_t ROOT::Deprecated::TAuthenticate::ReadRootAuthrc() -{ - // rootauthrc family - TString tRootAuthrc; - if (gSystem->Getenv("ROOTAUTHRC") != 0) { - tRootAuthrc = gSystem->Getenv("ROOTAUTHRC"); - } else { - if (fgReadHomeAuthrc) { - tRootAuthrc = ".rootauthrc"; - gSystem->PrependPathName(gSystem->HomeDirectory(), tRootAuthrc); - } - } - if (!tRootAuthrc.IsNull() && gDebug > 2) - ::Info("TAuthenticate::ReadRootAuthrc", "Checking file: %s", tRootAuthrc.Data()); - if (tRootAuthrc.IsNull() || gSystem->AccessPathName(tRootAuthrc, kReadPermission)) { - if (!tRootAuthrc.IsNull() && gDebug > 1) - ::Info("TAuthenticate::ReadRootAuthrc", - "file %s cannot be read (errno: %d)", tRootAuthrc.Data(), errno); - tRootAuthrc = "system.rootauthrc"; - gSystem->PrependPathName(TROOT::GetEtcDir(), tRootAuthrc); - if (gDebug > 2) - ::Info("TAuthenticate::ReadRootAuthrc", "Checking system file: %s", tRootAuthrc.Data()); - if (gSystem->AccessPathName(tRootAuthrc, kReadPermission)) { - if (gDebug > 1) - ::Info("TAuthenticate::ReadRootAuthrc", - "file %s cannot be read (errno: %d)", tRootAuthrc.Data(), errno); - return 0; - } - } - - // Check if file has changed since last read - if (tRootAuthrc == fgRootAuthrc) { - struct stat si; - stat(tRootAuthrc, &si); - if ((UInt_t)si.st_mtime < fgLastAuthrc.Convert()) { - if (gDebug > 1) - ::Info("TAuthenticate::ReadRootAuthrc", - "file %s already read", tRootAuthrc.Data()); - return 0; - } - } - - // Save filename in static variable - fgRootAuthrc = tRootAuthrc; - fgLastAuthrc = TDatime(); - - // THostAuth lists - TList *authinfo = TAuthenticate::GetAuthInfo(); - - // Expand File into temporary file name and open it - int expand = 1; - TString filetmp = "rootauthrc"; - FILE *ftmp = gSystem->TempFileName(filetmp); - if (gDebug > 2) - ::Info("TAuthenticate::ReadRootAuthrc", "got tmp file: %s open at 0x%zx", - filetmp.Data(), (size_t)ftmp); - if (ftmp == 0) - expand = 0; // Problems opening temporary file: ignore 'include's ... - - FILE *fd = 0; - // If the temporary file is open, copy everything to the new file ... - if (expand == 1) { - TAuthenticate::FileExpand(tRootAuthrc, ftmp); - fd = ftmp; - rewind(fd); - } else { - // Open file - fd = fopen(tRootAuthrc, "r"); - if (fd == 0) { - if (gDebug > 2) - ::Info("TAuthenticate::ReadRootAuthrc", - "file %s cannot be open (errno: %d)", tRootAuthrc.Data(), errno); - return 0; - } - } - - // Now scan file for meaningful directives - TList tmpAuthInfo; - char line[kMAXPATHLEN]; - while (fgets(line, sizeof(line), fd) != 0) { - - // Skip comment lines - if (line[0] == '#') - continue; - - // Get rid of end of line '\n', if there ... - if (line[strlen(line) - 1] == '\n') - line[strlen(line) - 1] = '\0'; - - // Skip empty lines - if (!line[0]) - continue; - - // Now scan - const size_t tmpSize = strlen(line) + 1; - char *tmp = new char[tmpSize]; - if (!tmp) { - ::Error("TAuthenticate::ReadRootAuthrc", - "could not allocate temporary buffer"); - fclose(fd); - return 0; - } - strlcpy(tmp, line, tmpSize); - char *nxt = strtok(tmp," "); - - - TString hostsrv = nxt; - TString host = hostsrv; - TString server = ""; - if (hostsrv.Contains(":")) { - server = hostsrv; - host.Remove(host.Index(":")); - server.Remove(0,server.Index(":")+1); - } - Int_t srvtyp = -1; - if (server.Length()) { - if (server == "0" || server.BeginsWith("sock")) - srvtyp = TSocket::kSOCKD; - else if (server == "1" || server.BeginsWith("root")) - srvtyp = TSocket::kROOTD; - } - - // Line with host info directives - TString user = "*"; - - nxt = strtok(0," "); - if (!strncmp(nxt,"user",4)) { - nxt = strtok(0," "); - if (strncmp(nxt,"list",4) && strncmp(nxt,"method",6)) { - user = TString(nxt); - nxt = strtok(0," "); - } - } - - // Get related THostAuth, if exists in the tmp list, - TIter next(&tmpAuthInfo); - THostAuth *ha; - while ((ha = (THostAuth *)next())) { - if (host == ha->GetHost() && user == ha->GetUser() && - srvtyp == ha->GetServer()) - break; - } - if (!ha) { - // Create a new one - ha = new THostAuth(host,srvtyp,user); - tmpAuthInfo.Add(ha); - } - - if (!strncmp(nxt,"list",4)) { - // list of methods for {host,usr} - Int_t nm = 0, me[kMAXSEC] = {0}; - char *mth = strtok(0," "); - while (mth) { - Int_t met = -1; - if (strlen(mth) > 1) { - // Method passed as string: translate it to number - met = GetAuthMethodIdx(mth); - if (met == -1 && gDebug > 2) - ::Info("TAuthenticate::ReadRootAuthrc", - "unrecognized method (%s): ", mth); - } else { - met = atoi(mth); - } - if (met > -1 && met < kMAXSEC) - me[nm++] = met; - mth = strtok(0," "); - } - if (nm) - ha->ReOrder(nm,me); - - } else if (!strncmp(nxt,"method",6)) { - - // details for {host,usr,method} - char *mth = strtok(0," "); - Int_t met = -1; - if (strlen(mth) > 1) { - // Method passed as string: translate it to number - met = GetAuthMethodIdx(mth); - if (met == -1 && gDebug > 2) - ::Info("TAuthenticate::ReadRootAuthrc", - "unrecognized method (%s): ", mth); - } else { - met = atoi(mth); - } - if (met > -1 && met < kMAXSEC) { - const char *det = 0; - nxt = strtok(0," "); - if (nxt) { - det = (const char *)strstr(line,nxt); - } - if (ha->HasMethod(met)) - ha->SetDetails(met,det); - else - ha->AddMethod(met,det); - } - } - if (tmp) delete [] tmp; - } - // Close file and remove it if temporary - fclose(fd); - if (expand == 1) - gSystem->Unlink(filetmp); - - // Update authinfo with new info found - TAuthenticate::MergeHostAuthList(authinfo,&tmpAuthInfo); - - // Print those left, if requested ... - if (gDebug > 2) - TAuthenticate::Show(); - - return authinfo->GetSize(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Standard version of CheckSecCtx to be passed to TAuthenticate::AuthExists -/// Check if User is matches the one in Ctx -/// Returns: 1 if ok, 0 if not -/// Deactivates Ctx is not valid - -static Int_t StdCheckSecCtx(const char *user, ROOT::Deprecated::TRootSecContext *ctx) -{ - Int_t rc = 0; - - if (ctx->IsActive()) { - if (!strcmp(user,ctx->GetUser()) && - strncmp("AFS", ctx->GetID(), 3)) - rc = 1; - } - return rc; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Tool for updating fgAuthInfo -/// 'nin' contains list of last input information through (re)reading -/// of a rootauthrc-alike file. 'nin' info has priority. -/// 'std' is cleaned from inactive members. -/// 'nin' members used to update existing members in 'std' are -/// removed from 'nin', do that they do not leak - -void ROOT::Deprecated::TAuthenticate::MergeHostAuthList(TList *std, TList *nin, Option_t *opt) -{ - // Remove inactive from the 'std' - TIter nxstd(std); - THostAuth *ha; - while ((ha = (THostAuth *) nxstd())) { - if (!ha->IsActive()) { - std->Remove(ha); - SafeDelete(ha); - } - } - - // Merge 'nin' info in 'std' - TIter nxnew(nin); - ROOT::Deprecated::THostAuth *hanew; - while ((hanew = (THostAuth *)nxnew())) { - if (hanew->NumMethods()) { - TString hostsrv; - hostsrv.Form("%s:%d",hanew->GetHost(),hanew->GetServer()); - THostAuth *hastd = - TAuthenticate::HasHostAuth(hostsrv,hanew->GetUser(),opt); - if (hastd) { - // Update with new info - hastd->Update(hanew); - // Flag for removal - hanew->DeActivate(); - } else { - // Add new ThostAuth to std - std->Add(hanew); - } - } else - // Flag for removal empty objects - hanew->DeActivate(); - } - - // Cleanup memory before quitting - nxnew.Reset(); - while ((hanew = (THostAuth *)nxnew())) { - if (!hanew->IsActive()) { - nin->Remove(hanew); - SafeDelete(hanew); - } - } - -} - -//////////////////////////////////////////////////////////////////////////////// -/// Tool for removing SecContext ctx from THostAuth listed in -/// fgAuthInfo - -void ROOT::Deprecated::TAuthenticate::RemoveSecContext(TRootSecContext *ctx) -{ - ROOT::Deprecated::THostAuth *ha = 0; - - // authinfo first - TIter nxai(GetAuthInfo()); - while ((ha = (THostAuth *)nxai())) { - TIter next(ha->Established()); - TRootSecContext *lctx = 0; - while ((lctx = (TRootSecContext *) next())) { - if (lctx == ctx) { - ha->Established()->Remove(ctx); - break; - } - } - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Static method returning supported client protocol. - -Int_t ROOT::Deprecated::TAuthenticate::GetClientProtocol() -{ - return TSocket::GetClientProtocol(); -} - diff --git a/net/auth/src/THostAuth.cxx b/net/auth/src/THostAuth.cxx deleted file mode 100644 index 21b979b5820d6..0000000000000 --- a/net/auth/src/THostAuth.cxx +++ /dev/null @@ -1,681 +0,0 @@ -// @(#)root/auth:$Id$ -// Author: G. Ganis 19/03/2003 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// THostAuth // -// // -// Contains details about host-specific authentication methods and the // -// result of their application. // -// Used by TAuthenticate. // -// // -////////////////////////////////////////////////////////////////////////// - -#include "RConfigure.h" -#include "TSystem.h" -#include "THostAuth.h" -#include "TRootSecContext.h" -#include "TAuthenticate.h" -#include "TSocket.h" -#include "TUrl.h" -#include - - - -//////////////////////////////////////////////////////////////////////////////// -/// Default constructor. - - ROOT::Deprecated::THostAuth::THostAuth() : TObject() -{ - Create(0, 0); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Create hostauth object. -/// 'host' may contain also the server for whicb these directives -/// are valid in the form 'host:server' or 'server://host' -/// with server either "sock[d]", "root[d]" or -/// 0, 1, respectively. - -ROOT::Deprecated::THostAuth::THostAuth(const char *host, const char *user, Int_t nmeth, - Int_t *authmeth, char **details) : TObject() -{ - Create(host, user, nmeth, authmeth, details); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Create hostauth object. -/// 'host' may contain also the server for whicb these directives -/// are valid in the form 'host:server' or 'server://host' -/// with server either "sock[d]", "root[d]" or -/// 0, 1, respectively. - -ROOT::Deprecated::THostAuth::THostAuth(const char *host, Int_t server, const char *user, - Int_t nmeth, Int_t *authmeth, char **details) : TObject() -{ - Create(host, user, nmeth, authmeth, details); - - fServer = server; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Create hostauth object with one method only. -/// 'host' may contain also the server for whicb these directives -/// are valid in the form 'host:server' or 'server://host' - -ROOT::Deprecated::THostAuth::THostAuth(const char *host, const char *user, Int_t authmeth, - const char *details) : TObject() -{ - Create(host, user, 1, &authmeth, (char **)&details); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Create hostauth object with one method only. -/// 'host' may contain also the server for whicb these directives -/// are valid in the form 'host:server' or 'server://host' - -ROOT::Deprecated::THostAuth::THostAuth(const char *host, Int_t server, const char *user, - Int_t authmeth, const char *details) : TObject() -{ - Create(host, user, 1, &authmeth, (char **)&details); - fServer = server; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Create hostauth object. -/// 'host' may contain also the server for whicb these directives -/// are valid in the form 'host:server' or 'server://host' -/// with server either "sock[d]", "root[d]" or -/// 0, 1, respectively. - -void ROOT::Deprecated::THostAuth::Create(const char *host, const char *user, Int_t nmeth, - Int_t *authmeth, char **details) -{ - int i; - - // Host - fHost = host; - - fServer = -1; - // Extract server, if given - TString srv(""); - if (fHost.Contains(":")) { - // .rootauthrc form: host:server - srv = fHost; - fHost.Remove(fHost.Index(":")); - srv.Remove(0,srv.Index(":")+1); - } else if (fHost.Contains("://")) { - // Url form: server://host - srv = TUrl(fHost).GetProtocol(); - fHost.Remove(0,fHost.Index("://")+3); - } - if (srv.Length()) { - if (srv == "0" || srv.BeginsWith("sock")) - fServer = TSocket::kSOCKD; - else if (srv == "1" || srv.BeginsWith("root")) - fServer = TSocket::kROOTD; - } - - // Check and save the host FQDN ... - if (fHost != "default" && !fHost.Contains("*")) { - TInetAddress addr = gSystem->GetHostByName(fHost); - if (addr.IsValid()) - fHost = addr.GetHostName(); - } - - // User - fUser = user; - if (fUser == "") - fUser = gSystem->Getenv("USER"); - if (fUser == "") { - UserGroup_t *u = gSystem->GetUserInfo(); - if (u) - fUser = u->fUser; - delete u; - } - - // Methods indexes - fNumMethods = nmeth; - if (fNumMethods > 0) { - if (!authmeth) - fNumMethods = 0; - for (i = 0; i < kMAXSEC; i++) { - if (i < fNumMethods) { - fMethods[i] = authmeth[i]; - fSuccess[i] = 0; - fFailure[i] = 0; - } else { - fMethods[i] = -1; - fSuccess[i] = -1; - fFailure[i] = -1; - } - } - } - - // Method details - if (fNumMethods > 0) { - for (i = 0; i < fNumMethods; i++) { - if (details && details[i] && strlen(details[i]) > 0) { - fDetails[i] = details[i]; - } else { - // Use default instead - char *tmp = TAuthenticate::GetDefaultDetails(fMethods[i],0,fUser); - fDetails[i] = (const char *)tmp; - delete[] tmp; - } - } - } - - // List of TSecContext - fSecContexts = new TList; - - // Active when created - fActive = kTRUE; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Copy ctor ... - -ROOT::Deprecated::THostAuth::THostAuth(THostAuth &ha) : TObject() -{ - fHost = ha.fHost; - fServer = ha.fServer; - fUser = ha.fUser; - fNumMethods = ha.fNumMethods; - Int_t i = 0; - for (; i < kMAXSEC; i++) { - fMethods[i] = ha.fMethods[i]; - fSuccess[i] = ha.fSuccess[i]; - fFailure[i] = ha.fFailure[i]; - fDetails[i] = ha.fDetails[i]; - } - fSecContexts = ha.Established(); - fActive = ha.fActive; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Add method to the list. If already there, change its -/// details to 'details' - -void ROOT::Deprecated::THostAuth::AddMethod(Int_t meth, const char *details) -{ - // Check 'meth' - if (meth < 0 || meth >= kMAXSEC) return; - - // If already there, set details and return - if (HasMethod(meth)) { - SetDetails(meth,details); - return; - } - - // This is a new method - fMethods[fNumMethods] = meth; - fSuccess[fNumMethods] = 0; - fFailure[fNumMethods] = 0; - if (details && strlen(details) > 0) { - fDetails[fNumMethods] = details; - } else { - // Use default instead - char *tmp = TAuthenticate::GetDefaultDetails(meth,0,fUser); - fDetails[fNumMethods] = (const char *)tmp; - delete[] tmp; - } - - // Increment total number - fNumMethods++; - - if (gDebug > 3) Print(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Remove method 'meth' from the list, if there ... - -void ROOT::Deprecated::THostAuth::RemoveMethod(Int_t meth) -{ - // If we don't have it, nothing to do - Int_t pos = -1; - if (!HasMethod(meth,&pos)) return; - - // Now rescale info - Int_t i = 0, k = 0; - for (; i < fNumMethods; i++) { - if (i != pos) { - fMethods[k] = fMethods[i]; - fSuccess[k] = fSuccess[i]; - fFailure[k] = fFailure[i]; - fDetails[k] = fDetails[i]; - k++; - } - } - - // Decrement total number - fNumMethods--; - - // Free last position - fMethods[fNumMethods] = -1; - fSuccess[fNumMethods] = -1; - fFailure[fNumMethods] = -1; - fDetails[fNumMethods].Resize(0); - - if (gDebug > 3) Print(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Remove all methods, leaving Active status and -/// list of associted TSceContexts unchanged - -void ROOT::Deprecated::THostAuth::Reset() -{ - // Free all filled positions - Int_t i = 0; - for (; i < fNumMethods; i++) { - fMethods[i] = -1; - fSuccess[i] = -1; - fFailure[i] = -1; - fDetails[i].Resize(0); - } - - // Set total number to 0 - fNumMethods = 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// The dtor. - -ROOT::Deprecated::THostAuth::~THostAuth() -{ - delete fSecContexts; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Return authentication details for specified level -/// or "" if the specified level does not exist for this host. - -const char *ROOT::Deprecated::THostAuth::GetDetails(Int_t level) -{ - Int_t i = -1; - if (HasMethod(level,&i)) { - if (gDebug > 3) - Info("GetDetails"," %d: returning fDetails[%d]: %s", - level,i,fDetails[i].Data()); - return fDetails[i]; - } - static const char *empty = " "; - return empty; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Return kTRUE if method 'level' is in the list - -Bool_t ROOT::Deprecated::THostAuth::HasMethod(Int_t level, Int_t *pos) -{ - int i; - for (i = 0; i < fNumMethods; i++) { - if (fMethods[i] == level) { - if (pos) *pos = i; - return kTRUE; - } - } - if (pos) *pos = -1; - return kFALSE; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set authentication details for specified level. - -void ROOT::Deprecated::THostAuth::SetDetails(Int_t level, const char *details) -{ - Int_t i = -1; - if (HasMethod(level,&i)) { - if (details && strlen(details) > 0) { - fDetails[i] = details; - } else { - // Use default instead - char *tmp = TAuthenticate::GetDefaultDetails(level,0,fUser); - fDetails[i] = (const char *)tmp; - delete[] tmp; - } - } else { - // Add new method ... - AddMethod(level, details); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Print object content. - -void ROOT::Deprecated::THostAuth::Print(Option_t *proc) const -{ - char srvnam[4][8] = { "any", "sockd", "rootd", "???" }; - - Int_t isrv = (fServer >= -1 && fServer <= TSocket::kROOTD) ? - fServer+1 : TSocket::kROOTD+2; - - Info("Print", - "%s +------------------------------------------------------------------+",proc); - Info("Print","%s + Host:%s - srv:%s - User:%s - # of available methods:%d", - proc, fHost.Data(), srvnam[isrv], fUser.Data(), fNumMethods); - int i = 0; - for (i = 0; i < fNumMethods; i++){ - Info("Print","%s + Method: %d (%s) Ok:%d Ko:%d Dets:%s", proc, - fMethods[i],TAuthenticate::GetAuthMethod(fMethods[i]), - fSuccess[i], fFailure[i], fDetails[i].Data()); - } - Info("Print", - "%s +------------------------------------------------------------------+",proc); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Print info about established authentication vis-a-vis of this Host. - -void ROOT::Deprecated::THostAuth::PrintEstablished() const -{ - Info("PrintEstablished", - "+------------------------------------------------------------------------------+"); - Info("PrintEstablished","+ Host:%s - Number of active sec contexts: %d", - fHost.Data(), fSecContexts->GetSize()); - - // Check list - if (fSecContexts->GetSize()>0) { - TIter next(fSecContexts); - TSecContext *ctx = 0; - Int_t k = 1; - while ((ctx = (TSecContext *) next())) { - TString opt; - opt += k++; - ctx->Print(opt); - } - } - Info("PrintEstablished", - "+------------------------------------------------------------------------------+"); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Reorder nmet methods according fmet[nmet] - -void ROOT::Deprecated::THostAuth::ReOrder(Int_t nmet, Int_t *fmet) -{ - // Temporary arrays - Int_t tMethods[kMAXSEC] = {0}; - Int_t tSuccess[kMAXSEC] = {0}; - Int_t tFailure[kMAXSEC] = {0}; - TString tDetails[kMAXSEC]; - Int_t flag[kMAXSEC] = {0}; - - // Copy info in the new order - Int_t j = 0; - for ( ; j < nmet; j++) { - Int_t i = -1; - if (HasMethod(fmet[j],&i)) { - tMethods[j] = fMethods[i]; - tSuccess[j] = fSuccess[i]; - tFailure[j] = fFailure[i]; - tDetails[j] = fDetails[i]; - flag[i]++; - } else if (fmet[j] >= 0 && fmet[j] < kMAXSEC) { - tMethods[j] = fmet[j]; - tSuccess[j] = 0; - tFailure[j] = 0; - char *tmp = TAuthenticate::GetDefaultDetails(fmet[j],0,fUser); - tDetails[j] = (const char *)tmp; - delete[] tmp; - } else { - Warning("ReOrder","Method id out of range (%d) - skipping",fmet[j]); - } - } - - // Add existing methods not listed ... if any - Int_t k = nmet, i = 0; - for(; i < fNumMethods; i++){ - if (flag[i] == 0) { - tMethods[k] = fMethods[i]; - tSuccess[k] = fSuccess[i]; - tFailure[k] = fFailure[i]; - tDetails[k] = fDetails[i]; - k++; - flag[i] = 1; - } - } - - // Restore from temporary - fNumMethods = k; - for (i = 0; i < fNumMethods; i++) { - fMethods[i] = tMethods[i]; - fSuccess[i] = tSuccess[i]; - fFailure[i] = tFailure[i]; - fDetails[i] = tDetails[i]; - } - - if (gDebug > 3) Print(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Update info with the one in ha -/// Remaining methods, if any, get lower priority - -void ROOT::Deprecated::THostAuth::Update(THostAuth *ha) -{ - // Temporary arrays - Int_t tNumMethods = fNumMethods; - Int_t tMethods[kMAXSEC]; - Int_t tSuccess[kMAXSEC]; - Int_t tFailure[kMAXSEC]; - TString tDetails[kMAXSEC]; - - // Save existing info in temporary arrays - Int_t i = 0; - for ( ; i < fNumMethods; i++) { - tMethods[i] = fMethods[i]; - tSuccess[i] = fSuccess[i]; - tFailure[i] = fFailure[i]; - tDetails[i] = fDetails[i]; - } - - // Reset - Reset(); - - // Get ha content in - for(i = 0; i < ha->NumMethods(); i++){ - fMethods[i] = ha->GetMethod(i); - fSuccess[i] = ha->GetSuccess(i); - fFailure[i] = ha->GetFailure(i); - fDetails[i] = ha->GetDetailsByIdx(i); - } - - // Set new tmp size - fNumMethods = ha->NumMethods(); - - // Add remaining methods with low priority - if (fNumMethods < kMAXSEC) { - for (i = 0; i < tNumMethods; i++) { - if (!HasMethod(tMethods[i]) && fNumMethods < kMAXSEC) { - fMethods[fNumMethods] = tMethods[i]; - fSuccess[fNumMethods] = tSuccess[i]; - fFailure[fNumMethods] = tFailure[i]; - fDetails[fNumMethods] = tDetails[i]; - fNumMethods++; - } - } - } - if (gDebug > 3) Print(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set 'method' to be the first used (if in the list ...). - -void ROOT::Deprecated::THostAuth::SetFirst(Int_t method) -{ - Int_t i = -1; - if (HasMethod(method,&i)) { - - Int_t tMe = fMethods[i]; - Int_t tSu = fSuccess[i]; - Int_t tFa = fFailure[i]; - TString tDe = fDetails[i]; - - // Rescale methods - Int_t j = i; - for (; j > 0; j--) { - fMethods[j] = fMethods[j-1]; - fSuccess[j] = fSuccess[j-1]; - fFailure[j] = fFailure[j-1]; - fDetails[j] = fDetails[j-1]; - } - - // The saved method first - fMethods[0] = tMe; - fSuccess[0] = tSu; - fFailure[0] = tFa; - fDetails[0] = tDe; - } - - if (gDebug > 3) Print(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set 'method' to be the last used (if in the list ...). - -void ROOT::Deprecated::THostAuth::SetLast(Int_t method) -{ - Int_t i = -1; - if (HasMethod(method,&i)) { - - Int_t tMe = fMethods[i]; - Int_t tSu = fSuccess[i]; - Int_t tFa = fFailure[i]; - TString tDe = fDetails[i]; - - // Rescale methods - Int_t j = i; - for (; j < (fNumMethods - 1); j++) { - fMethods[j] = fMethods[j+1]; - fSuccess[j] = fSuccess[j+1]; - fFailure[j] = fFailure[j+1]; - fDetails[j] = fDetails[j+1]; - } - - // The saved method first - Int_t lp = fNumMethods - 1; - fMethods[lp] = tMe; - fSuccess[lp] = tSu; - fFailure[lp] = tFa; - fDetails[lp] = tDe; - } - - if (gDebug > 3) Print(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Add new method in first position -/// If already in the list, set as first method 'level' with -/// authentication 'details'. -/// Faster then AddMethod(method,details)+SetFirst(method). - -void ROOT::Deprecated::THostAuth::AddFirst(Int_t level, const char *details) -{ - Int_t i = -1; - if (HasMethod(level,&i)) { - if (i > 0) { - SetDetails(level, details); - SetFirst(level); - } - if (gDebug > 3) Print(); - return; - } - - // Rescale methods - for (i = fNumMethods; i > 0; i--) { - fMethods[i] = fMethods[i-1]; - fSuccess[i] = fSuccess[i-1]; - fFailure[i] = fFailure[i-1]; - fDetails[i] = fDetails[i-1]; - } - - // This method first - fMethods[0] = level; - fSuccess[0] = 0; - fFailure[0] = 0; - if (details && strlen(details) > 0) { - fDetails[0] = details; - } else { - // Use default instead - char *tmp = TAuthenticate::GetDefaultDetails(level,0,fUser); - fDetails[0] = (const char *)tmp; - delete[] tmp; - } - - // Increment total number - fNumMethods++; - - if (gDebug > 3) Print(); -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Count successes for 'method' - -void ROOT::Deprecated::THostAuth::CountSuccess(Int_t method) -{ - int i; - for (i = 0; i < fNumMethods; i++) { - if (fMethods[i] == method) { - fSuccess[i]++; - break; - } - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Count failures for 'method' - -void ROOT::Deprecated::THostAuth::CountFailure(Int_t method) -{ - int i; - for (i = 0; i < fNumMethods; i++) { - if (fMethods[i] == method) { - fFailure[i]++; - break; - } - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Create a Security context and add it to local list -/// Return pointer to it to be stored in TAuthenticate - -ROOT::Deprecated::TRootSecContext * -ROOT::Deprecated::THostAuth::CreateSecContext(const char *user, const char *host, - Int_t meth, Int_t offset, - const char *details, const char *token, - TDatime expdate, void *sctx, Int_t key) -{ - auto *ctx = new TRootSecContext(user, host, meth, offset, details, token, expdate, sctx, key); - // Add it also to the local list if active - if (ctx->IsActive()) - fSecContexts->Add(ctx); - - return ctx; - -} - -//////////////////////////////////////////////////////////////////////////////// -/// Return a static string with all info in a serialized form - -void ROOT::Deprecated::THostAuth::AsString(TString &Out) const -{ - Out = Form("h:%s u:%s n:%d",GetHost(),GetUser(),fNumMethods); - - Int_t i = 0; - for (; i < fNumMethods; i++) { - Out += TString(Form(" '%d %s'",fMethods[i],fDetails[i].Data())); - } - -} diff --git a/net/auth/src/TRootAuth.cxx b/net/auth/src/TRootAuth.cxx deleted file mode 100644 index a3b85aa429b8b..0000000000000 --- a/net/auth/src/TRootAuth.cxx +++ /dev/null @@ -1,102 +0,0 @@ -// @(#)root/auth:$Id$ -// Author: Gerardo Ganis 08/07/05 - -/************************************************************************* - * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// TRootAuth // -// // -// TVirtualAuth implementation based on the old client authentication // -// code. // -// // -////////////////////////////////////////////////////////////////////////// - -#include "TAuthenticate.h" -#include "TError.h" -#include "THostAuth.h" -#include "TRootAuth.h" -#include "TRootSecContext.h" -#include "TSocket.h" -#include "TSystem.h" -#include "TUrl.h" - -//////////////////////////////////////////////////////////////////////////////// -/// Runs authentication on socket s. -/// Invoked when dynamic loading is needed. -/// Returns 1 on success, 0 on failure. - -ROOT::Deprecated::TSecContext * -ROOT::Deprecated::TRootAuth::Authenticate(TSocket *s, const char *host, const char *user, Option_t */*opts*/) -{ - TSecContext *ctx = 0; - - Int_t rproto = s->GetRemoteProtocol() % 1000; - if (s->GetServType() == (Int_t)TSocket::kROOTD) { - if (rproto > 6 && rproto < 10) { - // Middle aged versions expect client protocol now - s->Send(Form("%d", TSocket::GetClientProtocol()), kROOTD_PROTOCOL2); - Int_t kind = 0; - if (s->Recv(rproto, kind) < 0) { - Error("Authenticate", "receiving remote protocol"); - return ctx; - } - s->SetRemoteProtocol(rproto); - } - } - - // Build the protocol string for TAuthenticate - TString proto = TUrl(s->GetUrl()).GetProtocol(); - if (proto == "") { - proto = "root"; - } else if (proto.Contains("sockd") || proto.Contains("rootd")) { - proto.ReplaceAll("d",1,"",0); - } - proto += Form(":%d",rproto); - - // Init authentication - TAuthenticate *auth = - new TAuthenticate(s, host, proto, user); - - // Attempt authentication - if (!auth->Authenticate()) { - // Close the socket if unsuccessful - if (auth->HasTimedOut() > 0) - Error("Authenticate", - "timeout expired for %s@%s", auth->GetUser(), host); - else - Error("Authenticate", - "authentication failed for %s@%s", auth->GetUser(), host); - } else { - // Search pointer to relevant TSecContext - ctx = auth->GetSecContext(); - ROOT::Deprecated::TSocketFriend::SetSecContext(*s, ctx); - } - // Cleanup - delete auth; - - // We are done - return ctx; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Return client version; - -Int_t ROOT::Deprecated::TRootAuth::ClientVersion() -{ - return TSocket::GetClientProtocol(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Print error string corresponding to ecode, prepending location - -void ROOT::Deprecated::TRootAuth::ErrorMsg(const char *where, Int_t ecode) -{ - TAuthenticate::AuthError(where, ecode); -} diff --git a/net/auth/src/TRootSecContext.cxx b/net/auth/src/TRootSecContext.cxx deleted file mode 100644 index 35dea54215b1a..0000000000000 --- a/net/auth/src/TRootSecContext.cxx +++ /dev/null @@ -1,260 +0,0 @@ -// @(#)root/auth:$Id$ -// Author: G. Ganis 08/07/2005 - -/************************************************************************* - * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// TRootSecContext // -// // -// Special implementation of TSecContext // -// // -////////////////////////////////////////////////////////////////////////// - -#include "RConfigure.h" - -#include - -#include "TError.h" -#include "TRootSecContext.h" -#include "TROOT.h" -#include "TSocket.h" -#include "TUrl.h" -#include "TVirtualMutex.h" - - -//////////////////////////////////////////////////////////////////////////////// -/// Ctor for SecContext object. - -ROOT::Deprecated::TRootSecContext::TRootSecContext(const char *user, const char *host, Int_t meth, - Int_t offset, const char *id, - const char *token, TDatime expdate, - void *ctx, Int_t key) - : TSecContext(user, host, meth, offset, id, token, expdate, ctx) -{ - R__ASSERT(gROOT); - - fRSAKey = key; - fMethodName = TAuthenticate::GetAuthMethod(fMethod); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Ctor for SecContext object. -/// User and host from url = `user@host` . - -ROOT::Deprecated::TRootSecContext::TRootSecContext(const char *url, Int_t meth, Int_t offset, - const char *id, const char *token, - TDatime expdate, void *ctx, Int_t key) - : TSecContext(url, meth, offset, id, token, expdate, ctx) -{ - R__ASSERT(gROOT); - - fRSAKey = key; - fMethodName = TAuthenticate::GetAuthMethod(fMethod); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Dtor: delete (deActivate, local/remote cleanup, list removal) -/// all what is still active - -ROOT::Deprecated::TRootSecContext::~TRootSecContext() -{ - TSecContext::Cleanup(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set OffSet to -1 and expiring Date to default -/// Remove from the list -/// If Opt contains "C" or "c", ask for remote cleanup -/// If Opt contains "R" or "r", remove from the list -/// Default Opt="CR" - -void ROOT::Deprecated::TRootSecContext::DeActivate(Option_t *Opt) -{ - // Ask remote cleanup of this context - Bool_t clean = (strstr(Opt,"C") || strstr(Opt,"c")); - if (clean && fOffSet > -1) - CleanupSecContext(kFALSE); - - // Cleanup TPwdCtx object fro UsrPwd - if (fMethod == TAuthenticate::kClear) - if (fContext) { - delete (TPwdCtx *)fContext; - fContext = 0; - } - - Bool_t remove = (strstr(Opt,"R") || strstr(Opt,"r")); - if (remove && fOffSet > -1){ - R__LOCKGUARD(gROOTMutex); - // Remove from the global list - ROOT::Deprecated::Internal::GetListOfSecContexts(*gROOT)->Remove(this); - // Remove also from local lists in THostAuth objects - TAuthenticate::RemoveSecContext(this); - } - - // Set inactive - fOffSet = -1; - fExpDate = kROOTTZERO; - -} - -//////////////////////////////////////////////////////////////////////////////// -/// Ask remote client to cleanup security context 'ctx' -/// If 'all', all sec context with the same host as ctx -/// are cleaned. - -Bool_t ROOT::Deprecated::TRootSecContext::CleanupSecContext(Bool_t all) -{ - Bool_t cleaned = kFALSE; - - // Nothing to do if inactive ... - if (!IsActive()) - return kTRUE; - - // Contact remote services that used this context, - // starting from the last ... - TIter last(fCleanup,kIterBackward); - TSecContextCleanup *nscc = 0; - while ((nscc = (TSecContextCleanup *)last()) && !cleaned) { - - // First check if remote daemon supports cleaning - Int_t srvtyp = nscc->GetType(); - Int_t rproto = nscc->GetProtocol(); - Int_t level = 2; - if ((srvtyp == TSocket::kROOTD && rproto < 10)) - level = 1; - if ((srvtyp == TSocket::kROOTD && rproto < 8)) - level = 0; - if (level) { - Int_t port = nscc->GetPort(); - - TSocket *news = new TSocket(fHost.Data(),port,-1); - - if (news && news->IsValid()) { - news->SetOption(kNoDelay, 0); - - // Backward compatibility: send socket size - if (srvtyp == TSocket::kROOTD && level == 1) - news->Send((Int_t)0, (Int_t)0); - - if (all || level == 1) { - news->Send(Form("%d",TAuthenticate::fgProcessID), kROOTD_CLEANUP); - cleaned = kTRUE; - } else { - news->Send(Form("%d %d %d %s", TAuthenticate::fgProcessID, fMethod, - fOffSet, fUser.Data()), kROOTD_CLEANUP); - if (TAuthenticate::SecureSend(news, 1, fRSAKey, - (char *)(fToken.Data())) == -1) { - Info("CleanupSecContext", "problems secure-sending token"); - } else { - cleaned = kTRUE; - } - } - if (cleaned && gDebug > 2) { - char srvname[3][10] = {"sockd", "rootd"}; - Info("CleanupSecContext", - "remote %s notified for cleanup (%s,%d)", - srvname[srvtyp],fHost.Data(),port); - } - } - SafeDelete(news); - } - } - - if (!cleaned) - if (gDebug > 2) - Info("CleanupSecContext", - "unable to open valid socket for cleanup for %s", fHost.Data()); - - return cleaned; -} - -//////////////////////////////////////////////////////////////////////////////// -/// If opt is "F" (default) print object content. -/// If opt is "" print in special form for calls within THostAuth -/// with cardinality "" -/// If opt is "S" prints short in-line form for calls within TFTP, -/// TSlave ... - -void ROOT::Deprecated::TRootSecContext::Print(Option_t *opt) const -{ - // Check if option is numeric - Int_t ord = -1, i = 0; - for (; i < (Int_t)strlen(opt); i++) { - if (opt[i] < 48 || opt[i] > 57) { - ord = -2; - break; - } - } - // If numeric get the cardinality and prepare the strings - if (ord == -1) - ord = atoi(opt); - - if (!strncasecmp(opt,"F",1)) { - Info("Print", - "+------------------------------------------------------+"); - Info("Print", - "+ Host:%s Method:%d (%s) User:'%s'", - GetHost(), fMethod, GetMethodName(), - fUser.Data()); - Info("Print", - "+ OffSet:%d Id: '%s'", fOffSet, fID.Data()); - if (fOffSet > -1) - Info("Print", - "+ Expiration time: %s",fExpDate.AsString()); - Info("Print", - "+------------------------------------------------------+"); - } else if (!strncasecmp(opt,"S",1)) { - if (fOffSet > -1) { - if (fID.BeginsWith("AFS")) - Printf("Security context: Method: AFS, not reusable"); - else - Printf("Security context: Method: %d (%s) expiring on %s", - fMethod, GetMethodName(), - fExpDate.AsString()); - } else { - Printf("Security context: Method: %d (%s) not reusable", - fMethod, GetMethodName()); - } - } else { - // special printing form for THostAuth - Info("PrintEstblshed","+ %d \t h:%s met:%d (%s) us:'%s'", - ord, GetHost(), fMethod, GetMethodName(), - fUser.Data()); - Info("PrintEstblshed","+ \t offset:%d id: '%s'", fOffSet, fID.Data()); - if (fOffSet > -1) - Info("PrintEstblshed","+ \t expiring: %s",fExpDate.AsString()); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Returns short string with relevant information about this -/// security context - -const char *ROOT::Deprecated::TRootSecContext::AsString(TString &out) -{ - if (fOffSet > -1) { - if (fID.BeginsWith("AFS")) - out = Form("Method: AFS, not reusable"); - else { - char expdate[32]; - out = Form("Method: %d (%s) expiring on %s", - fMethod, GetMethodName(), fExpDate.AsString(expdate)); - } - } else { - if (fOffSet == -1) - out = Form("Method: %d (%s) not reusable", fMethod, GetMethodName()); - else if (fOffSet == -3) - out = Form("Method: %d (%s) authorized by /etc/hosts.equiv or $HOME/.rhosts", - fMethod, GetMethodName()); - else if (fOffSet == -4) - out = Form("No authentication required remotely"); - } - return out.Data(); -} diff --git a/net/auth/src/rsaaux.cxx b/net/auth/src/rsaaux.cxx deleted file mode 100644 index ea004b09896f8..0000000000000 --- a/net/auth/src/rsaaux.cxx +++ /dev/null @@ -1,1133 +0,0 @@ -/* @(#)root/auth:$Id$ */ -/* Author: Martin Nicolay 22/11/1988 */ - -/****************************************************************************** -Copyright (C) 2006 Martin Nicolay - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later -version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free -Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, -MA 02110-1301 USA -******************************************************************************/ - -/******************************************************************************* -* * -* Simple RSA public key code. * -* Adaptation in library for ROOT by G. Ganis, July 2003 * -* (gerardo.ganis@cern.ch) * -* * -*******************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef WIN32 -# include -typedef long off_t; -#else -# include -# include -#endif - -#include "rsaaux.h" -#include "rsalib.h" - -/******************************************************************************** - * * - * arith.c * - * * - ********************************************************************************/ - -/* - * !!!!!!!!!!!!!!!!!!!!!!!!!!!! ACHTUNG !!!!!!!!!!!!!!!!!!!!!!!!!!!! - * Es findet keinerlei Ueberpruefung auf Bereichsueberschreitung - * statt. Alle Werte muessen natuerliche Zahlen aus dem Bereich - * 0 ... (rsa_MAXINT+1)^rsa_MAXLEN-1 sein. - * - * - * Bei keiner Funktion oder Hilsfunktion werden Annahmen getroffen, - * ueber die Verschiedenheit von Eingabe- & Ausgabe-Werten. - * - * - * Funktionen: - * - * a_add( s1, s2, d ) - * rsa_NUMBER *s1,*s2,*d; - * *d = *s1 + *s2; - * - * a_assign( *d, *s ) - * rsa_NUMBER *d,*s; - * *d = *s; - * - * int a_cmp( c1, c2 ) - * rsa_NUMBER *c1,*c2; - * 1 : falls *c1 > *c2 - * 0 : falls *c1 == *c2 - * -1 : falls *c1 < *c2 - * - * a_div( d1, d2, q, r ) - * rsa_NUMBER *d1,*d2,*q,*r; - * *q = *d1 / *d2 Rest *r; - * - * a_div2( n ) - * rsa_NUMBER *n; - * *n /= 2; - * - * a_ggt( a, b, f ) - * rsa_NUMBER *a,*b,*f; - * *f = ( *a, *b ); - * - * a_imult( n, m, d ) - * rsa_NUMBER *n; - * rsa_INT m; - * rsa_NUMBER *d; - * *d = *n * m - * - * a_mult( m1, m2, d ) - * rsa_NUMBER *m1,*m2,*d; - * *d = *m1 * *m2; - * - * a_sub( s1, s2, d ) - * rsa_NUMBER *s1,*s2,*d; - * *d = *s1 - *s2; - * - * Modulare Funktionen - * m_init( n, o ) - * rsa_NUMBER *n,*o; - * Initialsierung der Modularen Funktionen - * o != 0 : *o = alter Wert - * - * m_add( s1, s2, d ) - * rsa_NUMBER *s1, *s2, *d; - * *d = *s1 + *s2; - * - * m_mult( m1, m2, d ) - * rsa_NUMBER *m1,*m2,*d; - * - * m_exp( x, n, z ) - * rsa_NUMBER *x,*n,*z; - * *z = *x exp *n; - * - * - * Hilfs-Funktionen: - * - * int n_bits( n, b ) - * rsa_NUMBER *n; - * int b; - * return( unterste b Bits der Dualdarstellung von n) - * - * n_div( d1, z2, q, r ) - * rsa_NUMBER *d1,z2[rsa_MAXBIT],*q,*r; - * *q = *d1 / z2[0] Rest *r; - * z2[i] = z2[0] * 2^i, i=0..rsa_MAXBIT-1 - * - * int n_cmp( i1, i2, l ) - * rsa_INT i1[l], i2[l]; - * 1 : falls i1 > i2 - * 0 : falls i1 == i2 - * -1 : falls i1 < i2 - * - * int n_mult( n, m, d, l) - * rsa_INT n[l], m, d[]; - * d = m * n; - * return( sizeof(d) ); d.h. 'l' oder 'l+1' - * - * int n_sub( p1, p2, p3, l, lo ) - * rsa_INT p1[l], p2[lo], p3[]; - * p3 = p1 - p2; - * return( sizeof(p3) ); d.h. '<= min(l,lo)' - * - * int n_bitlen( n ) - * rsa_NUMBER *n; - * return( sizeof(n) in bits ) - * - */ - - -//////////////////////////////////////////////////////////////////////////////// -/// rand() implementation using /udev/random or /dev/random, if available - -static int aux_rand() -{ -#ifndef WIN32 - int frnd = open("/dev/urandom", O_RDONLY); - if (frnd < 0) frnd = open("/dev/random", O_RDONLY); - int r; - if (frnd >= 0) { - ssize_t rs = read(frnd, (void *) &r, sizeof(int)); - close(frnd); - if (r < 0) r = -r; - if (rs == sizeof(int)) return r; - } - printf("+++ERROR+++ : aux_rand: neither /dev/urandom nor /dev/random are available or readable!\n"); - struct timeval tv; - if (gettimeofday(&tv,0) == 0) { - int t1, t2; - memcpy((void *)&t1, (void *)&tv.tv_sec, sizeof(int)); - memcpy((void *)&t2, (void *)&tv.tv_usec, sizeof(int)); - r = t1 + t2; - if (r < 0) r = -r; - return r; - } - return -1; -#else - // No special random device available: use rand() - return rand(); -#endif -} - -/* - * Konstante 1, 2 - */ -rsa_NUMBER a_one = { - 1, - { (rsa_INT)1, }, -}; - -rsa_NUMBER a_two = { -#if rsa_MAXINT == 1 - 2, - { 0, (rsa_INT)1, }, -#else - 1, - { (rsa_INT)2, }, -#endif -}; - - -/* - * Vergleiche zwei rsa_INT arrays der Laenge l - */ -int n_cmp(rsa_INT *i1, rsa_INT *i2, int l) -{ - i1 += (l-1); /* Pointer ans Ende */ - i2 += (l-1); - - for (;l--;) - if ( *i1-- != *i2-- ) - return( i1[1] > i2[1] ? 1 : -1 ); - - return(0); -} - -/* - * Vergleiche zwei rsa_NUMBER - */ -int a_cmp(rsa_NUMBER *c1, rsa_NUMBER *c2) -{ - int l; - /* bei verschiedener Laenge klar*/ - if ( (l=c1->n_len) != c2->n_len) - return( l - c2->n_len); - - /* vergleiche als arrays */ - return( n_cmp( c1->n_part, c2->n_part, l) ); -} - -/* - * Zuweisung einer rsa_NUMBER (d = s) - */ -void a_assign(rsa_NUMBER *d, rsa_NUMBER *s) -{ - int l; - - if (s == d) /* nichts zu kopieren */ - return; - - if ((l=s->n_len)) - memcpy( d->n_part, s->n_part, sizeof(rsa_INT)*l); - - d->n_len = l; -} - -/* - * Addiere zwei rsa_NUMBER (d = s1 + s2) - */ -void a_add(rsa_NUMBER *s1, rsa_NUMBER *s2, rsa_NUMBER *d) -{ - int l,lo,ld,same; - rsa_LONG sum; - rsa_INT *p1,*p2,*p3; - rsa_INT b; - - /* setze s1 auch die groessere Zahl */ - l = s1->n_len; - if ( (l=s1->n_len) < s2->n_len) { - rsa_NUMBER *tmp = s1; - - s1 = s2; - s2 = tmp; - - l = s1->n_len; - } - - ld = l; - lo = s2->n_len; - p1 = s1->n_part; - p2 = s2->n_part; - p3 = d->n_part; - same = (s1 == d); - sum = 0; - - while (l --) { - if (lo) { /* es ist noch was von s2 da */ - lo--; - b = *p2++; - } - else - b = 0; /* ansonten 0 nehmen */ - - sum += (rsa_LONG)*p1++ + (rsa_LONG)b; - *p3++ = rsa_TOINT(sum); - - if (sum > (rsa_LONG)rsa_MAXINT) { /* carry merken */ - sum = 1; - } - else - sum = 0; - - if (!lo && same && !sum) /* nichts mehr zu tuen */ - break; - } - - if (sum) { /* letztes carry beruecksichtigen */ - ld++; - *p3 = sum; - } - - d->n_len = ld; /* Laenge setzen */ -} - -/* - * Subtrahiere zwei rsa_INT arrays. return( Laenge Ergebniss ) - * l == Laenge p1 - * lo== Laenge p3 - */ -int n_sub(rsa_INT *p1, rsa_INT *p2, rsa_INT *p3, int l, int lo) -{ - int ld,lc,same; - int over = 0; - rsa_LONG dif; - rsa_LONG a,b; - - same = (p1 == p3); /* frueher Abbruch moeglich */ - - for (lc=1, ld=0; l--; lc++) { - a = (rsa_LONG)*p1++; - if (lo) { /* ist noch was von p2 da ? */ - lo--; - b = (rsa_LONG)*p2++; - } - else - b=0; /* ansonten 0 nehmen */ - - if (over) /* frueherer Overflow */ - b++; - if ( b > a) { /* jetzt Overflow ? */ - over = 1; - dif = (rsa_MAXINT +1) + a; - } - else { - over = 0; - dif = a; - } - dif -= b; - *p3++ = (rsa_INT)dif; - - if (dif) /* Teil != 0 : Laenge neu */ - ld = lc; - if (!lo && same && !over) { /* nichts mehr zu tuen */ - if (l > 0) /* Laenge korrigieren */ - ld = lc + l; - break; - } - } - - return( ld ); -} - -/* - * Subtrahiere zwei rsa_NUMBER (d= s1 - s2) - */ -void a_sub(rsa_NUMBER *s1, rsa_NUMBER *s2, rsa_NUMBER *d) -{ - d->n_len = n_sub( s1->n_part, s2->n_part, d->n_part - ,s1->n_len, s2->n_len ); -} - -/* - * Mulitipliziere rsa_INT array der Laenge l mit einer rsa_INT (d = n * m) - * return neue Laenge - */ -int n_mult(rsa_INT *n, rsa_INT m, rsa_INT *d, int l) -{ - int i; - rsa_LONG mul; - - for (i=l,mul=0; i; i--) { - mul += (rsa_LONG)m * (rsa_LONG)*n++; - *d++ = rsa_TOINT(mul); - mul = rsa_DIVMAX1( mul ); - } - - if (mul) { /* carry ? */ - l++; - *d = mul; - } - - return( l ); -} - -/* - * Mulitipliziere eine rsa_NUMBER mit einer rsa_INT (d = n * m) - */ -void a_imult(rsa_NUMBER *n, rsa_INT m, rsa_NUMBER *d) -{ - if (m == 0) - d->n_len=0; - else if (m == 1) - a_assign( d, n ); - else - d->n_len = n_mult( n->n_part, m, d->n_part, n->n_len ); -} - -/* - * Multipliziere zwei rsa_NUMBER (d = m1 * m2) - */ -void a_mult(rsa_NUMBER *m1, rsa_NUMBER *m2, rsa_NUMBER *d) -{ - static rsa_INT id[ rsa_MAXLEN ]; /* Zwischenspeicher */ - rsa_INT *vp; /* Pointer darin */ - rsa_LONG sum; /* Summe fuer jede Stelle */ - rsa_LONG tp1; /* Zwischenspeicher fuer m1 */ - rsa_INT *p2; - rsa_INT *p1; - int l1,l2,ld,lc,l,i,j; - - l1 = m1->n_len; - l2 = m2->n_len; - l = l1 + l2; - if (l >= rsa_MAXLEN) - abort(); - - for (i=l, vp=id; i--;) - *vp++ = 0; - - /* ohne Uebertrag in Zwischenspeicher multiplizieren */ - for ( p1 = m1->n_part, i=0; i < l1 ; i++, p1++) { - - tp1 = (rsa_LONG)*p1; - vp = &id[i]; - sum = 0; - for ( p2 = m2->n_part, j = l2; j--;) { - sum += (rsa_LONG)*vp + (tp1 * (rsa_LONG)*p2++); - *vp++ = rsa_TOINT( sum ); - sum = rsa_DIVMAX1(sum); - } - *vp++ += (rsa_INT)sum; - } - - /* jetzt alle Uebertraege beruecksichtigen */ - ld = 0; - for (lc=0, vp=id, p1=d->n_part; lc++ < l;) { - if ( (*p1++ = *vp++)) - ld = lc; - } - - d->n_len = ld; -} - - -/* - * Dividiere Zwei rsa_NUMBER mit Rest (q= d1 / z2[0] Rest r) - * z2[i] = z2[0] * 2^i, i=0..rsa_MAXBIT-1 - * r = 0 : kein Rest - * q = 0 : kein Quotient - */ -void n_div(rsa_NUMBER *d1, rsa_NUMBER *z2, rsa_NUMBER *q, rsa_NUMBER *r) -{ - static rsa_NUMBER dummy_rest; /* Dummy Variable, falls r = 0 */ - static rsa_NUMBER dummy_quot; /* Dummy Variable, falla q = 0 */ - rsa_INT *i1,*i1e,*i3; - int l2,ld,l,lq; -#if rsa_MAXINT != 1 - rsa_INT z; - int pw,l2t; -#endif - - if (!z2->n_len) - abort(); - - if (!r) - r = &dummy_rest; - if (!q) - q = &dummy_quot; - - a_assign( r, d1 ); /* Kopie von d1 in den Rest */ - - l2= z2->n_len; /* Laenge von z2[0] */ - l = r->n_len - l2; /* Laenge des noch ''rechts'' liegenden - Stuecks von d1 */ - lq= l +1; /* Laenge des Quotienten */ - i3= q->n_part + l; - i1= r->n_part + l; - ld = l2; /* aktuelle Laenge des ''Vergleichsstuecks'' - von d1 */ - i1e= i1 + (ld-1); - - for (; l >= 0; ld++, i1--, i1e--, l--, i3--) { - *i3 = 0; - - if (ld == l2 && ! *i1e) { - ld--; - continue; - } - - if ( ld > l2 || (ld == l2 && n_cmp( i1, z2->n_part, l2) >= 0) ) { -#if rsa_MAXINT != 1 - /* nach 2er-Potenzen zerlegen */ - for (pw=rsa_MAXBIT-1, z=(rsa_INT)rsa_HIGHBIT; pw >= 0; pw--, z /= 2) { - if ( ld > (l2t= z2[pw].n_len) - || (ld == l2t - && n_cmp( i1, z2[pw].n_part, ld) >= 0)) { - ld = n_sub( i1, z2[pw].n_part, i1, ld, l2t ); - (*i3) += z; - } - } -#else - /* bei rsa_MAXINT == 1 alles viel einfacher */ - ld = n_sub( i1, z2->n_part, i1, ld, l2 ); - (*i3) ++; -#endif - } - } - - /* Korrektur, falls l von Anfang an Negativ war */ - l ++; - lq -= l; - ld += l; - - if (lq>0 && !q->n_part[lq -1]) /* evtl. Laenge korrigieren */ - lq--; - - q->n_len = lq; - r->n_len = ld -1; -} - -/* - * Dividiere Zwei rsa_NUMBER mit Rest (q= d1 / z2[0] Rest r) - * z2[i] = z2[0] * 2^i, i=0..rsa_MAXBIT-1 - * r = 0 : kein Rest - * q = 0 : kein Quotient - */ -void a_div(rsa_NUMBER *d1, rsa_NUMBER *d2, rsa_NUMBER *q, rsa_NUMBER *r) -{ -#if rsa_MAXINT != 1 - rsa_NUMBER z2[rsa_MAXBIT]; - rsa_INT z; - int i; - - a_assign( &z2[0], d2 ); - for (i=1,z=2; i < rsa_MAXBIT; i++, z *= 2) - a_imult( d2, z, &z2[i] ); - - d2 = z2; -#endif - - n_div( d1, d2, q, r ); -} - -/* - * Dividiere eine rsa_NUMBER durch 2 - */ -void a_div2(rsa_NUMBER *n) -{ -#if rsa_MAXBIT == rsa_LOWBITS - rsa_INT *p; - int i; - -#if rsa_MAXINT != 1 - rsa_INT h; - int c; - - c=0; - i= n->n_len; - p= &n->n_part[i-1]; - - for (; i--;) { - if (c) { - c = (h= *p) & 1; - h /= 2; - h |= rsa_HIGHBIT; - } - else { - c = (h= *p) & 1; - h /= 2; - } - - *p-- = h; - } - - if ( (i= n->n_len) && n->n_part[i-1] == 0 ) - n->n_len = i-1; - -#else /* rsa_MAXBIT != 1 */ - p = n->n_part; - i = n->n_len; - - if (i) { - n->n_len = i-1; - for (; --i ; p++) - p[0] = p[1]; - } -#endif /* rsa_MAXBIT != 1 */ -#else /* rsa_MAXBIT == rsa_LOWBITS */ - a_div( n, &a_two, n, rsa_NUM0P ); -#endif /* rsa_MAXBIT == rsa_LOWBITS */ -} - - -/* - * MODULO-FUNKTIONEN - */ - -static rsa_NUMBER g_mod_z2[ rsa_MAXBIT ]; - -/* - * Init - */ -void m_init(rsa_NUMBER *n, rsa_NUMBER *o) -{ - rsa_INT z; - int i; - - if (o) - a_assign( o, &g_mod_z2[0] ); - - if (! a_cmp( n, &g_mod_z2[0]) ) - return; - - for (i=0,z=1; i < rsa_MAXBIT; i++, z *= 2) - a_imult( n, z, &g_mod_z2[i] ); -} - -void m_add(rsa_NUMBER *s1, rsa_NUMBER *s2, rsa_NUMBER *d) -{ - a_add( s1, s2, d ); - if (a_cmp( d, g_mod_z2) >= 0) - a_sub( d, g_mod_z2, d ); -} - -void m_mult(rsa_NUMBER *m1, rsa_NUMBER *m2, rsa_NUMBER *d) -{ - a_mult( m1, m2, d ); - n_div( d, g_mod_z2, rsa_NUM0P, d ); -} - -/* - * Restklassen Exponent - */ -void m_exp(rsa_NUMBER *x, rsa_NUMBER *n, rsa_NUMBER *z) -{ - rsa_NUMBER xt,nt; - - a_assign( &nt, n ); - a_assign( &xt, x ); - a_assign( z, &a_one ); - - while (nt.n_len) { - while ( ! (nt.n_part[0] & 1)) { - m_mult( &xt, &xt, &xt ); - a_div2( &nt ); - } - m_mult( &xt, z, z ); - a_sub( &nt, &a_one, &nt ); - } -} - -/* - * GGT - */ -void a_ggt(rsa_NUMBER *a, rsa_NUMBER *b, rsa_NUMBER *f) -{ - rsa_NUMBER t[2]; - int at,bt, tmp; - - a_assign( &t[0], a ); at= 0; - a_assign( &t[1], b ); bt= 1; - - if ( a_cmp( &t[at], &t[bt]) < 0) { - tmp= at; at= bt; bt= tmp; - } - /* euklidischer Algorithmus */ - while ( t[bt].n_len) { - a_div( &t[at], &t[bt], rsa_NUM0P, &t[at] ); - tmp= at; at= bt; bt= tmp; - } - - a_assign( f, &t[at] ); -} - -/* - * die untersten b bits der Dualdarstellung von n - * die bits muessen in ein int passen - */ -int n_bits(rsa_NUMBER *n, int b) -{ - rsa_INT *p; - int l; - unsigned r; - int m = (1<n_len == 0) - return(0); - - if (rsa_LOWBITS >= b) - return( n->n_part[0] & m ); - -#if rsa_LOWBITS != 0 - l = (b-1) / rsa_LOWBITS; -#else - l = n->n_len -1; -#endif - for (p= &n->n_part[l],r=0; l-- >= 0 && b > 0; b-= rsa_LOWBITS, p--) { - r = rsa_MULMAX1( r ); - r += (unsigned)*p; - } - - return( r & m ); -} - -/* - * Anzahl der bits von n bei Dualdarstellung - */ -int n_bitlen(rsa_NUMBER *n) -{ - rsa_NUMBER b; - int i; - - a_assign( &b, &a_one ); - - for (i=0; a_cmp( &b, n) <= 0; a_mult( &b, &a_two, &b ), i++) - ; - - return(i); -} - - -/******************************************************************************* - * * - * prim.c * - * * - ********************************************************************************/ - -/* - * RSA - * - * p,q prim - * p != q - * n = p*q - * phi = (p -1)*(q -1) - * e,d aus 0...n-1 - * e*d == 1 mod phi - * - * m aus 0...n-1 sei eine Nachricht - * - * Verschluesseln: - * E(x) = x^e mod n ( n,e oeffendlich ) - * - * Entschluesseln: - * D(x) = x^d mod n ( d geheim ) - * - * - * Sicherheit: - * - * p,q sollten bei mind. 10^100 liegen. - * (d,phi) == 1, das gilt fuer alle Primzahlen > max(p,q). - * Allerdings sollte d moeglichst gross sein ( d < phi-1 ) - * um direktes Suchen zu verhindern. - */ - - -/* - * FUNKTIONEN um RSA Schluessel zu generieren. - * - * int p_prim( n, m ) - * rsa_NUMBER *n; - * int m; - * 0 : n ist nicht prim - * 1 : n ist mit Wahrscheinlichkeit (1-1/2^m) prim - * ACHTUNG !!!! - * p_prim benutzt m_init - * - * inv( d, phi, e ) - * rsa_NUMBER *d,*phi,*e; - * *e = *d^-1 (mod phi) - * ACHTUNG !!!! - * p_prim benutzt m_init - */ - -/* - * Prototypes - */ -static int jak_f( rsa_NUMBER* ); -static int jak_g( rsa_NUMBER*, rsa_NUMBER* ); -static int jakobi( rsa_NUMBER*, rsa_NUMBER* ); - -/* - * Hilfs-Funktion fuer jakobi - */ -static int jak_f(rsa_NUMBER *n) -{ - int f,ret; - - f = n_bits( n, 3 ); - - ret = ((f == 1) || (f == 7)) ? 1 : -1; - - return(ret); -} - -/* - * Hilfs-Funktuion fuer jakobi - */ -static int jak_g(rsa_NUMBER *a, rsa_NUMBER *n) -{ - int ret; - - if ( n_bits( n, 2) == 1 || - n_bits( a, 2) == 1 ) - ret = 1; - else - ret = -1; - - return(ret); -} - -/* - * Jakobi-Symbol - */ -static int jakobi(rsa_NUMBER *a, rsa_NUMBER *n) -{ - rsa_NUMBER t[2]; - int at,nt, ret; - - a_assign( &t[0], a ); at = 0; - a_assign( &t[1], n ); nt = 1; - - /* - * b > 1 - * - * J( a, b) = - * a == 1 : 1 - * a == 2 : f(n) - * a == 2*b : J(b,n)*J(2,n) ( == J(b,n)*f(n) ) - * a == 2*b -1 : J(n % a,a)*g(a,n) - * - */ - - ret = 1; - while (1) { - if (! a_cmp(&t[at],&a_one)) { - break; - } - if (! a_cmp(&t[at],&a_two)) { - ret *= jak_f( &t[nt] ); - break; - } - if ( ! t[at].n_len ) /* Fehler :-) */ - abort(); - if ( t[at].n_part[0] & 1) { /* a == 2*b -1 */ - int tmp; - - ret *= jak_g( &t[at], &t[nt] ); - a_div( &t[nt], &t[at], rsa_NUM0P, &t[nt] ); - tmp = at; at = nt; nt = tmp; - } - else { /* a == 2*b */ - ret *= jak_f( &t[nt] ); - a_div2( &t[at] ); - } - - } - - return(ret); -} - -/* - * Probabilistischer Primzahltest - * - * 0 -> n nicht prim - * 1 -> n prim mit (1-1/2^m) Wahrscheinlichkeit. - * - * ACHTUNG !!!!!! - * p_prim benutzt m_init !! - * - */ -int p_prim(rsa_NUMBER *n, int m) -{ - rsa_NUMBER gt,n1,n2,a; - rsa_INT *p; - int i,w,j; - - if (a_cmp(n,&a_two) <= 0 || m <= 0) - abort(); - - a_sub( n, &a_one, &n1 ); /* n1 = -1 mod n */ - a_assign( &n2, &n1 ); - a_div2( &n2 ); /* n2 = ( n -1) / 2 */ - - m_init( n, rsa_NUM0P ); - - w = 1; - for (; w && m; m--) { - /* ziehe zufaellig a aus 2..n-1 */ - do { - for (i=n->n_len-1, p=a.n_part; i; i--) - *p++ = (rsa_INT)aux_rand(); - if ((i=n->n_len) ) - *p = (rsa_INT)( aux_rand() % ((unsigned long)n->n_part[i-1] +1) ); - while ( i && ! *p ) - p--,i--; - a.n_len = i; - } while ( a_cmp( &a, n) >= 0 || a_cmp( &a, &a_two) < 0 ); - - /* jetzt ist a fertig */ - - /* - * n ist nicht prim wenn gilt: - * (a,n) != 1 - * oder - * a^( (n-1)/2) != J(a,n) mod n - * - */ - - a_ggt( &a, n, > ); - if ( a_cmp( >, &a_one) == 0) { - - j= jakobi( &a, n ); - m_exp( &a, &n2, &a ); - - if ( ( a_cmp( &a, &a_one) == 0 && j == 1 ) - || ( a_cmp( &a, &n1 ) == 0 && j == -1) ) - w = 1; - else - w = 0; - } - else - w = 0; - } - - return( w ); -} - -/* - * Berechne mulitiplikatives Inverses zu d (mod phi) - * d relativ prim zu phi ( d < phi ) - * d.h. (d,phi) == 1 - * - * ACHTUNG !!!! - * inv benutzt m_init - */ -void inv(rsa_NUMBER *d, rsa_NUMBER *phi, rsa_NUMBER *e) -{ - int k, i0, i1, i2; - rsa_NUMBER r[3],p[3],c; - - /* - * Berlekamp-Algorithmus - * ( fuer diesen Spezialfall vereinfacht ) - */ - - if (a_cmp(phi,d) <= 0) - abort(); - - m_init( phi, rsa_NUM0P ); - - p[1].n_len = 0; - a_assign( &p[2], &a_one ); - a_assign( &r[1], phi ); - a_assign( &r[2], d ); - - k = -1; - do { - k++; - i0=k%3; i1=(k+2)%3; i2=(k+1)%3; - a_div( &r[i2], &r[i1], &c, &r[i0] ); - m_mult( &c, &p[i1], &p[i0] ); - m_add( &p[i0], &p[i2], &p[i0] ); - } while (r[i0].n_len); - - if ( a_cmp( &r[i1], &a_one) ) /* r[i1] == (d,phi) muss 1 sein */ - abort(); - - if ( k & 1 ) /* falsches ''Vorzeichen'' */ - a_sub( phi, &p[i1], e ); - else - a_assign( e, &p[i1] ); -} - - -/******************************************************************************* - * * - * rnd.c * - * * - ********************************************************************************/ - -void gen_number(int len, rsa_NUMBER *n) -{ - const char *hex = "0123456789ABCDEF" ; - char num[ rsa_STRLEN +1 ]; - char *p; - int i,l; - - p=&num[ sizeof(num) -1]; - *p-- = '\0'; - - for (l=len; l--; p--) { - i = aux_rand() % 16; - *p = hex[ i ]; - } - p++; - - while (len-- && *p == '0') - p++; - - rsa_num_sget( n, p ); -} - -void init_rnd() -{ - const char *randdev = "/dev/urandom"; - - int fd; - unsigned int seed; - if ((fd = open(randdev, O_RDONLY)) != -1) { - if (read(fd, &seed, sizeof(seed))) {;} - close(fd); - } else { - seed = (unsigned int)time(0); //better use times() + win32 equivalent - } - srand( seed ); -} - - -/******************************************************************************* - * * - * aux.c * - * * - ********************************************************************************/ - -/* These are not needed, for the moment - -int get_clear(char *p, FILE *fp) -{ -int n; - -n = fread( p, 1, clear_siz, fp ); - -if (n <= 0) -return(0); - -memset( p + n, 0, enc_siz - n ); - -return(1); -} - -int get_enc(char *p, FILE *fp) -{ - int n; - - n = fread( p, 1, enc_siz, fp ); - - if (n != enc_siz) - return(0); - - return(1); -} - -int put_clear(char *p, FILE *fp) -{ - int n; - - n = fwrite( p, 1, clear_siz, fp ); - - if (n != clear_siz) - return(0); - - return(1); -} - -int put_enc(char *p, FILE *fp) -{ - int n; - - n = fwrite( p, 1, enc_siz, fp ); - - if (n != enc_siz) - return(0); - - return(1); -} - -*/ - -void do_crypt(char *s, char *d, int len, rsa_NUMBER *e) -{ - static char hex[] = "0123456789ABCDEF"; - rsa_NUMBER n; - char buf[ rsa_STRLEN + 1 ]; - char *ph; - int i,c; - - ph = buf + rsa_STRLEN - 1; - ph[1] = '\0'; - - for (i=len; i; i--) { - c = *s++; - *ph-- = hex[ (c >> 4) & 0xF ]; - *ph-- = hex[ c & 0xF ]; - } - ph++; - - rsa_num_sget( &n, ph ); - - m_exp( &n, e, &n ); - - rsa_num_sput( &n, buf, rsa_STRLEN +1 ); - - ph = buf + (i=strlen(buf)) -1; - - for (; len; len--) { - if (i-- > 0) { - c = (strchr( hex, *ph) - hex) << 4; - ph--; - } - else - c=0; - if (i-- > 0) { - c |= strchr( hex, *ph) - hex; - ph--; - } - - *d++ = c; - } -} - diff --git a/net/auth/src/rsafun.cxx b/net/auth/src/rsafun.cxx deleted file mode 100644 index 1491bdc9cd907..0000000000000 --- a/net/auth/src/rsafun.cxx +++ /dev/null @@ -1,89 +0,0 @@ -/* @(#)root/auth:$Id$ */ -/* Author: Martin Nicolay 22/11/1988 */ - -/****************************************************************************** -Copyright (C) 2006 Martin Nicolay - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later -version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free -Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, -MA 02110-1301 USA -******************************************************************************/ - -/******************************************************************************* -* * -* Simple RSA public key code. * -* Adaptation in library for ROOT by G. Ganis, July 2003 * -* (gerardo.ganis@cern.ch) * -* * -*******************************************************************************/ - -#include "rsafun.h" - -rsa_NUMBER rsa_genprim(int, int); -int rsa_genrsa(rsa_NUMBER, rsa_NUMBER, rsa_NUMBER *, rsa_NUMBER *, rsa_NUMBER *); -int rsa_encode(char *, int, rsa_NUMBER, rsa_NUMBER); -int rsa_decode(char *, int, rsa_NUMBER, rsa_NUMBER); -int rsa_num_sput( rsa_NUMBER*, char*, int ); -int rsa_num_fput( rsa_NUMBER*, FILE* ); -int rsa_num_sget( rsa_NUMBER*, char* ); -int rsa_num_fget( rsa_NUMBER*, FILE* ); -void rsa_assign( rsa_NUMBER*, rsa_NUMBER* ); -int rsa_cmp( rsa_NUMBER*, rsa_NUMBER* ); - -RSA_genprim_t TRSA_fun::fg_rsa_genprim; -RSA_genrsa_t TRSA_fun::fg_rsa_genrsa; -RSA_encode_t TRSA_fun::fg_rsa_encode; -RSA_decode_t TRSA_fun::fg_rsa_decode; -RSA_num_sput_t TRSA_fun::fg_rsa_num_sput; -RSA_num_fput_t TRSA_fun::fg_rsa_num_fput; -RSA_num_sget_t TRSA_fun::fg_rsa_num_sget; -RSA_num_fget_t TRSA_fun::fg_rsa_num_fget; -RSA_assign_t TRSA_fun::fg_rsa_assign; -RSA_cmp_t TRSA_fun::fg_rsa_cmp; - -RSA_genprim_t TRSA_fun::RSA_genprim() { return fg_rsa_genprim; } -RSA_genrsa_t TRSA_fun::RSA_genrsa() { return fg_rsa_genrsa; } -RSA_encode_t TRSA_fun::RSA_encode() { return fg_rsa_encode; } -RSA_decode_t TRSA_fun::RSA_decode() { return fg_rsa_decode; } -RSA_num_sput_t TRSA_fun::RSA_num_sput() { return fg_rsa_num_sput; } -RSA_num_fput_t TRSA_fun::RSA_num_fput() { return fg_rsa_num_fput; } -RSA_num_sget_t TRSA_fun::RSA_num_sget() { return fg_rsa_num_sget; } -RSA_num_fget_t TRSA_fun::RSA_num_fget() { return fg_rsa_num_fget; } -RSA_assign_t TRSA_fun::RSA_assign() { return fg_rsa_assign; } -RSA_cmp_t TRSA_fun::RSA_cmp() { return fg_rsa_cmp; } - -// Static instantiation to load hooks during dynamic load -static TRSA_fun g_rsa_init(&rsa_genprim,&rsa_genrsa,&rsa_encode,&rsa_decode, - &rsa_num_sput,&rsa_num_fput,&rsa_num_sget, - &rsa_num_fget,&rsa_assign,&rsa_cmp); - -TRSA_fun::TRSA_fun(RSA_genprim_t genprim, RSA_genrsa_t genrsa, RSA_encode_t encode, - RSA_decode_t decode, RSA_num_sput_t num_sput, RSA_num_fput_t num_fput, - RSA_num_sget_t num_sget, RSA_num_fget_t num_fget, - RSA_assign_t assign, RSA_cmp_t cmp) -{ - // constructor - - fg_rsa_genprim = genprim; - fg_rsa_genrsa = genrsa; - fg_rsa_encode = encode; - fg_rsa_decode = decode; - fg_rsa_num_sput = num_sput; - fg_rsa_num_fput = num_fput; - fg_rsa_num_sget = num_sget; - fg_rsa_num_fget = num_fget; - fg_rsa_assign = assign; - fg_rsa_cmp = cmp; -} diff --git a/net/auth/src/rsalib.cxx b/net/auth/src/rsalib.cxx deleted file mode 100644 index e50aa79a6f250..0000000000000 --- a/net/auth/src/rsalib.cxx +++ /dev/null @@ -1,498 +0,0 @@ -/* @(#)root/auth:$Id$ */ -/* Author: Martin Nicolay 22/11/1988 */ - -/****************************************************************************** -Copyright (C) 2006 Martin Nicolay - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later -version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free -Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, -MA 02110-1301 USA -******************************************************************************/ - -/******************************************************************************* -* * -* Simple RSA public key code. * -* Adaptation in library for ROOT by G. Ganis, July 2003 * -* (gerardo.ganis@cern.ch) * -* * -*******************************************************************************/ - -#include -#include -#include -#include -#include - -#include "rsaaux.h" -#include "rsalib.h" - -static int g_clear_siz; /* clear-text blocksize */ -static int g_enc_siz; /* encoded blocksize */ - /* g_clear_siz < g_enc_siz */ - -int gLog = 0; -int kMAXT = 100; - -rsa_NUMBER rsa_genprim(int len, int prob) -{ - rsa_NUMBER a_three,a_four; - rsa_NUMBER prim; - int i; - - a_add( &a_one, &a_two, &a_three ); - a_add( &a_two, &a_two, &a_four ); - - /* This is done elsewhere to allow different initialization of - rand seed (GGa - Sep 15, 2003) */ - /* init_rnd(); */ - - do { - gen_number( len, &prim ); - } while ( !prim.n_len ); - - a_mult( &prim, &a_two, &prim ); - a_mult( &prim, &a_three, &prim ); - a_add( &prim, &a_one, &prim ); - - for (i=1 ;; i++) { - - if (p_prim( &prim, prob )) - break; - if (i % 2) - a_add( &prim, &a_four, &prim ); - else - a_add( &prim, &a_two, &prim ); - } - - return prim; -} - -int rsa_genrsa(rsa_NUMBER p1, rsa_NUMBER p2, rsa_NUMBER *n, rsa_NUMBER *e, rsa_NUMBER *d) -{ - rsa_NUMBER phi, *max_p; - int len; - int ii, jj; - - if ( !a_cmp( &p1, &p2) ) return 1; - - if (a_cmp( &p1, &p2) > 0) - max_p = &p1; - else - max_p = &p2; - - - a_mult( &p1, &p2, n ); - a_sub( &p1, &a_one, &phi ); - a_sub( &p2, &a_one, e ); - a_mult( &phi, e, &phi ); - - len = n_bitlen( &phi ); - len = ( len + 3) / 4; - - a_assign( &p1, &phi ); - a_sub( &p1, &a_one, &p1 ); - - /* This is done elsewhere to allow different initialization of - rand seed (GGa - Sep 15, 2003) */ - /* init_rnd(); */ - - ii = 0; - do { - ii++; - jj = 0; - do { - jj++; - gen_number( len, d ); - } while (((a_cmp( d, max_p) <= 0 || a_cmp( d, &p1) >= 0)) && jj < kMAXT); - - a_ggt( d, &phi, e ); - } while ( a_cmp( e, &a_one) && ii < kMAXT); - - if (ii >= kMAXT || jj >= kMAXT) - return 2; - - inv( d, &phi, e ); - - return 0; - -} - -int rsa_encode_size(rsa_NUMBER n) -{ - // Returns length unit block of output - - return ( n_bitlen( &n) + 7) / 8; -} - -int rsa_encode(char *bufin, int lin, rsa_NUMBER n, rsa_NUMBER e) -{ - /* Encodes plain string in 'bufin' (output in 'bufin') - Returns length of encoded string - (key validity is not checked) */ - - char buf[ rsa_STRLEN*2 ]; - char bufout[ rsa_STRLEN*2 ]; - int i, j, lout; - char *pout; - - g_enc_siz = ( n_bitlen( &n) + 7) / 8; - g_clear_siz = g_enc_siz -1; - m_init( &n, rsa_NUM0P ); - - pout = bufout; - lout = 0; - for ( i = 0; i < lin; i += g_clear_siz) { - - memcpy(buf,bufin+i,g_clear_siz); - - j = ((lin-i) < g_clear_siz) ? lin-i : g_clear_siz; - memset(buf+j,0,(g_enc_siz-j)); - - do_crypt( buf, buf, g_enc_siz, &e ); - - memcpy(pout,buf,g_enc_siz); - - pout += g_enc_siz; - lout += g_enc_siz; - } - - memcpy(bufin,bufout,lout); - - return lout; - -} - -int rsa_decode(char *bufin, int lin, rsa_NUMBER n, rsa_NUMBER e) -{ - /* Decodes string in 'bufin' (output in 'bufin') - Returns length of plaintext string - (key validity is not checked) */ - - char buf[ rsa_STRLEN*2 ]; - char bufout[ rsa_STRLEN*2 ]; - int i, lout; - char *pout; - - g_enc_siz = ( n_bitlen( &n) + 7) / 8; - g_clear_siz = g_enc_siz -1; - m_init( &n, rsa_NUM0P ); - - pout = bufout; - lout = 0; - for ( i = 0; i < lin; i += g_enc_siz) { - - memcpy(buf,bufin+i,g_enc_siz); - - do_crypt( buf, buf, g_enc_siz, &e ); - - memcpy(pout,buf,g_clear_siz); - - pout += g_clear_siz; - lout += g_clear_siz; - } - - memcpy(bufin,bufout,lout); - - return lout; - -} - - -/******************************************************************************* - * * - * nio.c * - * * - ********************************************************************************/ - - -/* - * rsa_NUMBER io - */ - -/* - * Funktionen - * - * int num_sput( n, s, l) - * rsa_NUMBER *n; - * char s[l]; - * schreibt *n als Hex-Zahl in s - * - * int num_fput( n, f ) - * rsa_NUMBER *n; - * FILE *f; - * schreibt *n als Hex-Zahl in File f - * - * int num_sget( n, s ) - * rsa_NUMBER *n; - * char *s; - * liest Hex-Zahl s in *n ein - * - * int num_fget( n, f ) - * rsa_NUMBER *n; - * FILE *f; - * liest eine Hex-Zahl von f in *n ein - * - */ - - -static const char *gHEX="0123456789ABCDEF"; -static const char *ghex="0123456789abcdef"; - -static rsa_NUMBER gbits[9]; -static rsa_NUMBER gint16[16]; - -static int ginit = 0; - -void num_init() -{ - int i; - - if (ginit) return; - - a_assign( &gbits[0], &a_one ); - for ( i=1; i<9; i++) - a_add( &gbits[i-1], &gbits[i-1], &gbits[i] ); - - a_assign( &gint16[0], &a_one ); - for ( i=1; i<16; i++) - a_add( &gint16[i-1], &a_one, &gint16[i] ); - - ginit = 1; -} - - -int rsa_num_sput(rsa_NUMBER *n, char *s, int l) -{ -#if rsa_MAXINT == ( (1 << rsa_MAXBIT) - 1 ) - rsa_INT *p; - int bi,ab,i; - long b; - int first = 1; - - bi = rsa_MAXBIT * n->n_len; - ab = 4 - (bi + 3) % 4 -1; - p = &n->n_part[n->n_len -1]; - - if ( (bi+3) / 4 >= l ) - return(EOF); - - b = 0; - while (bi) { - b <<= (rsa_MAXBIT); - b |= (unsigned long)*p--; - bi -= rsa_MAXBIT; - ab += rsa_MAXBIT; - while (ab >= 4) { - i = (b >> (ab - 4)); - b &= ( 1L << (ab - 4)) -1L; - ab -= 4; - - if (first && !i) - continue; - first = 0; - *s++ = gHEX[ i ]; - } - } - if (b) - abort(); - *s = '\0'; - - return (0); -#else - rsa_NUMBER r,q; - int i,b,p,len,low,high; - char *np; - - if (! ginit) - num_init(); - - a_assign( &q, n); - len = l; - np = s + l; - - for (; q.n_len && len > 1; len --) { - a_div( &q, &gbits[4], &q, &r ); - for (p=8, b=0, i=3; i >= 0; i--, p /= 2) { - if ( a_cmp( &r, &gbits[i]) >= 0) { - a_sub( &r, &gbits[i], &r ); - b += p; - } - } - *--np = gHEX[ b ]; - } - if (q.n_len) - return(EOF); - - l -= len; - len = l; - for (; l--; ) - *s++ = *np++; - - *s = '\0'; - - return (0); -#endif -} - - -int rsa_num_fput(rsa_NUMBER *n, FILE *f) -{ - int j; - char *np; - char n_print[ rsa_STRLEN + 1 ]; - - if ( rsa_num_sput( n, n_print, sizeof( n_print) ) == EOF ) - return(EOF); - - for (j=0, np=n_print; *np ; np++, j++) { - if (j==64) { - fputs("\n",f); - j = 0; - } - putc((int)*np,f); - } - - if (j) - putc('\n',f); - - return(0); -} - - -int rsa_num_sget(rsa_NUMBER *n, char *s) -{ -#if rsa_MAXINT == ( (1 << rsa_MAXBIT) - 1 ) - rsa_INT *p; - const char *hp; - int bi,ab,i; - long b; - int first = 1; - - bi = 4 * strlen(s); - ab = rsa_MAXBIT - (bi + rsa_MAXBIT -1) % rsa_MAXBIT -1; - i = (bi + rsa_MAXBIT-1) / rsa_MAXBIT; - p = &n->n_part[ i -1 ]; - n->n_len = i; - - if ( i > rsa_MAXLEN ) - return(EOF); - - b = 0; - while (bi > 0) { - if ( (hp = strchr( gHEX, *s )) ) - i = hp - gHEX; - else if ((hp = strchr( ghex, *s )) ) - i = hp - ghex; - else - return(EOF); - s++; - - b <<= 4; - b |= (unsigned long)i; - bi -= 4; - ab += 4; - while (ab >= rsa_MAXBIT) { - i = (b >> (ab - rsa_MAXBIT)); - b &= ( 1L << (ab - rsa_MAXBIT)) -1L; - ab -= rsa_MAXBIT; - if (first && !i) { - p--; - n->n_len--; - } - else { - first = 0; - *p-- = i; - } - } - } - if (b) - abort(); - *s = '\0'; - - return (0); -#else - char *p; - int i,c; - - if (! ginit) - num_init(); - - n->n_len = 0; - while ( (c = *s++ & 0xFF)) { - if ( p= strchr( gHEX, c) ) - i = p - gHEX; - else if ( p= strchr( ghex, c) ) - i = p - ghex; - else - return(EOF); - - a_mult( n, &gbits[4], n ); - if (i) - a_add( n, &gint16[i-1], n ); - } - - return(0); -#endif -} - -int rsa_num_fget(rsa_NUMBER *n, FILE *f) -{ - int j,c; - char *np; - char n_print[ rsa_STRLEN + 1 ]; - - np = n_print; - j = sizeof(n_print); - while ( (c=getc(f)) != EOF && ( isxdigit(c) || isspace(c)) ) { - if (isspace(c)) - continue; - if (! --j) - return(EOF); - *np++ = (char)c; - } - *np = '\0'; - - if (c != EOF) - ungetc(c,f); - - if ( rsa_num_sget( n, n_print) == EOF ) - return( EOF ); - - return(0); -} - -int rsa_cmp(rsa_NUMBER *c1, rsa_NUMBER *c2) -{ - int l; - /* bei verschiedener Laenge klar*/ - if ( (l=c1->n_len) != c2->n_len) - return( l - c2->n_len); - - /* vergleiche als arrays */ - return( n_cmp( c1->n_part, c2->n_part, l) ); -} - -void rsa_assign(rsa_NUMBER *d, rsa_NUMBER *s) -{ - int l; - - if (s == d) /* nichts zu kopieren */ - return; - - if ((l=s->n_len)) - memcpy( d->n_part, s->n_part, sizeof(rsa_INT)*l); - - d->n_len = l; -} diff --git a/net/rpdutils/CMakeLists.txt b/net/rpdutils/CMakeLists.txt deleted file mode 100644 index ffde37d2e52a2..0000000000000 --- a/net/rpdutils/CMakeLists.txt +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. -# All rights reserved. -# -# For the licensing terms see $ROOTSYS/LICENSE. -# For the list of contributors see $ROOTSYS/README/CREDITS. - -############################################################################ -# CMakeLists.txt file for building ROOT net/rpdutils package -# @author Pere Mato, CERN -############################################################################ - -include_directories(res ../auth/res) - -if(MACOSX_SSL_DEPRECATED) - set_source_files_properties(src/rpdutils.cxx COMPILE_FLAGS "-Wno-deprecated-declarations") -endif() - -if(shadowpw) - add_definitions(-DR__SHADOWPW) -endif() - -if(ssl) - include_directories(${OPENSSL_INCLUDE_DIR}) -endif() - -add_library(rpdutil STATIC - src/daemon.cxx - src/error.cxx - src/net.cxx - src/netpar.cxx - src/rpdutils.cxx -) - -target_include_directories(rpdutil PRIVATE - ${CMAKE_SOURCE_DIR}/core/clib/inc # for snprintf.h - ${CMAKE_SOURCE_DIR}/core/base/inc # for RConfig.hxx - ${CMAKE_SOURCE_DIR}/core/foundation/inc # for TError.hxx - ${CMAKE_SOURCE_DIR}/core/meta/inc # for TGenericClassInfo.h - ${CMAKE_SOURCE_DIR}/net/net/inc # for NetErrors.h - ${CMAKE_SOURCE_DIR}/net/auth/inc # for NetErrors.h - ${CMAKE_BINARY_DIR}/ginclude # for RConfigure.h -) - -target_link_libraries(rpdutil INTERFACE $<$:crypt>) -set_property(TARGET rpdutil PROPERTY POSITION_INDEPENDENT_CODE ON) -add_dependencies(rpdutil move_headers) - -ROOT_LINKER_LIBRARY(SrvAuth rpdutils.cxx DaemonUtils.h DaemonUtils.cxx - LIBRARIES - ${OPENSSL_LIBRARIES} - rpdutil - rsa - DEPENDENCIES - Net - BUILTINS - OPENSSL -) - -target_include_directories(SrvAuth PRIVATE - ${CMAKE_SOURCE_DIR}/net/auth/res - ${CMAKE_SOURCE_DIR}/net/auth/inc - ${CMAKE_SOURCE_DIR}/rpdutils/res -) - -if (CMAKE_SYSTEM_NAME MATCHES FreeBSD) - target_link_libraries(SrvAuth PRIVATE crypt) -endif() - diff --git a/net/rpdutils/res/rpdconn.h b/net/rpdutils/res/rpdconn.h deleted file mode 100644 index 32ac8da5f4b89..0000000000000 --- a/net/rpdutils/res/rpdconn.h +++ /dev/null @@ -1,220 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Gerardo Ganis, March 2011 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_rpdconn -#define ROOT_rpdconn - -////////////////////////////////////////////////////////////////////////// -// // -// rpdconn // -// // -// This header file contains the definition of some utility classes // -// used for process communication between rootd. // -// // -////////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include -#include - -// -// Basic mutex helper class -// - -class rpdmtxhelper { -private: - pthread_mutex_t *mtx; - bool ok; - - void rawlock(const pthread_mutex_t *m) { if (m) { - if (!pthread_mutex_lock((pthread_mutex_t *)m)) { - mtx = (pthread_mutex_t *)m; ok = 1; } } } - void rawunlock(const pthread_mutex_t *m) { if (m) { pthread_mutex_unlock((pthread_mutex_t *)m); } mtx = 0; ok = 0; } - -public: - rpdmtxhelper(const pthread_mutex_t *m = 0) { mtx = 0; ok = 0; rawlock(m); } - rpdmtxhelper(const pthread_mutex_t &m) { mtx = 0; ok = 0; rawlock(&m); } - virtual ~rpdmtxhelper() { rawunlock(mtx); } - - inline void lock() { rawlock(mtx); }; - inline void unlock() { rawunlock(mtx); } - inline bool isok() { return ok; } -}; - -// -// Class describing a basic message -// -class rpdconn; -class rpdmsg { -friend class rpdconn; -protected: - int type; // Message type (positive; -1 for undef) - std::string buf; // Internal buffer - int cur; // Offset while streaming out - -public: - rpdmsg(int t = -1) : type(t), cur(0) { } - rpdmsg(int t, const char *b) : type(t), buf(b), cur(0) { } - - bool empty() { return ((cur < 0 || - (cur >= 0 && (int) buf.length() <= cur)) ? 1 : 0); } - void reset(int t = -1) { if (t >= 0) type = t; buf = ""; cur = 0; } - void rewind() { cur = 0; } - void settype(int t) { type = t; } - - // Access content - int what() const { return type; } - const char *content() const { return buf.c_str(); } - - // in/out functions - void r_int(int &i); - void r_double(double &d); - void r_string(std::string &s); - void w_int(int i); - void w_double(double d); - void w_string(const std::string &s); -}; -// rpdmsg external operators -inline rpdmsg &operator>>(rpdmsg &m, int &i) { m.r_int(i); return m; } -inline rpdmsg &operator>>(rpdmsg &m, double &d) { m.r_double(d); return m; } -inline rpdmsg &operator>>(rpdmsg &m, std::string &s) { m.r_string(s); return m; } -inline rpdmsg &operator<<(rpdmsg &m, int i) { m.w_int(i); return m; } -inline rpdmsg &operator<<(rpdmsg &m, double d) { m.w_double(d); return m; } -inline rpdmsg &operator<<(rpdmsg &m, const std::string &s) { m.w_string(s); return m; } - -// -// Class describing a basic connection -// -class rpdconn { -protected: - pthread_mutex_t rdmtx; // Mutex for read operations - pthread_mutex_t wrmtx; // Mutex for write operations - int rdfd; // Descriptor for read operations - int wrfd; // Descriptor for write operations -public: - rpdconn(int r = -1, int w = -1); - virtual ~rpdconn() { } - - virtual void close() = 0; - virtual bool isvalid(bool rd) const { - int rc = 0; - if (rd) { - rpdmtxhelper mh(&rdmtx); - rc = (rdfd > 0) ? 1 : 0; - } else { - rpdmtxhelper mh(&wrmtx); - rc = (wrfd > 0) ? 1 : 0; - } - return rc; - } - void setdescriptors(int r = -1, int w = -1) { - { rpdmtxhelper mh(&rdmtx); rdfd = r; } - { rpdmtxhelper mh(&wrmtx); wrfd = w; } - } - - int pollrd(int to = -1); - - int send(int i); - int send(int type, const char *msg); - int send(const rpdmsg &msg); - virtual int send(const void *buf, int len); - int recv(int &i); - int recv(int &type, std::string &msg); - int recv(rpdmsg &msg); - virtual int recv(void *buffer, int len); - - int senddesc(int desc); - int recvdesc(int &desc); -}; - -// -// Class describing a TCP connection -// -class rpdtcp : public rpdconn { -protected: - std::string host; // Host name - int port; // Port - int fd; // Socket descriptor - struct sockaddr addr; // Structure describing the peer address -public: - rpdtcp(int d = -1) : rpdconn(), port(0), fd(d) { memset(&addr, 0, sizeof(addr)); - setdescriptors(d,d); } // Used by rpdtcpsrv - rpdtcp(const char *h, int p); - virtual ~rpdtcp() { close(); } - - void close() { if (fd > 0) ::close(fd); fd = -1; setdescriptors(); } - int exportfd() { int d = fd; fd = -1; setdescriptors(); return d; } - const struct sockaddr *address() const { return (const struct sockaddr *)&addr; } -}; - -// -// Class describing a server TCP connection -// -class rpdtcpsrv : public rpdtcp { -public: - rpdtcpsrv(int p, int backlog = 10); - virtual ~rpdtcpsrv() { rpdtcp::close(); } - - rpdtcp *accept(int to = -1, int *err = 0); -}; - -// -// Class describing a UNIX TCP connection -// -class rpdunix : public rpdtcp { -protected: - std::string sockpath; // Socket path -public: - rpdunix(int d = -1) : rpdtcp(d) { } - rpdunix(const char *p); - virtual ~rpdunix() { rpdtcp::close(); } - const char *path() const { return sockpath.c_str(); } -}; - -// -// Class describing a server UNIX TCP connection -// -class rpdunixsrv : public rpdunix { -protected: - int fd; // Socket descriptor -public: - rpdunixsrv(const char *p, int backlog = 10); - virtual ~rpdunixsrv() { rpdtcp::close(); } - - rpdunix *accept(int to = -1, int *err = 0); -}; - -// -// Class describing a UDP connection -// -class rpdudp : public rpdtcp { -public: - rpdudp(int d = -1) : rpdtcp(d) { } // Used by rpdudpsrv - rpdudp(const char *h, int p); - virtual ~rpdudp() { } - - int send(const void *buf, int len); - int recv(void *buffer, int len); -}; - -// -// Class describing a server UDP connection -// -class rpdudpsrv : public rpdudp { -public: - rpdudpsrv(int p); - virtual ~rpdudpsrv() { rpdudp::close(); } -}; - -#endif diff --git a/net/rpdutils/res/rpddefs.h b/net/rpdutils/res/rpddefs.h deleted file mode 100644 index fc09d26961d8c..0000000000000 --- a/net/rpdutils/res/rpddefs.h +++ /dev/null @@ -1,42 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Gerardo Ganis 7/4/2003 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_rpddefs -#define ROOT_rpddefs - - -///////////////////////////////////////////////////////////////////// -// // -// Definition used by daemons // -// // -///////////////////////////////////////////////////////////////////// - -#include "AuthConst.h" - -// -// Typedefs -typedef void (*SigPipe_t)(int); - -// -// Global consts -const int kMAXRECVBUF = 1024; -const int kMAXUSERLEN = 128; - -// Masks for initialization options -const unsigned int kDMN_RQAUTH = 0x1; // Require authentication -const unsigned int kDMN_HOSTEQ = 0x2; // Allow host equivalence -const unsigned int kDMN_SYSLOG = 0x4; // Log messages to syslog i.o. stderr - -// -// type of service -enum EService { kSOCKD = 0, kROOTD }; - -#endif diff --git a/net/rpdutils/res/rpderr.h b/net/rpdutils/res/rpderr.h deleted file mode 100644 index 665db0b2bc410..0000000000000 --- a/net/rpdutils/res/rpderr.h +++ /dev/null @@ -1,29 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Fons Rademakers 11/08/97 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_rpderr -#define ROOT_rpderr - - -////////////////////////////////////////////////////////////////////////// -// // -// rpderr // -// // -// This header file defines error codes generated by rootd. // -// NB: In case of change update also strings in net/inc/ErrStr.h // -// // -////////////////////////////////////////////////////////////////////////// - -#include "NetErrors.h" - -typedef void (*ErrorHandler_t)(int level, const char *msg, int size); - -#endif diff --git a/net/rpdutils/res/rpdp.h b/net/rpdutils/res/rpdp.h deleted file mode 100644 index ba2a6a881f758..0000000000000 --- a/net/rpdutils/res/rpdp.h +++ /dev/null @@ -1,188 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Gerardo Ganis 7/4/2003 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_rpdp -#define ROOT_rpdp - - -////////////////////////////////////////////////////////////////////////// -// // -// rpdp // -// // -// This header file contains private definitions and declarations // -// used by modules in rpdutils/src. // -// // -////////////////////////////////////////////////////////////////////////// - -#include "Varargs.h" -#include "MessageTypes.h" -#include "rpderr.h" -#include - -///////////////////////////////////////////////////////////////////// -// // -// Definition used by daemons // -// // -///////////////////////////////////////////////////////////////////// - -#include "rpddefs.h" - -#include "Rtypes.h" //const int kMAXPATHLEN = kMAXSECBUF; - -///////////////////////////////////////////////////////////////////// -// // -// Prototypes used by daemons // -// // -///////////////////////////////////////////////////////////////////// - -// -// rpdutils globals -namespace ROOT { - -// Utility functions -int SPrintf(char *buf, size_t size, const char *va_(fmt), ...); - -// error handling functions -void Error(ErrorHandler_t ErrHand,int code,const char *va_(fmt), ...); -void ErrorInfo(const char *va_(fmt), ...); -void ErrorInit(const char *ident); -int GetErrno(); -void Perror(char *buf, int size = kMAXPATHLEN); -void ResetErrno(); - -// network functions -void NetClose(); -double NetGetBytesRecv(); -double NetGetBytesSent(); -void NetGetRemoteHost(std::string &host); -int NetGetSockFd(); -int NetInit(EService service, int port1, int port2, int tcpwindowsize); -int NetParOpen(int port, int size); -int NetOpen(int inetdflag, EService service); -int NetRecv(char *msg, int len, EMessageTypes &kind); -int NetRecvAllocate(void *&buf, int &len, EMessageTypes &kind); -int NetRecvRaw(void *buf, int len); -void NetResetByteCount(); -int NetSend(int code, EMessageTypes kind); -int NetSend(const char *msg, EMessageTypes kind = kMESS_STRING); -int NetSendError(ERootdErrors err); -int NetSendRaw(const void *buf, int len); -void NetSetSigPipeHook(SigPipe_t hook); - -// fork functionality -void DaemonStart(int ignsigcld, int fdkeep, EService service); - -// rpdutils.cxx -void RpdAuthCleanup(const char *sstr, int opt); -int RpdGenRSAKeys(int); -int RpdInitSession(int, std::string &, int &); -int RpdInitSession(int, std::string &, int &, int &, std::string &); -int RpdInitSession(int, std::string &, int &, int &, int &, std::string &); -void RpdInit(EService serv, int pid, int sproto, - unsigned int opts, int rumsk, int sshp, - const char *tmpd, const char *asrpp, int login = 0); -void RpdSetErrorHandler(ErrorHandler_t Err, ErrorHandler_t Sys, - ErrorHandler_t Fatal); -#ifdef R__KRB5 -void RpdSetKeytabFile(const char *keytabfile); -#endif -void RpdSetSysLogFlag(int syslog); -void RpdSetMethInitFlag(int methinit); -int RpdUpdateAuthTab(int opt, const char *line, char **token, int ilck = 0); - -} // namespace ROOT - - -///////////////////////////////////////////////////////////////////// -// // -// Internal Definition and prototypes used by modules in rpdutils // -// // -///////////////////////////////////////////////////////////////////// - -// -// Prototypes -// -namespace ROOT { - -// -// Utility functions -char *ItoA(int i); - -// -// net.cxx -int NetRecv(char *msg, int max); -int NetRecvRaw(int sock, void *buf, int len); -int NetSend(const void *buf, int len, EMessageTypes kind); -int NetSendAck(); -void NetSetOptions(EService service, int sock, int tcpwindowsize); - -// -// netpar.cxx -void NetParClose(); -int NetParRecv(void *buf, int len); -int NetParSend(const void *buf, int len); - -// -// rpdutils.cxx -int RpdAuthenticate(); -int RpdCheckAuthAllow(int Sec, const char *Host); -int RpdCheckAuthTab(int Sec, const char *User, const char *Host, - int RemId, int *OffSet); -int RpdCheckDaemon(const char *daemon); -int RpdCheckHost(const char *Host, const char *host); -int RpdCheckOffSet(int Sec, const char *User, const char *Host, int RemId, - int *OffSet, char **tkn, int *shmid, char **glbsuser); -int RpdCheckSpecialPass(const char *passwd); - int RpdRetrieveSpecialPass(const char *usr, const char *fpw, char *pwd, int lmx); -int RpdCheckSshd(int opt); -bool RpdCheckToken(char *tknin, char *tknref); -int RpdCleanupAuthTab(const char *crypttoken); -int RpdCleanupAuthTab(const char *Host, int RemId, int OffSet); -void RpdDefaultAuthAllow(); -int RpdDeleteKeyFile(int ofs); -void RpdFreeKeys(); -int RpdGetAuthMethod(int kind); -char *RpdGetIP(const char *host); -char *RpdGetRandString(int Opt, int Len); -int RpdGetRSAKeys(const char *PubKey, int Opt); -int RpdGlobusAuth(const char *sstr); -int RpdGuessClientProt(const char *buf, EMessageTypes kind); -void RpdInitAuth(); -void RpdInitRand(); -int RpdKrb5Auth(const char *sstr); -int RpdLogin(int,int); -int RpdNoAuth(int); -int RpdPass(const char *pass, int errheq = 0); -int RpdProtocol(int); -int RpdRecvClientRSAKey(); -int RpdRenameKeyFile(int oofs, int nofs); -int RpdReUseAuth(const char *sstr, int kind); -int RpdRfioAuth(const char *sstr); -int RpdSavePubKey(const char *PubKey, int OffSet, char *User); -int RpdSecureRecv(char **Str); -int RpdSecureSend(char *Str); -void RpdSendAuthList(); -int RpdSetUid(int uid); -int RpdSRPUser(const char *user); -int RpdSshAuth(const char *sstr); -int RpdUser(const char *sstr); - -// -// Ssh Utility Function prototypes ... -int SshToolAllocateSocket(unsigned int, unsigned int, char **); -void SshToolDiscardSocket(const char *, int); -int SshToolGetAuth(int); -int SshToolGetAuth(int, const char *); -int SshToolNotifyFailure(const char *); - -} // namespace ROOT - -#endif diff --git a/net/rpdutils/res/rpdpriv.h b/net/rpdutils/res/rpdpriv.h deleted file mode 100644 index a59a57fbc0bb8..0000000000000 --- a/net/rpdutils/res/rpdpriv.h +++ /dev/null @@ -1,81 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Gerardo Ganis, March 2011 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_rpdpriv -#define ROOT_rpdpriv - -////////////////////////////////////////////////////////////////////////// -// // -// rpdpriv // -// // -// Implementation of a privileges handling API following the paper // -// "Setuid Demystified" by H.Chen, D.Wagner, D.Dean // -// also quoted in "Secure programming Cookbook" by J.Viega & M.Messier. // -// // -// NB: this not thread-safe: it is meant to be used in single-threaded // -// applications // -// // -////////////////////////////////////////////////////////////////////////// - -#if !defined(WINDOWS) -# include -#else -# define uid_t unsigned int -# define gid_t unsigned int -#endif - -class rpdpriv -{ - friend class rpdprivguard; - private: - - rpdpriv(); - - static bool debug; - - static int changeto(uid_t uid, gid_t gid); - static void dumpugid(const char *msg = 0); - static int restore(bool saved = 1); - - public: - virtual ~rpdpriv() { } - static int changeperm(uid_t uid, gid_t gid); -}; - -// -// Guard class; -// Usage: -// -// { rpdprivguard priv(tempuid); -// -// // Work as tempuid (maybe superuser) -// ... -// -// } -// -class rpdprivguard -{ - public: - rpdprivguard(uid_t uid, gid_t gid); - rpdprivguard(const char *user); - virtual ~rpdprivguard(); - bool isvalid() const { return valid; } - private: - bool dum; - bool valid; - void init(uid_t uid, gid_t gid); -}; - -#ifndef rpdbadpguard -#define rpdbadpguard(g,u) (!(g.isvalid()) && (geteuid() != (uid_t)u)) -#endif - -#endif diff --git a/net/rpdutils/src/DaemonUtils.cxx b/net/rpdutils/src/DaemonUtils.cxx deleted file mode 100644 index 19d79bef87c46..0000000000000 --- a/net/rpdutils/src/DaemonUtils.cxx +++ /dev/null @@ -1,579 +0,0 @@ -// @(#)root/auth:$Id$ -// Author: Gerri Ganis 19/1/2004 - -/************************************************************************* - * Copyright (C) 1995-2003, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// DaemonUtils // -// // -// This file defines wrappers to client utils calls used by server // -// authentication daemons // -// // -////////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(linux) -# include -# if __GNU_LIBRARY__ == 6 -# ifndef R__GLIBC -# define R__GLIBC -# endif -# endif -#endif -#if defined(__MACH__) && !defined(__APPLE__) -# define R__GLIBC -#endif - -#ifdef __sun -# ifndef _REENTRANT -# if __SUNPRO_CC > 0x420 -# define GLOBAL_ERRNO -# endif -# endif -#endif - -#include "Rtypes.h" -#include "Varargs.h" -#include "DaemonUtils.h" -#include "TSecContext.h" -#include "TEnv.h" -#include "TROOT.h" - -//________________________________________________________________________ - -// --- Globals -------------------------------------------------------- -static TSocket *gSocket; - -// This is to be changed whenever something is changed -// in non-backward compatible way -// 0 -> 1: support for SSH authentication via SSH tunnel -static Int_t gSrvProtocol = 1; -static EService gService = kSOCKD; -static Int_t gReuseAllow = 0x1F; - -using namespace std; -using namespace ROOT; - -extern "C" { - Int_t SrvAuthenticate(TSocket *socket, - const char *confdir, const char *tmpdir, - string &user, Int_t &meth, Int_t &type, string &ctkn, - TSeqCollection *secctxlist) { - return SrvAuthImpl(socket, confdir, tmpdir, user, meth, type, ctkn, secctxlist); - } -} - -extern "C" { - Int_t SrvAuthCleanup(TSeqCollection *sls) { - return SrvClupImpl(sls); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set relevant environment variables - -static Int_t SrvSetVars(string /*confdir*/) -{ - // Executables and conf dirs - - // Make rootbindir available to all the session via env - string execdir = TROOT::GetBinDir().Data(); - if (execdir.length()) { - int len = 15 + execdir.length(); - char *tmp = new char[len+1]; - if (tmp) { - snprintf(tmp,len+1, "ROOTBINDIR=%.*s", len, execdir.c_str()); - putenv(tmp); - } else - return -1; - } - - // Make rootetcdir available to all the session via env - string etcdir = TROOT::GetEtcDir().Data(); - if (etcdir.length()) { - int len = 15 + etcdir.length(); - char *tmp = new char[len+1]; - if (tmp) { - snprintf(tmp, len+1, "ROOTETCDIR=%.*s", len, etcdir.c_str()); - putenv(tmp); - } else - return -1; - } - - // If specified, set the special daemonrc file to be used - string daemonrc = string(gEnv->GetValue("SrvAuth.DaemonRc","")); - if (daemonrc.length()) { - int len = 15 + daemonrc.length(); - char *tmp = new char[len+1]; - if (tmp) { - snprintf(tmp, len+1, "ROOTDAEMONRC=%.*s", len, daemonrc.c_str()); - putenv(tmp); - } else - return -1; - } - - // If specified, set the special gridmap file to be used - string gridmap = string(gEnv->GetValue("SrvAuth.GridMap","")); - if (gridmap.length()) { - int len = 15 + gridmap.length(); - char *tmp = new char[len+1]; - if (tmp) { - snprintf(tmp, len+1, "GRIDMAP=%.*s", len, gridmap.c_str()); - putenv(tmp); - } else - return -1; - } - - // If specified, set the special hostcert.conf file to be used - string hcconf = string(gEnv->GetValue("SrvAuth.HostCert","")); - if (hcconf.length()) { - int len = 15 + hcconf.length(); - char *tmp = new char[len+1]; - if (tmp) { - snprintf(tmp, len+1, "ROOTHOSTCERT=%.*s", len, hcconf.c_str()); - putenv(tmp); - } else - return -1; - } - - return 0; -} - - -//////////////////////////////////////////////////////////////////////////////// - -void Err(int level, const char *msg, int size) -{ - Perror((char *)msg, size); - if (level > -1) NetSend(level, kROOTD_ERR); -} - -//////////////////////////////////////////////////////////////////////////////// - -void ErrFatal(int level, const char *msg, int size) -{ - Perror((char *)msg, size); - if (level > -1) NetSend(msg, kMESS_STRING); -} - -//////////////////////////////////////////////////////////////////////////////// - -void ErrSys(int level, const char *msg, int size) -{ - Perror((char *)msg, size); - ErrFatal(level, msg, size); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Wrapper to cleanup code - -Int_t SrvClupImpl(TSeqCollection *secls) -{ - TIter next(secls); - ROOT::Deprecated::TSecContext *nsc ; - while ((nsc = (ROOT::Deprecated::TSecContext *)next())) { - if (!strncmp(nsc->GetID(),"server",6)) { - int rc = RpdCleanupAuthTab(nsc->GetToken()); - if (gDebug > 0 && rc < 0) - ErrorInfo("SrvClupImpl: operation unsuccessful (rc: %d, ctkn: %s)", - rc, nsc->GetToken()); - } - } - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Server authentication code. -/// Returns 0 in case authentication failed -/// 1 in case of success -/// On success, returns authenticated username in user - -Int_t SrvAuthImpl(TSocket *socket, const char *confdir, const char *tmpdir, - string &user, Int_t &meth, Int_t &type, string &ctoken, - TSeqCollection *secctxlist) -{ - Int_t rc = 0; - - // Check if hosts equivalence is required - Bool_t hequiv = gEnv->GetValue("SrvAuth.CheckHostsEquivalence",0); - - // Pass file for SRP - string altSRPpass = string(gEnv->GetValue("SrvAuth.SRPpassfile","")); - - // Port for the SSH daemon - Int_t sshdport = gEnv->GetValue("SrvAuth.SshdPort",22); - - // Set envs - if (SrvSetVars(string(confdir)) == -1) - // Problems setting environment - return rc; - - // Parent ID - int parentid = getpid(); // Process identifier - - // default job options - unsigned int options = kDMN_RQAUTH | kDMN_HOSTEQ; - if (!hequiv) - options &= ~kDMN_HOSTEQ; - - // Init error handlers - RpdSetErrorHandler(Err, ErrSys, ErrFatal); - - // Init daemon code - RpdInit(gService, parentid, gSrvProtocol, options, - gReuseAllow, sshdport, - tmpdir, altSRPpass.c_str()); - - // Generate Local RSA keys for the session - if (RpdGenRSAKeys(0)) - // Problems generating keys - return rc; - - // Reset check of the available method list - RpdSetMethInitFlag(0); - - // Trasmit relevant socket details - SrvSetSocket(socket); - - // Init Session (get protocol, run authentication, ...) - // type of authentication: - // 0 (new), 1 (existing), 2 (updated offset) - int clientprotocol = 0; - rc = RpdInitSession(gService, user, clientprotocol, meth, type, ctoken); - - ROOT::Deprecated::TSecContext *seccontext = 0; - if (rc > 0) { - string openhost(socket->GetInetAddress().GetHostName()); - - if (type == 1) { - // An existing authentication has been re-used: retrieve - // the related security context - TIter next(ROOT::Deprecated::Internal::GetListOfSecContexts(*gROOT)); - while ((seccontext = (ROOT::Deprecated::TSecContext *)next())) { - if (!(strncmp(seccontext->GetID(),"server",6))) { - if (seccontext->GetMethod() == meth) { - if (!strcmp(openhost.c_str(),seccontext->GetHost())) { - if (!strcmp(user.c_str(),seccontext->GetUser())) - break; - } - } - } - } - } - - if (!seccontext) { - // New authentication: Fill a SecContext for cleanup - // in case of interrupt - seccontext = new ROOT::Deprecated::TSecContext(user.c_str(), openhost.c_str(), meth, -1, - "server", ctoken.c_str()); - if (seccontext) { - // Add to the list - secctxlist->Add(seccontext); - // Store SecContext - ROOT::Deprecated::TSocketFriend::SetSecContext(*socket, seccontext); - } else { - if (gDebug > 0) - ErrorInfo("SrvAuthImpl: could not create sec context object" - ": potential problems in cleaning"); - } - } - } - - - // Done - return rc; -} - - -namespace ROOT { - - static int gSockFd = -1; - -//////////////////////////////////////////////////////////////////////////////// -/// Fill socket parameters - - void SrvSetSocket(TSocket *Socket) - { - gSocket = Socket; - gSockFd = Socket->GetDescriptor(); - } - -//////////////////////////////////////////////////////////////////////////////// -/// Receive exactly length bytes into buffer. Returns number of bytes -/// received. Returns -1 in case of error. - - static int Recvn(int sock, void *buffer, int length) - { - if (sock < 0) return -1; - - int n, nrecv = 0; - char *buf = (char *)buffer; - - for (n = 0; n < length; n += nrecv) { - while ((nrecv = recv(sock, buf+n, length-n, 0)) == -1 - && GetErrno() == EINTR) - ResetErrno(); // probably a SIGCLD that was caught - if (nrecv < 0) { - Error(gErrFatal,-1, - "Recvn: error (sock: %d): errno: %d",sock,GetErrno()); - return nrecv; - } else if (nrecv == 0) - break; // EOF - } - - return n; - } - -//////////////////////////////////////////////////////////////////////////////// -/// Empty call, for consistency - - void NetClose() - { - return; - } - -//////////////////////////////////////////////////////////////////////////////// -/// return open socket descriptor - - int NetGetSockFd() - { - return gSockFd; - } - -//////////////////////////////////////////////////////////////////////////////// -/// Empty call, for consistency - - int NetParOpen(int port, int size) - { - if (port+size) - return (port+size); - else - return 1; - } - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a string of maximum length max. - - int NetRecv(char *msg, int max) - { - return gSocket->Recv(msg, max); - } - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a string of maximum len length. Returns message type in kind. -/// Return value is msg length. - - int NetRecv(char *msg, int len, EMessageTypes &kind) - { - Int_t tmpkind; - Int_t rc = gSocket->Recv(msg, len, tmpkind); - kind = (EMessageTypes)tmpkind; - return rc; - } - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a buffer. Returns the newly allocated buffer, the length -/// of the buffer and message type in kind. - - int NetRecv(void *&buf, int &len, EMessageTypes &kind) - { - int hdr[2]; - - if (NetRecvRaw(hdr, sizeof(hdr)) < 0) - return -1; - - len = ntohl(hdr[0]) - sizeof(int); - kind = (EMessageTypes) ntohl(hdr[1]); - if (len) { - buf = new char* [len]; - return NetRecvRaw(buf, len); - } - buf = 0; - return 0; - - } - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a buffer of maximum len bytes. - - int NetRecvRaw(void *buf, int len) - { - return gSocket->RecvRaw(buf,len); - } - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a buffer of maximum len bytes from generic socket sock. - - int NetRecvRaw(int sock, void *buf, int len) - { - if (sock == -1) return -1; - - if (Recvn(sock, buf, len) < 0) { - Error(gErrFatal,-1, - "NetRecvRaw: Recvn error (sock: %d, errno: %d)",sock,GetErrno()); - } - - return len; - } - -//////////////////////////////////////////////////////////////////////////////// -/// Send integer. Message will be of type "kind". - - int NetSend(int code, EMessageTypes kind) - { - int hdr[3]; - int hlen = sizeof(int) + sizeof(int); - hdr[0] = htonl(hlen); - hdr[1] = htonl(kind); - hdr[2] = htonl(code); - - return gSocket->SendRaw(hdr, sizeof(hdr)); - } - -//////////////////////////////////////////////////////////////////////////////// -/// Send a string. Message will be of type "kind". - - int NetSend(const char *msg, EMessageTypes kind) - { - return gSocket->Send(msg, kind); - } - -//////////////////////////////////////////////////////////////////////////////// -/// Send buffer of len bytes. Message will be of type "kind". - - int NetSend(const void *buf, int len, EMessageTypes kind) - { - int hdr[2]; - int hlen = sizeof(int) + len; - hdr[0] = htonl(hlen); - hdr[1] = htonl(kind); - if (gSocket->SendRaw(hdr, sizeof(hdr)) < 0) - return -1; - - return gSocket->SendRaw(buf, len); - } - -//////////////////////////////////////////////////////////////////////////////// -/// Send acknowledge code - - int NetSendAck() - { - return NetSend(0, kROOTD_ACK); - } - -//////////////////////////////////////////////////////////////////////////////// -/// Send error code - - int NetSendError(ERootdErrors err) - { - return NetSend(err, kROOTD_ERR); - } - -//////////////////////////////////////////////////////////////////////////////// -/// Send buffer of len bytes. - - int NetSendRaw(const void *buf, int len) - { - return gSocket->SendRaw(buf, len); - } - -//////////////////////////////////////////////////////////////////////////////// -/// Return name of connected host - - void NetGetRemoteHost(std::string &openhost) - { - // Get Host name - openhost = string(gSocket->GetInetAddress().GetHostName()); - } - -//////////////////////////////////////////////////////////////////////////////// -/// return errno - - int GetErrno() - { -#ifdef GLOBAL_ERRNO - return ::errno; -#else - return errno; -#endif - } -//////////////////////////////////////////////////////////////////////////////// -/// reset errno - - void ResetErrno() - { -#ifdef GLOBAL_ERRNO - ::errno = 0; -#else - errno = 0; -#endif - } - -//////////////////////////////////////////////////////////////////////////////// -/// Return in buf the message belonging to errno. - - void Perror(char *buf, int size) - { - int len = strlen(buf); -#if (defined(__sun) && defined (__SVR4)) || defined (__linux) || \ - defined(_AIX) || defined(__MACH__) - snprintf(buf+len, size, " (%s)", strerror(GetErrno())); -#else - if (GetErrno() >= 0 && GetErrno() < sys_nerr) - snprintf(buf+len, size, " (%s)", sys_errlist[GetErrno()]); -#endif - } - -//////////////////////////////////////////////////////////////////////////////// -/// Formats a string in a circular formatting buffer and prints the string. -/// Appends a newline. -/// Cut & Paste from Printf in base/src/TString.cxx - - void ErrorInfo(const char *va_(fmt), ...) - { - char buf[1024]; - va_list ap; - va_start(ap,va_(fmt)); - vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - printf("%s\n", buf); - fflush(stdout); - } - -//////////////////////////////////////////////////////////////////////////////// -/// Write error message and call a handler, if required - - void Error(ErrorHandler_t func,int code,const char *va_(fmt), ...) - { - char buf[1024]; - va_list ap; - va_start(ap,va_(fmt)); - vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - printf("%s\n", buf); - fflush(stdout); - - // Actions are defined by the specific error handler ( - // see rootd.cxx) - if (func) (*func)(code,(const char *)buf, sizeof(buf)); - } - -} // namespace ROOT diff --git a/net/rpdutils/src/DaemonUtils.h b/net/rpdutils/src/DaemonUtils.h deleted file mode 100644 index d28622b0f63a8..0000000000000 --- a/net/rpdutils/src/DaemonUtils.h +++ /dev/null @@ -1,53 +0,0 @@ -// @(#)root/auth:$Id$ -// Author: Gerri Ganis 19/1/2004 - -/************************************************************************* - * Copyright (C) 1995-2003, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_DaemonUtils -#define ROOT_DaemonUtils - - -////////////////////////////////////////////////////////////////////////// -// // -// DaemonUtils // -// // -// This file defines wrappers to client utils calls used by server // -// authentication daemons. // -// // -////////////////////////////////////////////////////////////////////////// - -#include - -#include "TSocket.h" -#include "TSeqCollection.h" -#include "NetErrors.h" -#include "rpddefs.h" - -#include "rpdp.h" - - -extern Int_t SrvAuthImpl(TSocket *socket, const char *, const char *, - std::string &user, Int_t &meth, - Int_t &type, std::string &ctoken, TSeqCollection *); -extern Int_t SrvClupImpl(TSeqCollection *); - -typedef void (*ErrorHandler_t)(int level, const char *msg, int size); - - -namespace ROOT { - -// Error handlers prototypes ... -extern ErrorHandler_t gErrSys; -extern ErrorHandler_t gErrFatal; -extern ErrorHandler_t gErr; -void SrvSetSocket(TSocket *socket); - -} - -#endif diff --git a/net/rpdutils/src/daemon.cxx b/net/rpdutils/src/daemon.cxx deleted file mode 100644 index c64b3d80f7045..0000000000000 --- a/net/rpdutils/src/daemon.cxx +++ /dev/null @@ -1,198 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Fons Rademakers 11/08/97 -// Modifified: Gerardo Ganis 8/04/2003 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// DaemonStart // -// // -// Detach a daemon process from login session context. // -// // -////////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include -#include -#include - -#if defined(__linux__) && !defined(linux) -# define linux -#endif - -#ifdef SIGTSTP -#include -#include -#include -#endif - -#include - -#ifndef NOFILE -# define NOFILE 0 -#endif - -#if defined(linux) || defined(__hpux) || defined(__sun) || defined(__sgi) || \ - defined(_AIX) || defined(__FreeBSD__) || defined(__OpenBSD__) || \ - defined(__APPLE__) || defined(__MACH__) || \ - (defined(__CYGWIN__) && defined(__GNUC__)) -#define USE_SETSID -#endif - - -#include "rpdp.h" - -extern int gDebug; - -namespace ROOT { - -extern ErrorHandler_t gErrSys; - -//////////////////////////////////////////////////////////////////////////////// - -static void SigChild(int) -{ - int pid; - int status; - - while ((pid = wait3(&status, WNOHANG, 0)) > 0) - ; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Detach a daemon process from login session context. - -void DaemonStart(int ignsigcld, int fdkeep, EService service) -{ - // If we were started by init (process 1) from the /etc/inittab file - // there's no need to detach. - // This test is unreliable due to an unavoidable ambiguity - // if the process is started by some other process and orphaned - // (i.e. if the parent process terminates before we are started). - - int fd; - -#if !(defined(__CYGWIN__) && defined(__GNUC__)) - if (getppid() == 1) { - if (service == kROOTD) printf ("ROOTD_PID=%ld\n", (long) getpid()); - goto out; - } -#endif - - // Ignore the terminal stop signals (BSD). - -#ifdef SIGTTOU - signal(SIGTTOU, SIG_IGN); -#endif -#ifdef SIGTTIN - signal(SIGTTIN, SIG_IGN); -#endif -#ifdef SIGTSTP - signal(SIGTSTP, SIG_IGN); -#endif - - // If we were not started in the background, fork and let the parent - // exit. This also guarantees the first child is not a process - // group leader. - - int childpid; - if ((childpid = fork()) < 0) { - if (service == kROOTD) fprintf(stderr, "DaemonStart: can't fork first child\n"); - Error(gErrSys,kErrFatal, "DaemonStart: can't fork first child"); - } else if (childpid > 0) { -#ifdef SIGTSTP - if (service == kROOTD) printf("ROOTD_PID=%d\n", childpid); -#endif - exit(0); // parent - } else { - if (gDebug > 2) - ErrorInfo("DaemonStart: this is the child thread ... socket is: %d",fdkeep); - } - - // First child process... - - // Disassociate from controlling terminal and process group. - // Ensure the process can't reacquire a new controlling terminal. - -#ifdef SIGTSTP - -#ifdef USE_SETSID - if (setsid() == -1) { -#else - if (setpgrp(0, getpid()) == -1) { -#endif - if (service == kROOTD) - fprintf(stderr, "DaemonStart: can't change process group\n"); - Error(gErrSys,kErrFatal, "DaemonStart: can't change process group"); - } - - if ((fd = open("/dev/tty", O_RDWR)) >= 0) { -#if !defined(__hpux) && !defined(__sun) && \ - !(defined(__CYGWIN__) && defined(__GNUC__)) - ioctl(fd, TIOCNOTTY, 0); // loose controlling tty -#endif - close(fd); - } - -#else - - if (setpgrp() == -1) { - if (service == kROOTD) - fprintf(stderr,"DaemonStart: can't change process group\n"); - Error(gErrSys,kErrFatal, "DaemonStart: can't change process group"); - } - - signal(SIGHUP, SIG_IGN); // immune from pgrp leader death - - if ((childpid = fork()) < 0) { - if (service == kROOTD) - fprintf(stderr, "DaemonStart: can't fork second child\n"); - Error(gErrSys,kErrFatal, "DaemonStart: can't fork second child"); - } else if (childpid > 0) { - if (service == kROOTD) printf("ROOTD_PID=%d (2nd fork)\n", childpid); - exit(0); // first child - } - -#endif -out: - // Close any open file descriptors - for (fd = 0; fd < NOFILE; fd++) { - if ((fd != fdkeep)) close(fd); - } - - ResetErrno(); // probably got set to EBADF from a close - - // Move current directory to root, make sure we aren't on a mounted - // file system. - - if (chdir("/") == -1) - fprintf(stderr, "DaemonStart: cannot chdir to /\n"); - - // Clear any inherited file mode creation mask - - umask(0); - - // See if the caller isn't interested in the exit status of its - // children and doesn't want to have them become zombies and - // clog up the system. - // With SysV all we need to do is ignore the signal. - // With BSD, however, we have to catch each signal - // and execute the wait3() system call. - - if (ignsigcld) { - signal(SIGCHLD, SigChild); - } -} - -} // namespace ROOT - diff --git a/net/rpdutils/src/error.cxx b/net/rpdutils/src/error.cxx deleted file mode 100644 index 6d182bb2771e6..0000000000000 --- a/net/rpdutils/src/error.cxx +++ /dev/null @@ -1,125 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Fons Rademakers 11/08/97 -// Modifified: Gerardo Ganis 8/04/2003 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// error // -// // -// Set of error handling routines for daemon process. // -// // -////////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include -#include -#include "snprintf.h" - -#if defined(hpux9) -extern "C" { - extern void openlog(const char *, int, int); - extern void syslog(int, const char *, ...); -} -#endif - -#include "rpderr.h" -#include "rpdp.h" - -// This is the only really global -extern int gDebug; - -namespace ROOT { - -extern bool gSysLog; - -//////////////////////////////////////////////////////////////////////////////// - -int GetErrno() -{ - return errno; -} - -//////////////////////////////////////////////////////////////////////////////// - -void ResetErrno() -{ - errno = 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Write info message to syslog. - -void ErrorInfo(const char *va_(fmt), ...) -{ - char buf[ROOT::Deprecated::kMAXSECBUF]; - va_list ap; - - va_start(ap,va_(fmt)); - vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - - if (gSysLog) { - syslog(LOG_INFO, "%s\n", buf); - } else { - fprintf(stderr, "%s\n", buf); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Open syslog. - -void ErrorInit(const char *ident) -{ - openlog(ident, (LOG_PID | LOG_CONS), LOG_DAEMON); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Return in buf the message belonging to errno. - -void Perror(char *buf, int size) -{ - int len = strlen(buf); -#if (defined(__sun) && defined (__SVR4)) || defined (__linux) || \ - defined(_AIX) || defined(__MACH__) - snprintf(buf+len, size, " (%s)", strerror(GetErrno())); -#else - if (GetErrno() >= 0 && GetErrno() < sys_nerr) - snprintf(buf+len, size, " (%s)", sys_errlist[GetErrno()]); -#endif -} - -//////////////////////////////////////////////////////////////////////////////// -/// Write fatal message to syslog and exit. - -void Error(ErrorHandler_t func, int code, const char *va_(fmt), ...) -{ - char buf[ROOT::Deprecated::kMAXSECBUF]; - va_list ap; - - va_start(ap,va_(fmt)); - vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - - if (gSysLog) { - syslog(LOG_ERR, "%s\n", buf); - } else { - fprintf(stderr, "%s\n", buf); - } - - // Actions are defined by the specific error handler function - // (see rootd.cxx) - if (func) (*func)(code,(const char *)buf, sizeof(buf)); -} - -} // namespace ROOT diff --git a/net/rpdutils/src/net.cxx b/net/rpdutils/src/net.cxx deleted file mode 100644 index 02f4c43b939a4..0000000000000 --- a/net/rpdutils/src/net.cxx +++ /dev/null @@ -1,586 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Fons Rademakers 12/08/97 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// net // -// // -// Set of network routines for rootd daemon process. // -// // -////////////////////////////////////////////////////////////////////////// - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "rpdp.h" -#include "rpderr.h" - -extern int gDebug; - -namespace ROOT { - -extern std::string gServName[3]; - -extern ErrorHandler_t gErrSys; -extern ErrorHandler_t gErrFatal; - -static double gBytesSent = 0; -static double gBytesRecv = 0; - -static std::string gOpenhost = "????"; - -static int gTcpSrvSock; -static struct sockaddr_in gTcpSrvAddr; -static struct sockaddr_in gTcpCliAddr; - -static int gSockFd = -1; -static SigPipe_t gSigPipeHook = 0; -extern int gParallel; - -//////////////////////////////////////////////////////////////////////////////// -/// return received bytes - -double NetGetBytesRecv() -{ - return gBytesRecv; -} - -//////////////////////////////////////////////////////////////////////////////// -/// return sent bytes - -double NetGetBytesSent() -{ - return gBytesSent; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Return name of connected host - -void NetGetRemoteHost(std::string &OpenHost) -{ - OpenHost = gOpenhost; -} - -//////////////////////////////////////////////////////////////////////////////// -/// return open socket descriptor - -int NetGetSockFd() -{ - return gSockFd; -} - -//////////////////////////////////////////////////////////////////////////////// -/// reset byte counts - -void NetResetByteCount() -{ - gBytesRecv = 0; - gBytesSent = 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set hook for SIGPIPE calls - -void NetSetSigPipeHook(SigPipe_t Hook) -{ - gSigPipeHook = Hook; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send exactly length bytes from buffer. - -static int Sendn(int sock, const void *buffer, int length) -{ - if (sock < 0) return -1; - - int n, nsent = 0; - const char *buf = (const char *)buffer; - - for (n = 0; n < length; n += nsent) { - if ((nsent = send(sock, buf+n, length-n, 0)) <= 0) { - Error(gErrFatal, -1, "Sendn: error (sock: %d): errno: %d", - sock, GetErrno()); - return nsent; - } - } - - gBytesSent += n; - - return n; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive exactly length bytes into buffer. Returns number of bytes -/// received or 0 in case connection is closed. Returns -1 in case of error. - -static int Recvn(int sock, void *buffer, int length) -{ - if (sock < 0) return -1; - - int n, nrecv = 0; - char *buf = (char *)buffer; - - for (n = 0; n < length; n += nrecv) { - while ((nrecv = recv(sock, buf+n, length-n, 0)) == -1 && GetErrno() == EINTR) - ResetErrno(); // probably a SIGCLD that was caught - if (nrecv == 0) - break; // EOF - if (nrecv < 0) { - Error(gErrFatal,-1,"Recvn: error (sock: %d): errno: %d",sock,GetErrno()); - return nrecv; - } - } - - gBytesRecv += n; - - return n; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send buffer of len bytes. - -int NetSendRaw(const void *buf, int len) -{ - if (gParallel > 0) { - - if (NetParSend(buf, len) != len) { - Error(gErrFatal,-1,"NetSendRaw: NetParSend error"); - } - - } else { - - if (gSockFd == -1 || !buf) return -1; - if (Sendn(gSockFd, buf, len) != len) { - Error(gErrFatal,-1,"NetSendRaw: Sendn error"); - } - } - - return len; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a buffer of maximum len bytes. - -int NetRecvRaw(void *buf, int len) -{ - if (gParallel > 0) { - - if (NetParRecv(buf, len) != len) { - Error(gErrFatal,-1,"NetRecvRaw: NetParRecv error"); - } - - } else { - - if (gSockFd == -1) return -1; - if (Recvn(gSockFd, buf, len) < 0) { - Error(gErrFatal,-1,"NetRecvRaw: Recvn error (gSockFd: %d)",gSockFd); - } - } - - return len; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a buffer of maximum len bytes from generic socket sock. - -int NetRecvRaw(int sock, void *buf, int len) -{ - if (sock == -1) return -1; - - if (Recvn(sock, buf, len) < 0) { - Error(gErrFatal,-1,"NetRecvRaw: Recvn error (sock: %d, errno: %d)",sock,GetErrno()); - } - - return len; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send buffer of len bytes. Message will be of type "kind". - -int NetSend(const void *buf, int len, EMessageTypes kind) -{ - int hdr[2]; - int hlen = sizeof(int) + len; - hdr[0] = htonl(hlen); - hdr[1] = htonl(kind); - if (NetSendRaw(hdr, sizeof(hdr)) < 0) - return -1; - - return NetSendRaw(buf, len); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send integer. Message will be of type "kind". - -int NetSend(int code, EMessageTypes kind) -{ - int hdr[3]; - int hlen = sizeof(int) + sizeof(int); - hdr[0] = htonl(hlen); - hdr[1] = htonl(kind); - hdr[2] = htonl(code); - return NetSendRaw(hdr, sizeof(hdr)); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send a string. Message will be of type "kind". - -int NetSend(const char *msg, EMessageTypes kind) -{ - int len = 0; - - if (msg) - len = strlen(msg)+1; - - return NetSend(msg, len, kind); -} - -//////////////////////////////////////////////////////////////////////////////// - -int NetSendAck() -{ - return NetSend(0, kROOTD_ACK); -} - -//////////////////////////////////////////////////////////////////////////////// - -int NetSendError(ERootdErrors err) -{ - return NetSend(err, kROOTD_ERR); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a buffer. Returns the newly allocated buffer, the length -/// of the buffer and message type in kind. - -int NetRecvAllocate(void *&buf, int &len, EMessageTypes &kind) -{ - int hdr[2] = { 0, 0 }; - - if (NetRecvRaw(hdr, sizeof(hdr)) < 0) - return -1; - - len = ntohl(hdr[0]) - sizeof(int); - if (len < 0) len = 0; - kind = (EMessageTypes) ntohl(hdr[1]); - if (len) { - buf = new char* [len]; - return NetRecvRaw(buf, len); - } - buf = 0; - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a string of maximum len length. Returns message type in kind. -/// Return value is msg length. - -int NetRecv(char *msg, int len, EMessageTypes &kind) -{ - int mlen = 0; - void *tmpbuf = nullptr; - - int res = NetRecvAllocate(tmpbuf, mlen, kind); - char *buf = static_cast(tmpbuf); - - if (res < 0) { - delete [] buf; - return -1; - } - - if (mlen == 0) { - msg[0] = 0; - delete [] buf; - return 0; - } else if (mlen > len-1) { - strncpy(msg, buf, len-1); - msg[len-1] = 0; - mlen = len; - } else { - strncpy(msg, buf, mlen); - msg[mlen] = 0; - } - - delete [] buf; - - return mlen - 1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Simulate TSocket::Recv(char *str, int max). - -int NetRecv(char *msg, int max) -{ - EMessageTypes kind; - - return NetRecv((char *)msg, max, kind); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Initialize the server's end. -/// We are passed a flag that says whether or not we are started -/// by a "master daemon" such as inetd. A master daemon will have -/// already waited for a message to arrive for us and will have -/// already set up the connection to the client. If we weren't -/// started by a master daemon, then we must wait for a client's -/// request to arrive. - -int NetOpen(int inetdflag, EService service) -{ - socklen_t clilen = sizeof(gTcpCliAddr); - - if (inetdflag) { - - // When we're fired up by inetd, file decriptors 0, 1 and 2 - // are sockets to the client. - - gSockFd = 0; - if (!getpeername(gSockFd, (struct sockaddr *)&gTcpCliAddr, &clilen)) { - struct hostent *hp; - if ((hp = gethostbyaddr((const char *)&gTcpCliAddr.sin_addr, - sizeof(gTcpCliAddr.sin_addr), AF_INET))) - gOpenhost = std::string(hp->h_name); - else { - struct in_addr *host_addr = (struct in_addr*)&gTcpCliAddr.sin_addr; - gOpenhost = std::string(inet_ntoa(*host_addr)); - } - } - - // Notify, if requested ... - if (gDebug > 1) - ErrorInfo("NetOpen: fired by inetd: connection from host %s" - " via socket %d", gOpenhost.data(),gSockFd); - - // Set several general performance network options - NetSetOptions(service,gSockFd, 65535); - - return 0; - } - - // For the concurrent server that's not initiated by inetd, - // we have to wait for a connection request to arrive, then - // fork a child to handle the client's request. - // Beware that the accept() can be interrupted, such as by - // a previously spawned child process that has terminated - // (for which we caught the SIGCLD signal). - -again: - int newsock = accept(gTcpSrvSock, (struct sockaddr *)&gTcpCliAddr, &clilen); - if (newsock < 0) { - if (GetErrno() == EINTR) { - ResetErrno(); - goto again; // probably a SIGCLD that was caught - } - Error(gErrSys,kErrFatal, "NetOpen: accept error (errno: %d) ... socket %d", - GetErrno(),gTcpSrvSock); - return 0; - } - - struct hostent *hp; - if ((hp = gethostbyaddr((const char *)&gTcpCliAddr.sin_addr, - sizeof(gTcpCliAddr.sin_addr), AF_INET))) - gOpenhost = std::string(hp->h_name); - else { - struct in_addr *host_addr = (struct in_addr*)&gTcpCliAddr.sin_addr; - gOpenhost = std::string(inet_ntoa(*host_addr)); - } - - // Fork a child process to handle the client's request. - // The parent returns the child pid to the caller, which is - // probably a concurrent server that'll call us again, to wait - // for the next client request to this well-known port. - - int childpid; - if ((childpid = fork()) < 0) - Error(gErrSys,kErrFatal, "NetOpen: server can't fork"); - else if (childpid > 0) { // parent - close(newsock); - return childpid; - } - - // Child process continues here. - // First close the original socket so that the parent - // can accept any further requests that arrive there. - // Then set "gSockFd" in our process to be the descriptor - // that we are going to process. - - close(gTcpSrvSock); - - gSockFd = newsock; - - // Notify, if requested ... - if (gDebug > 1) - ErrorInfo("NetOpen: concurrent server: connection from host %s" - " via socket %d", gOpenhost.data(), gSockFd); - - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Close the network connection. - -void NetClose() -{ - if (gParallel > 0) { - - NetParClose(); - - } else { - - close(gSockFd); - if (gDebug > 0) - ErrorInfo("NetClose: host = %s, fd = %d", - gOpenhost.data(), gSockFd); - gSockFd = -1; - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Initialize the network connection for the server, when it has *not* -/// been invoked by inetd. Used by rootd. - -int NetInit(EService servtype, int port1, int port2, int tcpwindowsize) -{ - // We weren't started by a master daemon. - // We have to create a socket ourselves and bind our well-known - // address to it. - - std::string service = gServName[servtype]; - - if (port1 <= 0) { - if (service.length()) { - struct servent *sp = getservbyname(service.data(), "tcp"); - if (!sp) { - if (servtype == kROOTD) { - port1 = 1094; - } else { - fprintf(stderr,"NetInit: unknown service: %s/tcp\n", service.data()); - Error(gErrFatal, kErrFatal, - "NetInit: unknown service: %s/tcp", service.data()); - } - } else { - port1 = ntohs(sp->s_port); - } - port2 += port1; // in this case, port2 is relative to service port - } else { - fprintf(stderr, "NetInit: must specify either service or port\n"); - Error(gErrFatal,kErrFatal, - "NetInit: must specify either service or port"); - } - } - - // Create the socket and bind our local address so that any client can - // send to us. - - if ((gTcpSrvSock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - fprintf(stderr, "NetInit: can't create socket\n"); - Error(gErrSys,kErrFatal, "NetInit: can't create socket"); - return gTcpSrvSock; - } - - int val = 1; - if (setsockopt(gTcpSrvSock, SOL_SOCKET, SO_REUSEADDR, (char*) &val, - sizeof(val)) == -1) { - fprintf(stderr, "NetInit: can't set SO_REUSEADDR socket option\n"); - Error(gErrSys, kErrFatal, "NetInit: can't set SO_REUSEADDR socket option"); - } - - // Set several general performance network options - NetSetOptions(kROOTD,gTcpSrvSock, tcpwindowsize); - - memset(&gTcpSrvAddr, 0, sizeof(gTcpSrvAddr)); - gTcpSrvAddr.sin_family = AF_INET; - gTcpSrvAddr.sin_addr.s_addr = htonl(INADDR_ANY); - - int port; - for (port= port1; port <= port2; port++) { - gTcpSrvAddr.sin_port = htons(port); - if (bind(gTcpSrvSock, (struct sockaddr *) &gTcpSrvAddr, - sizeof(gTcpSrvAddr)) == 0) break; - } - - if (port > port2) { - fprintf(stderr, "NetInit: can't bind local address to ports %d-%d\n", port1, port2); - Error(gErrSys, kErrFatal, "NetInit: can't bind local address to ports %d-%d", port1, port2); - } - - printf("ROOTD_PORT=%d\n", port); - port1 = port; - - // And set the listen parameter, telling the system that we're - // ready to accept incoming connection requests. - - // listen(gTcpSrvSock, 5); - if (listen(gTcpSrvSock, 5)==-1) { - ErrorInfo("NetInit: listen: error (errno: %d)",GetErrno()); - } - - if (gDebug > 0) - ErrorInfo("NetInit: socket %d listening on port %d", gTcpSrvSock, - ntohs(gTcpSrvAddr.sin_port)); - - return gTcpSrvSock; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set some options for network socket. - -void NetSetOptions(EService serv, int sock, int tcpwindowsize) -{ - int val = 1; - - if (serv == kROOTD) { - if (!setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,(char *)&val,sizeof(val))) - if (gDebug > 0) - ErrorInfo("NetSetOptions: set TCP_NODELAY"); - if (!setsockopt(sock,SOL_SOCKET,SO_KEEPALIVE,(char *)&val,sizeof(val))) { - if (gDebug > 0) - ErrorInfo("NetSetOptions: set SO_KEEPALIVE"); - if (gSigPipeHook != 0) - signal(SIGPIPE, (*gSigPipeHook)); // handle SO_KEEPALIVE failure - } - } - - val = tcpwindowsize; - if (!setsockopt(sock,SOL_SOCKET,SO_SNDBUF,(char *)&val,sizeof(val))) - if (gDebug > 0) - ErrorInfo("NetSetOptions: set SO_SNDBUF %d", val); - if (!setsockopt(sock,SOL_SOCKET,SO_RCVBUF,(char *)&val,sizeof(val))) - if (gDebug > 0) - ErrorInfo("NetSetOptions: set SO_RCVBUF %d", val); - - if (gDebug > 0) { - socklen_t optlen = sizeof(val); - if (serv == kROOTD) { - getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&val, &optlen); - ErrorInfo("NetSetOptions: get TCP_NODELAY: %d", val); - getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, &optlen); - ErrorInfo("NetSetOptions: get SO_KEEPALIVE: %d", val); - } - getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&val, &optlen); - ErrorInfo("NetSetOptions: get SO_SNDBUF: %d", val); - getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&val, &optlen); - ErrorInfo("NetSetOptions: get SO_RCVBUF: %d", val); - } -} - -} // namespace ROOT diff --git a/net/rpdutils/src/netpar.cxx b/net/rpdutils/src/netpar.cxx deleted file mode 100644 index 465bcdf797972..0000000000000 --- a/net/rpdutils/src/netpar.cxx +++ /dev/null @@ -1,264 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Fons Rademakers 06/02/2001 - -/************************************************************************* - * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// netpar // -// // -// Set of parallel network routines for rootd daemon process. To be // -// used when remote uses TPSocket to connect to rootd. // -// // -////////////////////////////////////////////////////////////////////////// - -#include - -// avoid warning due to wrong bzero prototype (used by FD_ZERO macro) -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(_AIX) -#include -#endif - -#include "rpdp.h" - -extern int gDebug; - -namespace ROOT { - -extern ErrorHandler_t gErrSys; - -int gParallel = 0; - -static int gMaxFd; -static int *gPSockFd; -static int *gWriteBytesLeft; -static int *gReadBytesLeft; -static char **gWritePtr; -static char **gReadPtr; -static fd_set gFdSet; - -//////////////////////////////////////////////////////////////////////////////// -/// Setup select masks. - -static void InitSelect(int nsock) -{ - FD_ZERO(&gFdSet); - gMaxFd = -1; - for (int i = 0; i < nsock; i++) { - FD_SET(gPSockFd[i], &gFdSet); - if (gPSockFd[i] > gMaxFd) - gMaxFd = gPSockFd[i]; - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send buffer of specified length over the parallel sockets. -/// Returns len in case of success and -1 in case of error. - -int NetParSend(const void *buf, int len) -{ - int i, alen = len, nsock = gParallel; - - if (!buf) return -1; - - // If data buffer is < 4K use only one socket - if (len < 4096) - nsock = 1; - - for (i = 0; i < nsock; i++) { - gWriteBytesLeft[i] = len/nsock; - gWritePtr[i] = (char *)buf + (i*gWriteBytesLeft[i]); - } - gWriteBytesLeft[i-1] += len%nsock; - - InitSelect(nsock); - - // Send the data on the parallel sockets - while (len > 0) { - - fd_set writeReady = gFdSet; - - int isel = select(gMaxFd+1, 0, &writeReady, 0, 0); - if (isel < 0) { - ErrorInfo("NetParSend: error on select"); - return -1; - } - - for (i = 0; i < nsock; i++) { - if (FD_ISSET(gPSockFd[i], &writeReady)) { - if (gWriteBytesLeft[i] > 0) { - int ilen; -again: - ilen = send(gPSockFd[i], gWritePtr[i], gWriteBytesLeft[i], 0); - if (ilen < 0) { - if (GetErrno() == EAGAIN) - goto again; - ErrorInfo("NetParSend: error sending for socket %d (%d)", - i, gPSockFd[i]); - return -1; - } - gWriteBytesLeft[i] -= ilen; - gWritePtr[i] += ilen; - len -= ilen; - } - } - } - } - - return alen; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive buffer of specified length over parallel sockets. -/// Returns len in case of success and -1 in case of error. - -int NetParRecv(void *buf, int len) -{ - int i, alen = len, nsock = gParallel; - - // If data buffer is < 4K use only one socket - if (len < 4096) - nsock = 1; - - for (i = 0; i < nsock; i++) { - gReadBytesLeft[i] = len/nsock; - gReadPtr[i] = (char *)buf + (i*gReadBytesLeft[i]); - } - gReadBytesLeft[i-1] += len%nsock; - - InitSelect(nsock); - - // Recieve the data on the parallel sockets - while (len > 0) { - - fd_set readReady = gFdSet; - - int isel = select(gMaxFd+1, &readReady, 0, 0, 0); - if (isel < 0) { - ErrorInfo("NetParRecv: error on select"); - return -1; - } - - for (i = 0; i < nsock; i++) { - if (FD_ISSET(gPSockFd[i], &readReady)) { - if (gReadBytesLeft[i] > 0) { - int ilen = recv(gPSockFd[i], gReadPtr[i], gReadBytesLeft[i], 0); - if (ilen < 0) { - ErrorInfo("NetParRecv: error receiving for socket %d (%d)", - i, gPSockFd[i]); - return -1; - } else if (ilen == 0) { - ErrorInfo("NetParRecv: EOF on socket %d (%d)", - i, gPSockFd[i]); - return 0; - } - gReadBytesLeft[i] -= ilen; - gReadPtr[i] += ilen; - len -= ilen; - } - } - } - } - - return alen; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Open size parallel sockets back to client. Returns 0 in case of error, -/// and number of parallel sockets in case of success. - -int NetParOpen(int port, int size) -{ - struct sockaddr_in remote_addr; - memset(&remote_addr, 0, sizeof(remote_addr)); - - socklen_t remlen = sizeof(remote_addr); - - if (!getpeername(NetGetSockFd(), (struct sockaddr *)&remote_addr, &remlen)) { - remote_addr.sin_family = AF_INET; - remote_addr.sin_port = htons(port); - - gPSockFd = new int[size]; - - for (int i = 0; i < size; i++) { - if ((gPSockFd[i] = socket(AF_INET, SOCK_STREAM, 0)) < 0) - Error(gErrSys, kErrFatal, "NetParOpen: can't create socket %d (%d)", - i, gPSockFd[i]); - - NetSetOptions(kROOTD, gPSockFd[i], 65535); - - if (connect(gPSockFd[i], (struct sockaddr *)&remote_addr, remlen) < 0) - Error(gErrSys, kErrFatal, "NetParOpen: can't connect socket %d (%d)", - i, gPSockFd[i]); - - // Set non-blocking - int val; - if ((val = fcntl(gPSockFd[i], F_GETFL, 0)) < 0) - Error(gErrSys, kErrFatal, "NetParOpen: can't get control flags"); - val |= O_NONBLOCK; - if (fcntl(gPSockFd[i], F_SETFL, val) < 0) - Error(gErrSys, kErrFatal, "NetParOpen: can't make socket non blocking"); - } - - gWriteBytesLeft = new int[size]; - gReadBytesLeft = new int[size]; - gWritePtr = new char*[size]; - gReadPtr = new char*[size]; - - // Close initial setup socket - NetClose(); - - gParallel = size; - - if (gDebug > 0) - ErrorInfo("NetParOpen: %d parallel connections established", size); - - } else - Error(gErrSys, kErrFatal, "NetParOpen: can't get peer name"); - - return gParallel; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Close parallel sockets. - -void NetParClose() -{ - for (int i = 0; i < gParallel; i++) - close(gPSockFd[i]); - - if (gDebug > 0) { - std::string host; - NetGetRemoteHost(host); - ErrorInfo("NetParClose: closing %d-stream connection to host %s", - gParallel, host.data()); - } - - delete [] gPSockFd; - delete [] gWriteBytesLeft; - delete [] gReadBytesLeft; - delete [] gWritePtr; - delete [] gReadPtr; - - gParallel = 0; -} - -} // namespace ROOT diff --git a/net/rpdutils/src/rpdconn.cxx b/net/rpdutils/src/rpdconn.cxx deleted file mode 100644 index 0eb8b9e85f63a..0000000000000 --- a/net/rpdutils/src/rpdconn.cxx +++ /dev/null @@ -1,1094 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Gerardo Ganis, March 2011 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// rpdconn // -// // -// This header file contains the definition of some utility classes // -// used for process communication between rootd. // -// // -////////////////////////////////////////////////////////////////////////// - -#include "rpdconn.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define RPD_MAXLEN 8192 - -// -// Control meaning of the msghdr structure -// -#if defined(__sun) -#define HAVE_MSGHDR_ACCRIGHT -#endif - -// -// To make socklen_t portable use SOCKLEN_t -// -#if defined(__solaris__) && !defined(__linux__) -# if __GNUC__ >= 3 || __GNUC_MINOR__ >= 90 -# define XR__SUNGCC3 -# endif -#endif -#if defined(__linux__) -# include -# if __GNU_LIBRARY__ == 6 -# ifndef XR__GLIBC -# define XR__GLIBC -# endif -# endif -#endif -#if defined(__MACH__) && defined(__i386__) -# define R__GLIBC -#endif -#if defined(_AIX) || (defined(XR__SUNGCC3) && !defined(__arch64__)) -# define SOCKLEN_t size_t -#elif defined(XR__GLIBC) || defined(__FreeBSD__) || \ - (defined(XR__SUNGCC3) && defined(__arch64__)) || defined(__APPLE__) || \ - (defined(__sun) && defined(_SOCKLEN_T)) -# ifndef SOCKLEN_t -# define SOCKLEN_t socklen_t -# endif -#elif !defined(SOCKLEN_t) -# define SOCKLEN_t int -#endif - -// -// Class describing a basic connection -// - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - -rpdconn::rpdconn(int r, int w) : rdfd(r), wrfd(w) -{ - int rc = 0; - pthread_mutexattr_t attr; - if (!(rc = pthread_mutexattr_init(&attr))) { - if (!(rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE))) { - pthread_mutex_init(&wrmtx, &attr); - pthread_mutex_init(&rdmtx, &attr); - } - } - pthread_mutexattr_destroy(&attr); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send an integer -/// Return: -/// 0 if OK -/// -1 if invalid descriptor -/// -2 if failed to acquire mutex lock - -int rpdconn::send(int i) -{ - rpdmtxhelper mh(&wrmtx); - if (isvalid(0)) { - if (mh.isok()) { - // Send the integer - i = htonl(i); - if (write(wrfd, &i, sizeof(i)) != sizeof(i)) - return -errno; - // Done - return 0; - } - // Could acquire the mutex lock - return -2; - } - // Invalid descriptor - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send a typed message -/// Return: -/// 0 if OK -/// -1 if invalid descriptor -/// -2 if failed to acquire mutex lock - -int rpdconn::send(int type, const char *msg) -{ - rpdmtxhelper mh(&wrmtx); - if (isvalid(0)) { - if (mh.isok()) { - // Send the type - type = htonl(type); - if (write(wrfd, &type, sizeof(type)) != sizeof(type)) - return -errno; - // Send the message, if any - int len = (msg) ? strlen(msg) : 0; - int mlen = len; - // Send the length - len = htonl(len); - if (write(wrfd, &len, sizeof(len)) != sizeof(len)) - return -errno; - if (msg && mlen > 0) - if (write(wrfd, msg, mlen) != mlen) - return -errno; - // Done - return 0; - } - // Could acquire the mutex lock - return -2; - } - // Invalid descriptor - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send message -/// Return: -/// 0 if OK -/// -1 if invalid descriptor -/// -2 if failed to acquire mutex lock - -int rpdconn::send(const rpdmsg &msg) -{ - return send(msg.type, msg.buf.c_str()); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send 'len' bytes at 'buf' -/// Return: -/// 0 if OK -/// -1 if invalid descriptor -/// -2 if failed to acquire mutex lock -/// -3 if the operation would block -/// -4 if connection broken -/// -errno if any another failure - -int rpdconn::send(const void *buf, int len) -{ - rpdmtxhelper mh(&wrmtx); - if (isvalid(0)) { - if (mh.isok()) { - // Send the buffer - int n, nsnt = 0; - const char *b = (const char *)buf; - for (n = 0; n < len; n += nsnt) { - errno = 0; - if ((nsnt = ::send(wrfd, b+n, len-n, 0)) <= 0) { - if (nsnt == 0) break; - if (errno != EINTR) { - if (errno == EPIPE || errno == ECONNRESET) - return -4; - else if (errno == EWOULDBLOCK) - return -3; - else - return -errno; - } - } - } - // Done - return 0; - } - // Could acquire the mutex lock - return -2; - } - // Invalid descriptor - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive an integer -/// Return: -/// 0 if OK -/// -1 if invalid descriptor -/// -2 if failed to acquire mutex lock - -int rpdconn::recv(int &i) -{ - rpdmtxhelper mh(&rdmtx); - if (isvalid(1)) { - if (mh.isok()) { - // Read the integer - if (read(rdfd, &i, sizeof(i)) != sizeof(i)) - return -errno; - i = ntohl(i); - // Done - return 0; - } - // Could acquire the mutex lock - return -2; - } - // Invalid descriptor - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a typed message -/// Return: -/// 0 if OK -/// -1 if invalid descriptor -/// -2 if failed to acquire mutex lock -/// -3 if failed to receive the full message (the partial message -/// is stored in 'msg') - -int rpdconn::recv(int &type, std::string &msg) -{ - rpdmtxhelper mh(&rdmtx); - if (isvalid(1)) { - if (mh.isok()) { - // Read message type - if (read(rdfd, &type, sizeof(type)) != sizeof(type)) - return -errno; - type = ntohl(type); - // Read message len - int len = 0; - if (read(rdfd, &len, sizeof(len)) != sizeof(len)) - return -errno; - len = ntohl(len); - int rc = 0; - if (len > 0) { - msg = ""; - // Read message - char buf[RPD_MAXLEN]; - int nr = -1; - do { - int wanted = (len > RPD_MAXLEN-1) ? RPD_MAXLEN-1 : len; - while ((nr = read(rdfd, buf, wanted)) < 0 && - errno == EINTR) - errno = 0; - if (nr < wanted) { - if (nr < 0) rc = -3; - break; - } else { - buf[nr] = '\0'; - msg += buf; - } - // Update counters - len -= nr; - } while (nr > 0 && len > 0); - - } - // Done - return rc; - } - // Could acquire the mutex lock - return -2; - } - // Invalid descriptor - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Recv message -/// Return: -/// 0 if OK -/// -1 if invalid descriptor -/// -2 if failed to acquire mutex lock - -int rpdconn::recv(rpdmsg &msg) -{ - return recv(msg.type, msg.buf); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive 'len' bytes at 'buf' -/// Return: -/// 0 if OK -/// -1 if invalid descriptor -/// -2 if failed to acquire mutex lock -/// -3 if the operation would block -/// -4 if connection broken -/// -errno if any another failure - -int rpdconn::recv(void *buf, int len) -{ - rpdmtxhelper mh(&rdmtx); - if (isvalid(1)) { - if (mh.isok()) { - int n, nrcv = 0; - char *b = (char *)buf; - for (n = 0; n < len; n += nrcv) { - errno = 0; - if ((nrcv = ::recv(rdfd, b+n, len-n, 0)) <= 0) { - if (nrcv == 0) break; // EOF - if (errno != EINTR) { - if (errno == EPIPE || errno == ECONNRESET) - return -4; - else if (errno == EWOULDBLOCK) - return -3; - else - return -errno; - } - } - } - // Done - return 0; - } - // Could acquire the mutex lock - return -2; - } - // Invalid descriptor - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Poll over the read descriptor for to secs; -/// Return: -/// >0 ready to poll -/// 0 timeout -/// -1 invalid descriptor -/// <-1 -errno from 'poll' - -int rpdconn::pollrd(int to) -{ - if (isvalid(1)) { - - // Read descriptor - struct pollfd fds_r; - fds_r.fd = rdfd; - fds_r.events = POLLIN; - - // We wait for processes to communicate a session status change - int pollrc = 0; - int xto = (to > 0) ? to * 1000 : -1; - while ((pollrc = poll(&fds_r, 1, xto)) < 0 && (errno == EINTR)) { - errno = 0; - } - // Done - return (pollrc >= 0) ? pollrc : -errno; - } - // Invalid pipe - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send a descriptor to a the connected peer -/// Return: -/// 0 if OK -/// -1 if invalid -/// -2 if failed to acquire mutex lock -/// <-2 -errno from sendmsg - -int rpdconn::senddesc(int desc) -{ - rpdmtxhelper mh(&wrmtx); - if (isvalid(0)) { - if (mh.isok()) { - // Create the structure - struct msghdr msg; - memset(&msg, 0, sizeof(msg)); - // Set the descriptor pointers -#ifndef HAVE_MSGHDR_ACCRIGHT - struct cmsghdr *cmsg; - int myfds[1] = {desc}; // Contains the file descriptor to pass -#ifdef R__MACOSX - char buf[sizeof(struct cmsghdr) + sizeof (myfds)]; -#else - char buf[CMSG_SPACE(sizeof myfds)]; // ancillary data buffer -#endif - int *fdptr = 0; - msg.msg_control = buf; - msg.msg_controllen = sizeof buf; - cmsg = CMSG_FIRSTHDR(&msg); - cmsg->cmsg_level = SOL_SOCKET; - cmsg->cmsg_type = SCM_RIGHTS; - cmsg->cmsg_len = CMSG_LEN(sizeof(int)); - // Initialize the payload: - fdptr = (int *) CMSG_DATA(cmsg); - memcpy(fdptr, myfds, sizeof(int)); - // Sum of the length of all control messages in the buffer - msg.msg_controllen = cmsg->cmsg_len; -#else - msg.msg_accrights = (caddr_t) &desc; - msg.msg_accrightslen = sizeof(desc); -#endif - struct iovec iov[1]; - memset(iov, 0, sizeof(iov)); - // The recvmsg() call will NOT block unless a non-zero length data - // buffer is specified - char c = '\0'; - iov[0].iov_base = &c; - iov[0].iov_len = 1; - msg.msg_iov = iov; - msg.msg_iovlen = 1; - // Send it over - if (sendmsg(wrfd, &msg, 0) < 0) - return -errno; - // We can close the descriptor in this process - ::close(desc); - // Done - return 0; - } - // Could acquire the mutex lock - return -2; - } - // Invalid descriptor - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive a descriptor from a the connected peer -/// Return: -/// 0 if OK -/// -1 if invalid -/// -2 if failed to acquire mutex lock -/// <-2 -errno from recvmsg - -int rpdconn::recvdesc(int &desc) -{ - rpdmtxhelper mh(&rdmtx); - if (isvalid(1)) { - if (mh.isok()) { - // Create the structures and initialize them - struct msghdr msg; - memset(&msg, 0, sizeof(msg)); -#ifndef HAVE_MSGHDR_ACCRIGHT - union { - struct cmsghdr cm; -#ifdef R__MACOSX - char control[sizeof(struct cmsghdr) + sizeof (int)]; -#else - char control[CMSG_SPACE(sizeof (int))]; -#endif - } control_un; - struct cmsghdr *cmptr; - - msg.msg_control = control_un.control; - msg.msg_controllen = sizeof(control_un.control); -#else - int tmpdesc = 0; - msg.msg_accrights = (caddr_t) &tmpdesc; - msg.msg_accrightslen = sizeof(tmpdesc); -#endif - struct iovec iov[1]; - memset(iov, 0, sizeof(iov)); - // The recvmsg() call will NOT block unless a non-zero length data - // buffer is specified - char c; - iov[0].iov_base = &c; - iov[0].iov_len = 1; - msg.msg_iov = iov; - msg.msg_iovlen = 1; - // Receive it - if (recvmsg(rdfd, &msg, 0) < 0) - return -errno; -#ifndef HAVE_MSGHDR_ACCRIGHT - if ((cmptr = CMSG_FIRSTHDR(&msg)) != 0 && - cmptr->cmsg_len == CMSG_LEN(sizeof(int))) { - if (cmptr->cmsg_level != SOL_SOCKET) - return -errno; - if (cmptr->cmsg_type != SCM_RIGHTS) - return -errno; - memcpy((void *)&desc, CMSG_DATA(cmptr), sizeof(int)); - } else - desc = -1; // descriptor was not passed -#else - if (msg.msg_accrightslen == sizeof(int)) - desc = tmpdesc; - else - desc = -1; // descriptor was not passed -#endif - // Done - return 0; - } - // Could acquire the mutex lock - return -2; - } - // Invalid descriptor - return -1; -} - -// -// Class describing a UNIX connection -// - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - -rpdtcp::rpdtcp(const char *h, int p) : rpdconn(), host(h), port(p), fd(-1) -{ - struct hostent *hent = 0; - if (!(hent = gethostbyname(h))) { - fprintf(stderr, "rpdtcp::rpdtcp: ERROR: failure resolving host address (errno: %d)\n", errno); - return; - } - memset(&addr, 0, sizeof(addr)); - - // The structure - struct sockaddr_in server; - memset(&server, 0, sizeof(server)); - server.sin_family = hent->h_addrtype; - memcpy((char *) &server.sin_addr.s_addr, hent->h_addr_list[0], hent->h_length); - server.sin_port = htons(port); - - // Open socket - if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - fprintf(stderr, "rpdtcp::rpdtcp: ERROR: failure getting socket descriptor (errno: %d)\n", errno); - return; - } - - // Connect - errno = 0; - while (connect(fd, (struct sockaddr*) &server, sizeof(server)) == -1) { - if (errno == EINTR) { - errno = 0; - } else { - fprintf(stderr, "rpdtcp::rpdtcp: ERROR: failure while connecting to '%s:%d' (errno: %d)\n", - h, p, errno); - ::close(fd); - return; - } - } - - // Set descriptors - setdescriptors(fd, fd); - - // Done - return; -} - -// -// Class describing a server TCP connection -// - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - -rpdtcpsrv::rpdtcpsrv(int p, int backlog) : rpdtcp(p) -{ - // The structure - struct sockaddr_in inserver; - memset(&inserver, 0, sizeof(inserver)); - inserver.sin_family = AF_INET; - inserver.sin_addr.s_addr = htonl(INADDR_ANY); - inserver.sin_port = htons(p); - - // Open socket - if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - fprintf(stderr, "rpdtcpsrv::rpdtcpsrv: ERROR: failure getting socket descriptor (errno: %d)\n", errno); - return; - } - - if (bind(fd, (struct sockaddr*) &inserver, sizeof(inserver))) { - fprintf(stderr, "rpdtcpsrv::rpdtcpsrv: ERROR: failure binding socket (errno: %d)\n", errno); - ::close(fd); - fd = -1; - return; - } - - // Start accepting connections - if (listen(fd, backlog)) { - fprintf(stderr, "rpdtcpsrv::rpdtcpsrv: ERROR: failure enabling listening on socket (errno: %d)\n", errno); - ::close(fd); - fd = -1; - return; - } - - // Set descriptors - setdescriptors(fd, fd); - - // Done - return; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Accept a connection on the server socket. -/// If to > 0, wait max to secs (granularity 1 sec). -/// Return a rpdtcp object describing the open connection (to be destroyed -/// by the caller). -/// On error return a NULL pointer and the errno in *err, if defined; - -rpdtcp *rpdtcpsrv::accept(int to, int *err) -{ - int d = -1; - // Wait for incoming connections in steps of 1 sec - int tw = 0, rc = 0; - while (d < 0 && (to <= 0 || tw < to)) { - struct pollfd sfd = {fd, POLLIN|POLLRDNORM|POLLRDBAND|POLLPRI|POLLHUP, 0}; - do { - errno = 0; - rc = poll(&sfd, 1, 1000); - } while (rc < 0 && (errno == EAGAIN || errno == EINTR)); - if (rc > 0) { - errno = 0; - SOCKLEN_t addrlen = sizeof(addr); - while ((d = ::accept(fd, &addr, &addrlen)) == -1 && errno == EINTR) { - errno = 0; - } - } - // Count waited time - tw++; - } - - // Create the socket - rpdtcp *c = 0; - if (d < 0 && err) { - if (rc == 0) { - *err = ETIME; // Timed out - } else if (errno > 0) { - *err = (int) errno; - } else { - *err = -1; - } - } else { - c = new rpdtcp(d); - printf("rpdtcpsrv::accept: got descriptor %d\n", d); - } - - // Done - return c; -} - -// -// Class describing a UNIX connection -// - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - -rpdunix::rpdunix(const char *p) : rpdtcp(0), sockpath(p) -{ - // Need a valid path - unsigned int plen = 0; - if (!p || (p && (plen = strlen(p)) <= 0)) { - fprintf(stderr, "rpdunix::rpdunix: ERROR: path is undefined\n"); - return; - } - - struct sockaddr_un unserver; - memset(&unserver, 0, sizeof(unserver)); - unserver.sun_family = AF_UNIX; - - if (plen > sizeof(unserver.sun_path)-1) { - fprintf(stderr, "rpdunix::rpdunix: ERROR: socket path %s, longer than max allowed length (%u)\n", - p, (unsigned int)sizeof(unserver.sun_path)-1); - return; - } - strcpy(unserver.sun_path, p); - - // Open socket - if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { - fprintf(stderr, "rpdunix::rpdunix: ERROR: failure getting socket descriptor (errno: %d)\n", errno); - return; - } - - // Connect - errno = 0; - while (connect(fd, (struct sockaddr*) &unserver, strlen(unserver.sun_path)+2) == -1) { - if (errno == EINTR) { - errno = 0; - } else { - fprintf(stderr, "rpdunix::rpdunix: ERROR: failure while connecting over '%s' (errno: %d)\n", - p, errno); - ::close(fd); - fd = -1; - return; - } - } - - // Set descriptors - setdescriptors(fd, fd); - - // Done - return; -} - -// -// Class describing a server UNIX connection -// - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - -rpdunixsrv::rpdunixsrv(const char *p, int backlog) : rpdunix() -{ - // Need a valid path - unsigned int plen = 0; - if (!p || (p && (plen = strlen(p)) <= 0)) { - fprintf(stderr, "rpdunixsrv::rpdunixsrv: ERROR: path is undefined\n"); - return; - } - - // Clean the path, if already existing - struct stat st; - if (stat(p, &st) != 0) { - if (errno != ENOENT) { - fprintf(stderr, "rpdunixsrv::rpdunixsrv: ERROR: cannot operate on (parts of) path '%s' (errno: %d)\n", p, errno); - return; - } - } else { - // Remove it - if (unlink(p)) { - fprintf(stderr, "rpdunixsrv::rpdunixsrv: ERROR: cannot unlink path '%s'\n", p); - return; - } - } - - // Prepare the structure - struct sockaddr_un unserver; - memset(&unserver, 0, sizeof(unserver)); - unserver.sun_family = AF_UNIX; - - if (plen > sizeof(unserver.sun_path)-1) { - fprintf(stderr, "rpdunixsrv::rpdunixsrv: ERROR: socket path %s, longer than max allowed length (%u)\n", - p, (unsigned int)sizeof(unserver.sun_path)-1); - return; - } - strcpy(unserver.sun_path, p); - - // Open socket - if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { - fprintf(stderr, "rpdunixsrv::rpdunixsrv: ERROR: failure getting socket descriptor (errno: %d)\n", errno); - return; - } - - // Should be able to reuse this - int val = 1; - if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val)) == -1) { - fprintf(stderr, "rpdunixsrv::rpdunixsrv: ERROR: failure setting SO_REUSEADDR (errno: %d)\n", errno); - return; - } - - // Bind - if (bind(fd, (struct sockaddr*) &unserver, strlen(unserver.sun_path)+2)) { - fprintf(stderr, "rpdunixsrv::rpdunixsrv: ERROR: failure binding socket (errno: %d)\n", errno); - ::close(fd); - fd = -1; - return; - } - - // Start accepting connections - if (listen(fd, backlog)) { - fprintf(stderr, "rpdunixsrv::rpdunixsrv: ERROR: failure enabling listening on socket (errno: %d)\n", errno); - ::close(fd); - fd = -1; - return; - } - - // Set descriptors - setdescriptors(fd, fd); - - // Save the path - sockpath = p; - - // Done - return; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Accept a connection on the server socket. -/// If to > 0, wait max to secs (granularity 1 sec). -/// Return a rpdunix object describing the open connection (to be destroyed -/// by the caller). -/// On error return a NULL pointer and the errno in *err, if defined; - -rpdunix *rpdunixsrv::accept(int to, int *err) -{ - int d = -1; - - // Wait for incoming connections in steps of 1 sec - int tw = 0, rc = 0; - while (d < 0 && (to <= 0 || tw < to)) { - struct pollfd sfd = {fd, POLLIN|POLLRDNORM|POLLRDBAND|POLLPRI|POLLHUP, 0}; - do { - errno = 0; - rc = poll(&sfd, 1, 1000); - } while (rc < 0 && (errno == EAGAIN || errno == EINTR)); - if (rc > 0) { - SOCKLEN_t addrlen = sizeof(addr); - errno = 0; - while ((d = ::accept(fd, &addr, &addrlen)) == -1 && errno == EINTR) { - errno = 0; - } - } - // Count waited time - tw++; - } - - // Create the socket - rpdunix *c = 0; - if (d < 0 && err) { - if (rc == 0) { - *err = ETIME; // Timed out - } else if (errno > 0) { - *err = (int) errno; - } else { - *err = -1; - } - } else { - c = new rpdunix(d); - } - - // Done - return c; -} - -// -// Class describing a UDP connection -// - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - -rpdudp::rpdudp(const char *h, int p) : rpdtcp(h,p) -{ - struct hostent *hent = 0; - if (!(hent = gethostbyname(h))) { - fprintf(stderr, "rpdtcp::rpdtcp: ERROR: failure resolving host address (errno: %d)\n", errno); - return; - } - - // The structure - struct sockaddr_in server; - memset(&server, 0, sizeof(server)); - server.sin_family = hent->h_addrtype; - memcpy((char *) &server.sin_addr.s_addr, hent->h_addr_list[0], hent->h_length); - server.sin_port = htons(port); - - // Open socket - if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { - fprintf(stderr, "rpdudp::rpdudp: ERROR: failure getting socket descriptor (errno: %d)\n", errno); - return; - } - - // Connect - errno = 0; - while (connect(fd, (struct sockaddr*) &server, sizeof(server)) == -1) { - if (errno == EINTR) { - errno = 0; - } else { - fprintf(stderr, "rpdudp::rpdudp: ERROR: failure while connecting to '%s:%d' (errno: %d)\n", - h, p, errno); - ::close(fd); - return; - } - } - - // Set descriptors - setdescriptors(fd, fd); - - // Done - return; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor - -rpdudpsrv::rpdudpsrv(int p) : rpdudp(p) -{ - // The structure - struct sockaddr_in inserver; - memset(&inserver, 0, sizeof(inserver)); - inserver.sin_family = AF_INET; - inserver.sin_addr.s_addr = htonl(INADDR_ANY); - inserver.sin_port = htons(p); - - // Open socket - if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { - fprintf(stderr, "rpdudpsrv::rpdudpsrv: ERROR: failure getting socket descriptor (errno: %d)\n", errno); - return; - } - - if (bind(fd, (struct sockaddr*) &inserver, sizeof(inserver))) { - fprintf(stderr, "rpdudpsrv::rpdudpsrv: ERROR: failure binding socket (errno: %d)\n", errno); - ::close(fd); - fd = -1; - return; - } - - // Set descriptors - setdescriptors(fd, fd); - - // Done - return; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send 'len' bytes at 'buf' -/// Return: -/// 0 if OK -/// -1 if invalid descriptor -/// -2 if failed to acquire mutex lock -/// -errno if any another failure - -int rpdudp::send(const void *buf, int len) -{ - rpdmtxhelper mh(&wrmtx); - if (isvalid(0)) { - if (mh.isok()) { - // Send the buffer - int n, nsnt = 0; - const char *b = (const char *)buf; - for (n = 0; n < len; n += nsnt) { - errno = 0; - if ((nsnt = ::sendto(wrfd, b+n, len-n, 0, 0, 0)) <= 0) { - if (nsnt == 0) break; - return -errno; - } - } - // Done - return 0; - } - // Could acquire the mutex lock - return -2; - } - // Invalid descriptor - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive 'len' bytes at 'buf' -/// Return: -/// 0 if OK -/// -1 if invalid descriptor -/// -2 if failed to acquire mutex lock -/// -errno if any another failure - -int rpdudp::recv(void *buf, int len) -{ - rpdmtxhelper mh(&rdmtx); - if (isvalid(1)) { - if (mh.isok()) { - int n, nrcv = 0; - char *b = (char *)buf; - for (n = 0; n < len; n += nrcv) { - errno = 0; - SOCKLEN_t addrlen = sizeof(addr); - if ((nrcv = recvfrom(rdfd, b+n, len-n, 0, &addr, &addrlen)) <= 0) { - if (nrcv == 0) break; // EOF - return -errno; - } - } - // Done - return 0; - } - // Could acquire the mutex lock - return -2; - } - // Invalid descriptor - return -1; -} - -// -// Class describing a basic message -// - -//////////////////////////////////////////////////////////////////////////////// -/// Add int 'i' to the internal buffer - -void rpdmsg::w_int(int i) -{ - char b[64] = {0}; - snprintf(b, 64, "%d", i); - if (!buf.empty()) buf += " "; - buf += b; - if (cur < 0) cur = 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Add double 'd' to the internal buffer - -void rpdmsg::w_double(double d) -{ - char b[128] = {0}; - snprintf(b, 128, "%f", d); - if (!buf.empty()) buf += " "; - buf += b; - if (cur < 0) cur = 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Add string 's' to the internal buffer - -void rpdmsg::w_string(const std::string &s) -{ - if (!buf.empty()) buf += " "; - buf += "'"; - buf += s; - buf += "'"; - if (cur < 0) cur = 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Retrieve an int from the internal buffer - -void rpdmsg::r_int(int &i) -{ - if (cur < 0 || cur > (int) buf.length()) return; - - char *p= ((char *)buf.c_str()) + cur; - while (*p == ' ') p++; - sscanf(p, "%d", &i); - if ((p = (char *) strchr(p+1, ' '))) while (*p == ' ') p++; - - // Update pointer - if (p) { - cur = (int) (p - (char *)buf.c_str()); - } else { - cur = (int) buf.length(); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Retrieve a double from the internal buffer - -void rpdmsg::r_double(double &d) -{ - if (cur < 0 || cur > (int) buf.length()) return; - - char *p= ((char *)buf.c_str()) + cur; - while (*p == ' ') p++; - float f; - sscanf(p, "%f", &f); - d = (double) f; - if ((p = (char *) strchr(p+1, ' '))) while (*p == ' ') p++; - - // Update pointer - if (p) { - cur = (int) (p - (char *)buf.c_str()); - } else { - cur = (int) buf.length(); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Retrieve a string from the internal buffer - -void rpdmsg::r_string(std::string &s) -{ - if (cur < 0 || cur > (int) buf.length()) return; - - s = ""; - int from = cur; - char *p = ((char *)buf.c_str()) + cur; - while (*p == ' ') { from++; p++; } - char *e = strchr(p, ' '); - int len = buf.length() - from; - len = (e) ? (int) (e - p) : buf.length() - from; - if (len > 0) s.assign(buf, from, len); - // Remove single quotes, if any - if (s[0] == '\'') s.erase(0,1); - if (s.length() > 0 && s[s.length() - 1] == '\'') s.erase(s.length() - 1, std::string::npos); - - // Update pointer - if (e) { - cur = (int) (e - (char *)buf.c_str()) + 1; - } else { - cur = (int) buf.length(); - } -} - diff --git a/net/rpdutils/src/rpdpriv.cxx b/net/rpdutils/src/rpdpriv.cxx deleted file mode 100644 index 8ca082792d22b..0000000000000 --- a/net/rpdutils/src/rpdpriv.cxx +++ /dev/null @@ -1,384 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Gerardo Ganis, March 2011 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// rpdpriv // -// // -// Implementation of a privileges handling API following the paper // -// "Setuid Demystified" by H.Chen, D.Wagner, D.Dean // -// also quoted in "Secure programming Cookbook" by J.Viega & M.Messier. // -// // -////////////////////////////////////////////////////////////////////////// - -#include "rpdpriv.h" -#include "RConfigure.h" - -#if !defined(WINDOWS) -#include -#include -#include -#include -#include -#include -using std::cout, std::endl; - -#define NOUC ((uid_t)(-1)) -#define NOGC ((gid_t)(-1)) -#define RPPERR(x) ((x == 0) ? -1 : -x) - -// Some machine specific stuff -#if defined(__sgi) && !defined(__GNUG__) && (SGI_REL<62) -extern "C" { - int seteuid(int euid); - int setegid(int egid); - int geteuid(); - int getegid(); -} -#endif - -#if defined(_AIX) -extern "C" { - int seteuid(uid_t euid); - int setegid(gid_t egid); - uid_t geteuid(); - gid_t getegid(); -} -#endif - -#if !defined(R__HAS_SETRESUID) -static int setresgid(gid_t r, gid_t e, gid_t) -{ - if (r != NOGC && setgid(r) == -1) - return RPPERR(errno); - return ((e != NOGC) ? setegid(e) : 0); -} - -static int setresuid(uid_t r, uid_t e, uid_t) -{ - if (r != NOUC && setuid(r) == -1) - return RPPERR(errno); - return ((e != NOUC) ? seteuid(e) : 0); -} - -static int getresgid(gid_t *r, gid_t *e, gid_t *) -{ - *r = getgid(); - *e = getegid(); - return 0; -} - -static int getresuid(uid_t *r, uid_t *e, uid_t *) -{ - *r = getuid(); - *e = geteuid(); - return 0; -} - -#else -#if (defined(__linux__) || \ - (defined(__CYGWIN__) && defined(__GNUC__))) && !defined(linux) -# define linux -#endif -#if defined(linux) && !defined(R__HAS_SETRESUID) -extern "C" { - int setresgid(gid_t r, gid_t e, gid_t s); - int setresuid(uid_t r, uid_t e, uid_t s); - int getresgid(gid_t *r, gid_t *e, gid_t *s); - int getresuid(uid_t *r, uid_t *e, uid_t *s); -} -#endif -#endif -#endif // not WINDOWS - -bool rpdpriv::debug = 0; // debug switch - -//////////////////////////////////////////////////////////////////////////////// -/// Restore the 'saved' (saved = TRUE) or 'real' entity as effective. -/// Return 0 on success, < 0 (== -errno) if any error occurs. - -int rpdpriv::restore(bool saved) -{ -#if !defined(WINDOWS) - // Get the UIDs - uid_t ruid = 0, euid = 0, suid = 0; - if (getresuid(&ruid, &euid, &suid) != 0) - return RPPERR(errno); - - // Set the wanted value - uid_t uid = saved ? suid : ruid; - - // Act only if a change is needed - if (euid != uid) { - - // Set uid as effective - if (setresuid(NOUC, uid, NOUC) != 0) - return RPPERR(errno); - - // Make sure the new effective UID is the one wanted - if (geteuid() != uid) - return RPPERR(errno); - } - - // Get the GIDs - uid_t rgid = 0, egid = 0, sgid = 0; - if (getresgid(&rgid, &egid, &sgid) != 0) - return RPPERR(errno); - - // Set the wanted value - gid_t gid = saved ? sgid : rgid; - - // Act only if a change is needed - if (egid != gid) { - - // Set newuid as effective, saving the current effective GID - if (setresgid(NOGC, gid, NOGC) != 0) - return RPPERR(errno); - - // Make sure the new effective GID is the one wanted - if (getegid() != gid) - return RPPERR(errno); - } - -#endif - // Done - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Change effective to entity newuid. Current entity is saved. -/// Real entity is not touched. Use RestoreSaved to go back to -/// previous settings. -/// Return 0 on success, < 0 (== -errno) if any error occurs. - -int rpdpriv::changeto(uid_t newuid, gid_t newgid) -{ -#if !defined(WINDOWS) - // Current UGID - uid_t oeuid = geteuid(); - gid_t oegid = getegid(); - - // Restore privileges, if needed - if (oeuid && rpdpriv::restore(0) != 0) - return RPPERR(errno); - - // Act only if a change is needed - if (newgid != oegid) { - - // Set newgid as effective, saving the current effective GID - if (setresgid(NOGC, newgid, oegid) != 0) - return RPPERR(errno); - - // Get the GIDs - uid_t rgid = 0, egid = 0, sgid = 0; - if (getresgid(&rgid, &egid, &sgid) != 0) - return RPPERR(errno); - - // Make sure the new effective GID is the one wanted - if (egid != newgid) - return RPPERR(errno); - } - - // Act only if a change is needed - if (newuid != oeuid) { - - // Set newuid as effective, saving the current effective UID - if (setresuid(NOUC, newuid, oeuid) != 0) - return RPPERR(errno); - - // Get the UIDs - uid_t ruid = 0, euid = 0, suid = 0; - if (getresuid(&ruid, &euid, &suid) != 0) - return RPPERR(errno); - - // Make sure the new effective UID is the one wanted - if (euid != newuid) - return RPPERR(errno); - } - -#endif - // Done - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Change permanently to entity newuid. Requires super-userprivileges. -/// Provides a way to drop permanently su privileges. -/// Return 0 on success, < 0 (== -errno) if any error occurs. - -int rpdpriv::changeperm(uid_t newuid, gid_t newgid) -{ - // Atomic action -#if !defined(WINDOWS) - // Get UIDs - uid_t cruid = 0, ceuid = 0, csuid = 0; - if (getresuid(&cruid, &ceuid, &csuid) != 0) { - return RPPERR(errno); - } - - // Get GIDs - uid_t crgid = 0, cegid = 0, csgid = 0; - if (getresgid(&crgid, &cegid, &csgid) != 0) { - return RPPERR(errno); - } - // Restore privileges, if needed - if (ceuid && rpdpriv::restore(0) != 0) { - return RPPERR(errno); - } - // Act only if needed - if (newgid != cegid || newgid != crgid) { - - // Set newgid as GID, all levels - if (setresgid(newgid, newgid, newgid) != 0) { - return RPPERR(errno); - } - // Get GIDs - uid_t rgid = 0, egid = 0, sgid = 0; - if (getresgid(&rgid, &egid, &sgid) != 0) { - return RPPERR(errno); - } - // Make sure the new GIDs are all equal to the one asked - if (rgid != newgid || egid != newgid) { - return RPPERR(errno); - } - } - - // Act only if needed - if (newuid != ceuid || newuid != cruid) { - - // Set newuid as UID, all levels - if (setresuid(newuid, newuid, newuid) != 0) { - return RPPERR(errno); - } - // Get UIDs - uid_t ruid = 0, euid = 0, suid = 0; - if (getresuid(&ruid, &euid, &suid) != 0) { - return RPPERR(errno); - } - // Make sure the new UIDs are all equal to the one asked - if (ruid != newuid || euid != newuid) { - return RPPERR(errno); - } - } -#endif - - // Done - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Dump current entity - -void rpdpriv::dumpugid(const char *msg) -{ -#if !defined(WINDOWS) - // Get the UIDs - uid_t ruid = 0, euid = 0, suid = 0; - if (getresuid(&ruid, &euid, &suid) != 0) - return; - - // Get the GIDs - uid_t rgid = 0, egid = 0, sgid = 0; - if (getresgid(&rgid, &egid, &sgid) != 0) - return; - - cout << "rpdpriv: " << endl; - cout << "rpdpriv: dump values: " << (msg ? msg : "") << endl; - cout << "rpdpriv: " << endl; - cout << "rpdpriv: real = (" << ruid <<","<< rgid <<")" << endl; - cout << "rpdpriv: effective = (" << euid <<","<< egid <<")" << endl; - cout << "rpdpriv: saved = (" << suid <<","<< sgid <<")" << endl; - cout << "rpdpriv: " << endl; -#endif -} - -// -// Guard class -//////////////////////////////////////////////////////////////////////////////// -/// Constructor. Create a guard object for temporarly change to privileges -/// of {'uid', 'gid'} - -rpdprivguard::rpdprivguard(uid_t uid, gid_t gid) -{ - dum = 1; - valid = 0; - - init(uid, gid); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Constructor. Create a guard object for temporarly change to privileges -/// of 'usr' - -rpdprivguard::rpdprivguard(const char *usr) -{ - dum = 1; - valid = 0; - -#if !defined(WINDOWS) - if (usr && strlen(usr) > 0) { - struct passwd *pw = getpwnam(usr); - if (pw) - init(pw->pw_uid, pw->pw_gid); - } -#else - if (usr) { } -#endif -} - -//////////////////////////////////////////////////////////////////////////////// -/// Destructor. Restore state and unlock the global mutex. - -rpdprivguard::~rpdprivguard() -{ - if (!dum) { - rpdpriv::restore(); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Init a change of privileges guard. Act only if superuser. -/// The result of initialization can be tested with the Valid() method. - -void rpdprivguard::init(uid_t uid, gid_t gid) -{ - dum = 1; - valid = 1; - - // Debug hook - if (rpdpriv::debug) - rpdpriv::dumpugid("before init()"); - -#if !defined(WINDOWS) - uid_t ruid = 0, euid = 0, suid = 0; - gid_t rgid = 0, egid = 0, sgid = 0; - if (getresuid(&ruid, &euid, &suid) == 0 && - getresgid(&rgid, &egid, &sgid) == 0) { - if ((euid != uid) || (egid != gid)) { - if (!ruid) { - // Change temporarly identity - if (rpdpriv::changeto(uid, gid) != 0) - valid = 0; - dum = 0; - } else { - // Change requested but not enough privileges - valid = 0; - } - } - } else { - // Something bad happened: memory corruption? - valid = 0; - } -#endif - // Debug hook - if (rpdpriv::debug) - rpdpriv::dumpugid("after init()"); -} diff --git a/net/rpdutils/src/rpdutils.cxx b/net/rpdutils/src/rpdutils.cxx deleted file mode 100644 index 08e9a3b127bdb..0000000000000 --- a/net/rpdutils/src/rpdutils.cxx +++ /dev/null @@ -1,4633 +0,0 @@ -// @(#)root/rpdutils:$Id$ -// Author: Gerardo Ganis 7/4/2003 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// rpdutils // -// // -// Set of utilities for rootd daemon authentication. // -// // -////////////////////////////////////////////////////////////////////////// - -#include "RConfigure.h" -#include "TError.h" -#include -#include "strlcpy.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "snprintf.h" - -#if defined(__CYGWIN__) && defined(__GNUC__) -# define cygwingcc -#endif - -#if defined(__linux__) && !defined(linux) -# define linux -#endif - -#if defined(linux) || defined(__sun) || defined(__sgi) || \ - defined(_AIX) || defined(__FreeBSD__) || defined(__OpenBSD__) || \ - defined(__APPLE__) || defined(__MACH__) || defined(cygwingcc) -#include -#include -#include -#endif - -#ifdef _AIX -extern "C" int ruserok(char *, int, char *, char *); -#endif - -#if defined(__APPLE__) -#include -extern "C" int fstatfs(int file_descriptor, struct statfs *buffer); -#elif defined(linux) || defined(__hpux) -#include -#elif defined(__FreeBSD__) || defined(__OpenBSD__) -#include -#include -#else -#include -#endif - -#if defined(linux) -# include -# if __GNU_LIBRARY__ == 6 -# ifndef R__GLIBC -# define R__GLIBC -# endif -# endif -#endif -#if defined(cygwingcc) || (defined(__MACH__) && !defined(__APPLE__)) -# define R__GLIBC -#endif - -#if (defined(__FreeBSD__) && (__FreeBSD__ < 4)) || defined(__OpenBSD__) || \ - (defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_10_3) || \ - (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_3))) -#include -#define lockf(fd, op, sz) flock((fd), (op)) -#ifndef F_LOCK -#define F_LOCK (LOCK_EX | LOCK_NB) -#endif -#ifndef F_ULOCK -#define F_ULOCK LOCK_UN -#endif -#endif - -#if defined(cygwingcc) && !defined(F_LOCK) && !defined(F_ULOCK) -#define F_LOCK F_WRLCK -#define F_ULOCK F_UNLCK -int ruserok(const char *, int, const char *, const char *) { - return 0; -} -static int fcntl_lockf(int fd, int op, off_t off) -{ - flock fl; - fl.l_whence = SEEK_SET; - fl.l_start = off; - fl.l_len = 0; // whole file - fl.l_pid = getpid(); - fl.l_type = op; - return fcntl(fd, F_SETLK, &fl); -} -#define lockf fcntl_lockf -#endif - -#if defined(__sun) || defined(R__GLIBC) -#include -#endif - -#if defined(__osf__) || defined(__sgi) || defined(R__MACOSX) -extern "C" char *crypt(const char *, const char *); -#endif - -#ifdef R__WIN32 -#define R__NOCRYPT -#endif - -#ifdef R__NOCRYPT -static std::string gRndmSalt = std::string("ABCDEFGH"); -#endif - -#if defined(__sun) -#ifndef R__SHADOWPW -#define R__SHADOWPW -#endif -#endif - -#ifdef R__SHADOWPW -#include -#endif - -#ifdef R__SSL -// SSL specific headers for RSA keys -#include -#include -#include -#include -#include -#include -#include -#endif - -#include "rpdp.h" -#include "rsadef.h" -#include "rsalib.h" -// -// To improve error logging for UsrPwd on the client side -static ERootdErrors gUsrPwdErr[4][4] = { - {kErrNoPasswd, kErrNoPassHEquNoFiles, kErrNoPassHEquBadFiles, kErrNoPassHEquFailed}, - {kErrBadPasswd, kErrBadPassHEquNoFiles, kErrBadPassHEquBadFiles, kErrBadPassHEquFailed}, - {kErrBadRtag, kErrBadRtagHEquNoFiles, kErrBadRtagHEquBadFiles, kErrBadRtagHEquFailed}, - {kErrBadPwdFile, kErrBadPwdFileHEquNoFiles, kErrBadPwdFileHEquBadFiles, - kErrBadPwdFileHEquFailed}}; - -//--- Machine specific routines ------------------------------------------------ - -#if defined(__sgi) && !defined(__GNUG__) && (SGI_REL<62) -extern "C" { - int seteuid(int euid); - int setegid(int egid); -} -#endif - -#if defined(_AIX) -extern "C" { - int seteuid(uid_t euid); - int setegid(gid_t egid); -} -#endif - -#if !defined(__hpux) && !defined(linux) && !defined(__FreeBSD__) && \ - !defined(__OpenBSD__) || defined(cygwingcc) -static int setresgid(gid_t r, gid_t e, gid_t) -{ - if (setgid(r) == -1) - return -1; - return setegid(e); -} - -static int setresuid(uid_t r, uid_t e, uid_t) -{ - if (setuid(r) == -1) - return -1; - return seteuid(e); -} -#else -#if defined(linux) && !defined(R__HAS_SETRESUID) -extern "C" { - int setresgid(gid_t r, gid_t e, gid_t s); - int setresuid(uid_t r, uid_t e, uid_t s); -} -#endif -#endif - -#if defined(__sun) -#if defined(R__SUNGCC3) -extern "C" int gethostname(char *, unsigned int); -#endif -#endif - -extern int gDebug; - -namespace ROOT { - -// -// rpdutils module globals -ErrorHandler_t gErrSys = 0; -ErrorHandler_t gErrFatal = 0; -ErrorHandler_t gErr = 0; -bool gSysLog = 0; -std::string gServName[3] = { "sockd", "rootd" }; - -// -// Local global consts -static const int gAUTH_CLR_MSK = 0x1; // Masks for authentication methods -static const int gMAXTABSIZE = 50000000; - -static const std::string gAuthMeth[ROOT::Deprecated::kMAXSEC] = { "UsrPwd", "Unsupported", "Unsupported", - "Unsupported", "Unsupported", "Unsupported" }; -static const std::string gAuthTab = "/rpdauthtab"; // auth table -static const std::string gDaemonRc = ".rootdaemonrc"; // daemon access rules -static const std::string gRootdPass = ".rootdpass"; // special rootd passwd -static const std::string gKeyRoot = "/rpk."; // Root for key files - -// -// RW dir for temporary files (needed by gRpdAuthTab: do not move) -static std::string gTmpDir = "/tmp"; - -// -// Local global vars -static int gAuthProtocol = -1; // Protocol used fro a successful authentication -static char gBufOld[kMAXRECVBUF] = {0}; // msg sync for old client (<=3.05/07) -static bool gCheckHostsEquiv = 1; -static int gClientOld = 0; // msg sync for old client (<=3.05/07) -static int gClientProtocol = -1; -static int gCryptRequired = -1; -static std::string gCryptToken; -static int gAllowMeth[ROOT::Deprecated::kMAXSEC]; -static int gAnon = 0; -static int gExistingAuth = 0; -static int gAuthListSent = 0; -static int gHaveMeth[ROOT::Deprecated::kMAXSEC]; -static EMessageTypes gKindOld; // msg sync for old client (<=3.05/07) -static int gMethInit = 0; -static int gNumAllow = -1; -static int gNumLeft = -1; -static int gOffSet = -1; -static std::string gOpenHost = "????"; -static int gParentId = -1; -static char gPasswd[kMAXUSERLEN] = { 0 }; -static char gPubKey[kMAXPATHLEN] = { 0 }; -static int gPubKeyLen = 0; -static int gRandInit = 0; -static int gRemPid = -1; -static bool gRequireAuth = 1; -static int gReUseAllow = 0x1F; // define methods for which tokens can be asked -static int gReUseRequired = -1; -static int gDoLogin = 0; // perform login -static std::string gRpdAuthTab = std::string(gTmpDir).append(gAuthTab); -static std::string gRpdKeyRoot = std::string(gTmpDir).append(gKeyRoot); -static rsa_NUMBER gRSA_d; -static rsa_NUMBER gRSA_n; -static int gRSAInit = 0; -static int gRSAKey = 0; -static rsa_KEY gRSAPriKey; -static rsa_KEY_export gRSAPubExport[2] = {{0,0},{0,0}}; -static rsa_KEY gRSAPubKey; -#ifdef R__SSL -static BF_KEY gBFKey; // Session symmetric key -static RSA *gRSASSLKey = 0; // Local RSA SSL key -#endif -static int gSaltRequired = -1; -static int gSec = -1; -static int gServerProtocol = -1; -static EService gService = kROOTD; -static int gTriedMeth[ROOT::Deprecated::kMAXSEC]; -static char gUser[64] = { 0 }; -static char *gUserAllow[ROOT::Deprecated::kMAXSEC] = { 0 }; // User access control -static unsigned int gUserAlwLen[ROOT::Deprecated::kMAXSEC] = { 0 }; -static unsigned int gUserIgnLen[ROOT::Deprecated::kMAXSEC] = { 0 }; -static char *gUserIgnore[ROOT::Deprecated::kMAXSEC] = { 0 }; - -//////////////////////////////////////////////////////////////////////////////// -/// rand() implementation using /udev/random or /dev/random, if available - -static int rpd_rand() -{ -#ifndef WIN32 - int frnd = open("/dev/urandom", O_RDONLY); - if (frnd < 0) frnd = open("/dev/random", O_RDONLY); - int r; - if (frnd >= 0) { - ssize_t rs = read(frnd, (void *) &r, sizeof(int)); - close(frnd); - if (r < 0) r = -r; - if (rs == sizeof(int)) return r; - } - ErrorInfo("+++ERROR+++ : rpd_rand: neither /dev/urandom nor /dev/random are available or readable!"); - struct timeval tv; - if (gettimeofday(&tv,0) == 0) { - int t1, t2; - memcpy((void *)&t1, (void *)&tv.tv_sec, sizeof(int)); - memcpy((void *)&t2, (void *)&tv.tv_usec, sizeof(int)); - r = t1 + t2; - if (r < 0) r = -r; - return r; - } - return -1; -#else - // No special random device available: use rand() - return rand(); -#endif -} - -//////////////////////////////////////////////////////////////////////////////// -/// reads in at most one less than len characters from open -/// descriptor fd and stores them into the buffer pointed to by buf. -/// Reading stops after an EOF or a newline. If a newline is -/// read, it is stored into the buffer. -/// A '\0' is stored after the last character in the buffer. -/// The number of characters read is returned (newline included). -/// Returns < 0 in case of error. - -static int reads(int fd, char *buf, int len) -{ - int k = 0; - int nread = -1; - int nr = read(fd,buf,1); - while (nr > 0 && buf[k] != '\n' && k < (len-1)) { - k++; - nr = read(fd,buf+k,1); - } - if (k >= len-1) { - buf[k] = 0; - nread = len-1; - } else if (buf[k] == '\n'){ - if (k <= len-2) { - buf[k+1] = 0; - nread = k+1; - } else { - buf[k] = 0; - nread = k; - } - } else if (nr == 0) { - if (k > 0) { - buf[k-1] = 0; - nread = k-1; - } else { - buf[0] = 0; - nread = 0; - } - } else if (nr < 0) { - if (k > 0) { - buf[k] = 0; - nread = -(k-1); - } else { - buf[0] = 0; - nread = -1; - } - } - // Fix the lengths - if (nread >= 0) buf[nread] = 0; - - return nread; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Case insensitive string compare of n characters. - -static int rpdstrncasecmp(const char *str1, const char *str2, int n) -{ - while (n > 0) { - int c1 = *str1; - int c2 = *str2; - - if (isupper(c1)) - c1 = tolower(c1); - - if (isupper(c2)) - c2 = tolower(c2); - - if (c1 != c2) - return c1 - c2; - - str1++; - str2++; - n--; - } - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Case insensitive string compare. - -static int rpdstrcasecmp(const char *str1, const char *str2) -{ - return rpdstrncasecmp(str1, str2, strlen(str2) + 1); -} - -//////////////////////////////////////////////////////////////////////////////// -/// To avoid problems due to compiler optmization -/// Taken from Viega&Messier, "Secure Programming Cookbook", O'Really, #13.2 -/// (see discussion there) - -static volatile void *rpdmemset(volatile void *dst, int c, int len) -{ - volatile char *buf; - - for (buf = (volatile char *)dst; len;) { buf[--len] = c; } - return dst; -} - -#ifdef R__NOCRYPT -//////////////////////////////////////////////////////////////////////////////// -/// This applies simple nor encryption with sa to the first 64 bytes -/// pw. Returns the hex of the result (max length 128). -/// This is foreseen for systms where crypt is not available -/// (on windows ...), to provide some protection of tokens. - -char *rpdcrypt(const char *pw, const char *sa) -{ - static char buf[129]; - char tbuf[64]; - int np = (strlen(pw) < 64) ? strlen(pw) : 64; - int ns = strlen(sa); - char c; - - int i = 0; - for (i=0; i> 4; - if (j < 10) - c = 48 + j; - else - c = 55 + j; - k = 2*i + 1; - buf[k] = c; - } - // Null termination - buf[np*2] = 0; - - return buf; -} -#endif - -//////////////////////////////////////////////////////////////////////////////// -/// Change the value of the static gSysLog to syslog. -/// Recognized values: -/// 0 log to syslog (for root started daemons) -/// 1 log to stderr (for user started daemons) - -void RpdSetSysLogFlag(int syslog) -{ - gSysLog = syslog; - if (gDebug > 2) - ErrorInfo("RpdSetSysLogFlag: gSysLog set to %d", gSysLog); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Change the value of the static gMethInit to methinit. -/// Recognized values: -/// 0 reset -/// 1 initialized already - -void RpdSetMethInitFlag(int methinit) -{ - gMethInit = methinit; - if (gDebug > 2) - ErrorInfo("RpdSetMethInitFlag: gMethInit set to %d", gMethInit); -} - -//////////////////////////////////////////////////////////////////////////////// - -int RpdGetAuthMethod(int kind) -{ - int method = -1; - - if (kind == kROOTD_USER) - method = 0; - - return method; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Delete Public Key file -/// Returns: 0 if ok -/// 1 if error unlinking (check errno); - -int RpdDeleteKeyFile(int ofs) -{ - int retval = 0; - - std::string pukfile = gRpdKeyRoot; - pukfile.append(ItoA(ofs)); - - // Some debug info - if (gDebug > 2) { - ErrorInfo("RpdDeleteKeyFile: proc uid:%d gid:%d", - getuid(),getgid()); - } - - // Unlink - if (unlink(pukfile.c_str()) == -1) { - if (gDebug > 0 && GetErrno() != ENOENT) { - ErrorInfo("RpdDeleteKeyFile: problems unlinking pub" - " key file '%s' (errno: %d)", - pukfile.c_str(),GetErrno()); - } - retval = 1; - } - return retval; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Update tab file. -/// If ilck <= 0 open and lock the file; if ilck > 0, use file -/// descriptor ilck, which should correspond to an open and locked file. -/// If opt = -1 : delete file (backup saved in `.bak`); -/// If opt = 0 : eliminate all inactive entries -/// (if line="size" act only if size > gMAXTABSIZE) -/// if opt = 1 : append 'line'. -/// Returns -1 in case of error. -/// Returns offset for 'line' and token for opt = 1. -/// Returns new file size for opt = 0. - -int RpdUpdateAuthTab(int opt, const char *line, char **token, int ilck) -{ - int retval = -1; - int itab = 0; - char fbuf[kMAXPATHLEN]; - - if (gDebug > 2) - ErrorInfo("RpdUpdateAuthTab: analyzing: opt: %d, line: %s, ilck: %d", - opt, line, ilck); - - if (ilck <= 0) { - - // Open file for reading/ writing - itab = open(gRpdAuthTab.c_str(), O_RDWR); - if (itab == -1) { - if (opt == 1 && GetErrno() == ENOENT) { - // Try creating the file - itab = open(gRpdAuthTab.c_str(), O_RDWR | O_CREAT, 0600); - if (itab == -1) { - ErrorInfo("RpdUpdateAuthTab: opt=%d: error opening %s" - "(errno: %d)", - opt, gRpdAuthTab.c_str(), GetErrno()); - return retval; - } - } else { - ErrorInfo("RpdUpdateAuthTab: opt=%d: error opening %s" - " (errno: %d)", - opt, gRpdAuthTab.c_str(), GetErrno()); - return retval; - } - } - - // lock tab file - if (lockf(itab, F_LOCK, (off_t) 1) == -1) { - ErrorInfo("RpdUpdateAuthTab: opt=%d: error locking %s" - " (errno: %d)", opt, gRpdAuthTab.c_str(), GetErrno()); - close(itab); - return retval; - } - if (gDebug > 0) - ErrorInfo("RpdUpdateAuthTab: opt= %d - file LOCKED", opt); - } else { - itab = ilck; - } - - // File size - int fsize = 0; - if ((fsize = lseek(itab, 0, SEEK_END)) == -1) { - ErrorInfo("RpdUpdateAuthTab: opt=%d: lseek error (errno: %d)", - opt, GetErrno()); - goto goingout; - } - - // Set indicator to beginning - if (lseek(itab, 0, SEEK_SET) == -1) { - ErrorInfo("RpdUpdateAuthTab: opt=%d: lseek error (errno: %d)", - opt, GetErrno()); - goto goingout; - } - - if (opt == -1) { - - // - // Save file in .bak and delete its content - - // Open backup file - std::string bak = std::string(gRpdAuthTab).append(".bak"); - int ibak = open(bak.c_str(), O_RDWR | O_CREAT, 0600); - if (ibak == -1) { - ErrorInfo("RpdUpdateAuthTab: opt=%d: error opening/creating %s" - " (errno: %d)", opt, bak.c_str(), GetErrno()); - goto goingout; - } - - // Truncate file to new length - if (ftruncate(ibak, 0) == -1) - ErrorInfo("RpdUpdateAuthTab: opt=%d: ftruncate error (%s)" - " (errno: %d)", opt, bak.c_str(), GetErrno()); - - // Copy the content - char buf[kMAXPATHLEN]; - int ofs = 0, nr = 0; - while ((nr = reads(itab, buf, sizeof(buf)))) { - int slen = strlen(buf); - - // Make sure there is a '\n' before writing - if (buf[slen-1] != '\n') { - if (slen >= kMAXPATHLEN -1) - buf[slen-1] = '\n'; - else { - buf[slen] = '\n'; - buf[slen+1] = '\0'; - } - } - if (slen) { - while (write(ibak, buf, slen) < 0 && GetErrno() == EINTR) - ResetErrno(); - } - - // Delete Public Key file - RpdDeleteKeyFile(ofs); - // Next OffSet - ofs += slen; - } - close(ibak); - - // Truncate file to new length - if (ftruncate(itab, 0) == -1) - ErrorInfo("RpdUpdateAuthTab: opt=%d: ftruncate error (%s)" - " (errno: %d)", opt, gRpdAuthTab.c_str(), GetErrno()); - retval = 0; - - } else if (opt == 0) { - - // - // Cleanup the file (remove inactive entries) - - // Now scan over entries - int pr = 0, pw = 0; - int lsec, act = 0, oldofs = 0, bytesread = 0; - char ln[kMAXPATHLEN], dumm[kMAXPATHLEN]; - bool fwr = 0; - - while ((bytesread = reads(itab, ln, sizeof(ln)))) { - - bool ok = 1; - // Current position - if ((pr = lseek(itab,0,SEEK_CUR)) < 0) { - ErrorInfo("RpdUpdateAuthTab: opt=%d: problems lseeking file %s" - " (errno: %d)", opt, gRpdAuthTab.c_str(), errno); - fwr = 1; - ok = 0; - } - - // Check file corruption: length and number of items - int slen = bytesread; - if (ok && slen < 1) { - ErrorInfo("RpdUpdateAuthTab: opt=%d: file %s seems corrupted" - " (slen: %d)", opt, gRpdAuthTab.c_str(), slen); - fwr = 1; - ok = 0; - } - if (ok) { - // Check file corruption: number of items - int ns = sscanf(ln, "%d %d %4095s", &lsec, &act, dumm); - if (ns < 3 ) { - ErrorInfo("RpdUpdateAuthTab: opt=%d: file %s seems corrupted" - " (ns: %d)", opt, gRpdAuthTab.c_str(), ns); - fwr = 1; - ok = 0; - } - } - - if (ok && act > 0) { - if (fwr) { - // We have to update the key file name - int nr = 0; - if ((nr = RpdRenameKeyFile(oldofs,pw)) == 0) { - // Write the entry at new position - lseek(itab, pw, SEEK_SET); - - if (ln[slen-1] != '\n') { - if (slen >= kMAXPATHLEN -1) - ln[slen-1] = '\n'; - else { - ln[slen] = '\n'; - ln[slen+1] = '\0'; - } - } - while (write(itab, ln, strlen(ln)) < 0 - && GetErrno() == EINTR) - ResetErrno(); - pw += strlen(ln); - } else - RpdDeleteKeyFile(oldofs); - lseek(itab, pr, SEEK_SET); - } else - pw += strlen(ln); - } else { - fwr = 1; - } - // Set old offset - oldofs = pr; - } - - // Truncate file to new length - if (ftruncate(itab, pw) == -1) - ErrorInfo("RpdUpdateAuthTab: opt=%d: ftruncate error (errno: %d)", - opt, GetErrno()); - - // Return new file size - retval = pw; - - } else if (opt == 1) { - - // - // Add 'line' at the end - // (check size and cleanup/truncate if needed) - - // Check size ... - if ((int)(fsize+strlen(line)) > gMAXTABSIZE) { - - // If it is going to be too big, cleanup or truncate first - fsize = RpdUpdateAuthTab(0,(const char *)0,0,itab); - - // If still too big: delete everything - if ((int)(fsize+strlen(line)) > gMAXTABSIZE) - fsize = RpdUpdateAuthTab(-1,(const char *)0,0,itab); - } - // We are going to write at the end - retval = lseek(itab, 0, SEEK_END); - - // Save first RSA public key into file for later use by the - // same or other rootd; we will update the tab file - // only if this operation is successful - int ntry = 10; - int rs = 0; - while ((rs = RpdSavePubKey(gPubKey, retval, gUser)) == 2 && ntry--) { - // We are here if a file with the same name exists already - // and can not be deleted: we shift the offset with a - // dummy entry - char ltmp[256]; - SPrintf(ltmp, 256, - "0 0 %d %d %s error: pubkey file in use: shift offset\n", - gRSAKey, gRemPid, gOpenHost.c_str()); - - // adds line - while (write(itab, ltmp, strlen(ltmp)) < 0 && GetErrno() == EINTR) - ResetErrno(); - - // Set to the new end - retval = lseek(itab, 0, SEEK_END); - } - - if (rs > 0) { - // Something wrong - retval = -1; - if (gDebug > 0) - ErrorInfo("RpdUpdateAuthTab: pub key could not be saved (%d)",rs); - } else { - // Generate token - *token = RpdGetRandString(3, 8); // 8 crypt-like chars -#ifndef R__NOCRYPT - char *cryptToken = crypt(*token, *token); -#else - char *cryptToken = rpdcrypt(*token,gRndmSalt.c_str()); -#endif - SPrintf(fbuf, kMAXPATHLEN, "%s %s\n", line, cryptToken); - if (gDebug > 2) - ErrorInfo("RpdUpdateAuthTab: token: '%s'", cryptToken); - // Save it for later use in kSOCKD servers - gCryptToken = std::string(cryptToken); - - // adds line - while (write(itab, fbuf, strlen(fbuf)) < 0 && GetErrno() == EINTR) - ResetErrno(); - } - - } else { - - // - // Unknown option - ErrorInfo("RpdUpdateAuthTab: unrecognized option (opt= %d)", opt); - } - - goingout: - if (itab != ilck) { - // unlock the file - lseek(itab, 0, SEEK_SET); - if (lockf(itab, F_ULOCK, (off_t) 1) == -1) { - ErrorInfo("RpdUpdateAuthTab: error unlocking %s", - gRpdAuthTab.c_str()); - } - - // closing file ... - close(itab); - } - - return retval; -} - -//////////////////////////////////////////////////////////////////////////////// -/// De-activates entry related to token with crypt crypttoken. -/// Returns: 0 if successful -/// -4 if entry not found or inactive -/// -1 problems opening auth tab file -/// -2 problems locking auth tab file -/// -3 auth tab file does not exists - -int RpdCleanupAuthTab(const char *crypttoken) -{ - int retval = -4; - - if (gDebug > 2) - ErrorInfo("RpdCleanupAuthTab: Crypt-token: '%s'",crypttoken); - - // Open file for update - int itab = -1; - if ((itab = open(gRpdAuthTab.c_str(), O_RDWR)) == -1) { - if (GetErrno() == ENOENT) { - if (gDebug > 0) - ErrorInfo("RpdCleanupAuthTab: file %s does not exist", - gRpdAuthTab.c_str()); - return -3; - } else { - ErrorInfo("RpdCleanupAuthTab: error opening %s (errno: %d)", - gRpdAuthTab.c_str(), GetErrno()); - return -1; - } - } - - // lock tab file - if (lockf(itab, F_LOCK, (off_t) 1) == -1) { - ErrorInfo("RpdCleanupAuthTab: error locking %s (errno: %d)", - gRpdAuthTab.c_str(), GetErrno()); - close(itab); - return -2; - } - if (gDebug > 0) - ErrorInfo("RpdCleanupAuthTab: file LOCKED (ctkn: '%s')",crypttoken); - - - // Now access entry or scan over entries - int pr = 0, pw = 0; - int nw, lsec, act, remid, pkey; - char line[kMAXPATHLEN]; - - // Set indicators - if ((pr = lseek(itab, 0, SEEK_SET)) < 0) { - ErrorInfo("RpdCleanupAuthTab: error lseeking %s (errno: %d)", - gRpdAuthTab.c_str(), GetErrno()); - close(itab); - return -2; - } - pw = pr; - while (reads(itab,line, sizeof(line))) { - - pr += strlen(line); - if (gDebug > 2) - ErrorInfo("RpdCleanupAuthTab: pr:%d pw:%d (line:%s) (pId:%d)", - pr, pw, line, gParentId); - - char dum1[kMAXPATHLEN] = {0}, host[kMAXUSERLEN] = {0}, user[kMAXUSERLEN] = {0}, - ctkn[30] = {0}, dum2[30] = {0}; - nw = sscanf(line, "%d %d %d %d %127s %127s %29s %4095s %29s", - &lsec, &act, &pkey, &remid, host, user, ctkn, dum1, dum2); - - int deactivate = 0; - - if (act > 0) { - - if (lsec == 3 && nw == 9) { - if (!strncmp(dum2,crypttoken,strlen(crypttoken))) - deactivate = 1; - } else if (nw == 7) { - if (!strncmp(ctkn,crypttoken,strlen(crypttoken))) - deactivate = 1; - } - - // Deactivate active entries: remote client has gone ... - if (deactivate) { - - retval = 0; - - // Delete Public Key file - RpdDeleteKeyFile(pw); - - // Locate 'act' ... skeep initial spaces, if any - int slen = (int)strlen(line); - int ka = 0; - while (ka < slen && line[ka] == 32) - ka++; - // skeep method - while (ka < slen && line[ka] != 32) - ka++; - // skeep spaces before 'act' - while (ka < slen && line[ka] == 32) - ka++; - // This is 'act' - line[ka] = '0'; - // Make sure there is a '\n' before writing - int sl = strlen(line); - if (line[sl-1] != '\n') { - if (sl >= kMAXPATHLEN -1) - line[sl-1] = '\n'; - else { - line[sl] = '\n'; - line[sl+1] = '\0'; - } - } - // Write it now - lseek(itab, pw, SEEK_SET); - while (write(itab, line, strlen(line)) < 0 - && GetErrno() == EINTR) - ResetErrno(); - // We are done - lseek(itab, 0, SEEK_END); - } - } - pw = pr; - } - - // unlock the file - lseek(itab, 0, SEEK_SET); - if (lockf(itab, F_ULOCK, (off_t) 1) == -1) { - ErrorInfo("RpdCleanupAuthTab: error unlocking %s", gRpdAuthTab.c_str()); - } - // closing file ... - close(itab); - - return retval; -} - -//////////////////////////////////////////////////////////////////////////////// -/// In tab file, cleanup (set inactive) entry at offset -/// 'OffSet' from remote PiD 'RemId' at 'Host'. -/// If Host="all" or RemId=0 discard all entries. -/// Return number of entries not cleaned properly ... - -int RpdCleanupAuthTab(const char *Host, int RemId, int OffSet) -{ - int retval = 0; - - if (gDebug > 2) - ErrorInfo("RpdCleanupAuthTab: Host: '%s', RemId:%d, OffSet: %d", - Host, RemId, OffSet); - - // Open file for update - int itab = -1; - if ((itab = open(gRpdAuthTab.c_str(), O_RDWR)) == -1) { - if (GetErrno() == ENOENT) { - if (gDebug > 0) - ErrorInfo("RpdCleanupAuthTab: file %s does not exist", - gRpdAuthTab.c_str()); - return -3; - } else { - ErrorInfo("RpdCleanupAuthTab: error opening %s (errno: %d)", - gRpdAuthTab.c_str(), GetErrno()); - return -1; - } - } - - // lock tab file - if (lockf(itab, F_LOCK, (off_t) 1) == -1) { - ErrorInfo("RpdCleanupAuthTab: error locking %s (errno: %d)", - gRpdAuthTab.c_str(), GetErrno()); - close(itab); - // return retval; - return -2; - } - if (gDebug > 0) - ErrorInfo("RpdCleanupAuthTab: file LOCKED" - " (Host: '%s', RemId:%d, OffSet: %d)", - Host, RemId, OffSet); - - // Now access entry or scan over entries - int pr = 0, pw = 0; - int nw, lsec, act, remid, pkey; - char line[kMAXPATHLEN]; - - // Clean all flag - int all = (!strcmp(Host, "all") || RemId == 0); - - // Set indicator - if (all || OffSet < 0) - pr = lseek(itab, 0, SEEK_SET); - else - pr = lseek(itab, OffSet, SEEK_SET); - if (pr < 0) { - ErrorInfo("RpdCleanupAuthTab: error lseeking %s (errno: %d)", - gRpdAuthTab.c_str(), GetErrno()); - close(itab); - // return retval; - return -2; - } - pw = pr; - while (reads(itab,line, sizeof(line))) { - - pr += strlen(line); - if (gDebug > 2) - ErrorInfo("RpdCleanupAuthTab: pr:%d pw:%d (line:%s) (pId:%d)", - pr, pw, line, gParentId); - - char dumm[kMAXPATHLEN], host[kMAXUSERLEN], user[kMAXUSERLEN], shmbuf[30]; - nw = sscanf(line, "%d %d %d %d %127s %127s %29s %4095s", - &lsec, &act, &pkey, &remid, host, user, shmbuf, dumm); - - if (nw > 5) { - if (all || OffSet > -1 || - (strstr(line,Host) && (RemId == remid))) { - - // Delete Public Key file - RpdDeleteKeyFile(pw); - - // Deactivate active entries: remote client has gone ... - if (act > 0) { - - // Locate 'act' ... skeep initial spaces, if any - int slen = (int)strlen(line); - int ka = 0; - while (ka < slen && line[ka] == 32) - ka++; - // skeep method - while (ka < slen && line[ka] != 32) - ka++; - // skeep spaces before 'act' - while (ka < slen && line[ka] == 32) - ka++; - // This is 'act' - line[ka] = '0'; - // Make sure there is a '\n' before writing - int sl = strlen(line); - if (line[sl-1] != '\n') { - if (sl >= kMAXPATHLEN -1) - line[sl-1] = '\n'; - else { - line[sl] = '\n'; - line[sl+1] = '\0'; - } - } - // Write it now - lseek(itab, pw, SEEK_SET); - while (write(itab, line, strlen(line)) < 0 - && GetErrno() == EINTR) - ResetErrno(); - if (all || OffSet < 0) - lseek(itab, pr, SEEK_SET); - else - lseek(itab, 0, SEEK_END); - } - } - } - pw = pr; - } - - // unlock the file - lseek(itab, 0, SEEK_SET); - if (lockf(itab, F_ULOCK, (off_t) 1) == -1) { - ErrorInfo("RpdCleanupAuthTab: error unlocking %s", gRpdAuthTab.c_str()); - } - // closing file ... - close(itab); - - return retval; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check authentication entry in tab file. - -int RpdCheckAuthTab(int Sec, const char *User, const char *Host, int RemId, - int *OffSet) -{ - int retval = 0; - if (gDebug > 2) - ErrorInfo("RpdCheckAuthTab: analyzing: %d %s %s %d %d", Sec, User, - Host, RemId, *OffSet); - - // Check OffSet first - char *tkn = 0, *user =0; - int shmid; - bool goodOfs = RpdCheckOffSet(Sec,User,Host,RemId, - OffSet,&tkn,&shmid,&user); - if (gDebug > 2) - ErrorInfo("RpdCheckAuthTab: goodOfs: %d", goodOfs); - - // Notify the result of the check - int tag = 0; - if (gClientProtocol >= 10) { - if (goodOfs) { - if (gClientProtocol > 11) { - // Generate tag - RpdInitRand(); - while ((tag = rpd_rand()) == 1) ; // .ne.1 for backward comptibility - - // We will receive the user token next - NetSend(tag, kROOTD_AUTH); - } else - // We will receive the user token next - NetSend(1, kROOTD_AUTH); - } else { - // No authentication available for re-use - NetSend(0, kROOTD_AUTH); - // Cleanup and return: we need a new one ... - if (tkn) delete[] tkn; - if (user) delete[] user; - // ... no need to continue receiving the old token - return retval; - } - } - - // Now Receive Token - int ofs = *OffSet; - char *token = 0; - if (gRSAKey > 0) { - if (RpdSecureRecv(&token) == -1) { - ErrorInfo("RpdCheckAuthTab: problems secure-" - "receiving token %s", - "- may result in authentication failure "); - } - - } else { - EMessageTypes kind; - int lenToken = 9; - token = new char[lenToken]; - NetRecv(token, lenToken, kind); - if (kind != kMESS_STRING) - ErrorInfo - ("RpdCheckAuthTab: got msg kind: %d instead of %d (kMESS_STRING)", - kind, kMESS_STRING); - // Invert Token - for (int i = 0; i < (int) strlen(token); i++) { - token[i] = ~token[i]; - } - } - if (gDebug > 2) - ErrorInfo - ("RpdCheckAuthTab: received from client: token: '%s' ", - token); - - // Check tag, if there - if (token && strlen(token) > 8) { - // Create hex from tag - char tagref[9] = {0}; - SPrintf(tagref,9,"%08x",tag); - if (strncmp(token+8,tagref,8)) { - ErrorInfo("RpdCheckAuthTab: token tag does not match - failure"); - goodOfs = 0; - } else - // Drop tag - token[8] = 0; - } - - // Now check Token validity - if (goodOfs && token && RpdCheckToken(token, tkn)) { - retval = 1; - // Comunicate new offset to remote client - *OffSet = ofs; - } - - if (tkn) delete[] tkn; - if (token) delete[] token; - if (user) delete[] user; - - return retval; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check offset received from client entry in tab file. - -int RpdCheckOffSet(int Sec, const char *User, const char *Host, int RemId, - int *OffSet, char **Token, int *ShmId, char **GlbsUser) -{ - int retval = 0; - bool goodOfs = 0; - int ofs = *OffSet >= 0 ? *OffSet : 0; - - if (gDebug > 2) - ErrorInfo("RpdCheckOffSet: analyzing: %d %s %s %d %d", Sec, User, - Host, RemId, *OffSet); - - // Open file - int itab = open(gRpdAuthTab.c_str(), O_RDWR); - if (itab == -1) { - if (GetErrno() == ENOENT) - ErrorInfo("RpcCheckOffSet: file %s does not exist", - gRpdAuthTab.c_str()); - else - ErrorInfo("RpcCheckOffSet: error opening %s (errno: %d)", - gRpdAuthTab.c_str(), GetErrno()); - return retval; - } - // lock tab file - if (lockf(itab, F_LOCK, (off_t) 1) == -1) { - ErrorInfo("RpcCheckOffSet: error locking %s (errno: %d)", - gRpdAuthTab.c_str(), GetErrno()); - close(itab); - return retval; - } - if (gDebug > 0) - ErrorInfo("RpdCheckOffSet: file LOCKED"); - - // File is open: set position at wanted location - if (lseek(itab, ofs, SEEK_SET) < 0) { - ErrorInfo("RpcCheckOffSet: error lseeking %s (errno: %d)", - gRpdAuthTab.c_str(), GetErrno()); - close(itab); - return retval; - } - - // Now read the entry - char line[kMAXPATHLEN]; - if (reads(itab,line, sizeof(line)) < 0) { - ErrorInfo("RpcCheckOffSet: error reading %d bytes from %s (errno: %d)", - sizeof(line), gRpdAuthTab.c_str(), GetErrno()); - close(itab); - return retval; - } - - // and parse its content according to auth method - int lsec, act, remid, shmid = -1; - char host[kMAXPATHLEN], usr[kMAXPATHLEN], subj[kMAXPATHLEN], - dumm[kMAXPATHLEN], tkn[20]; - int nw = - sscanf(line, "%d %d %d %d %4095s %4095s %19s %4095s", - &lsec, &act, &gRSAKey, &remid, host, usr, tkn, dumm); - if (gDebug > 2) - ErrorInfo("RpdCheckOffSet: found line: %s", line); - - if (nw > 5 && act > 0) { - if (lsec == Sec) { - if (lsec == 3) { - sscanf(line, "%d %d %d %d %4095s %4095s %d %4095s %19s %4095s", - &lsec, &act, &gRSAKey, &remid, host, usr, &shmid, subj, tkn, dumm); - if ((remid == RemId) - && !strcmp(host, Host) && !strcmp(subj, User)) - goodOfs = 1; - } else { - if ((remid == RemId) && - !strcmp(host, Host) && !strcmp(usr, User)) - goodOfs = 1; - } - } - } - if (!goodOfs) { - // Tab may have been cleaned in the meantime ... try a scan - lseek(itab, 0, SEEK_SET); - ofs = 0; - while (reads(itab, line, sizeof(line))) { - - nw = sscanf(line, "%d %d %d %d %4095s %4095s %19s %4095s", - &lsec, &act, &gRSAKey, &remid, host, usr, tkn, dumm); - if (gDebug > 2) - ErrorInfo("RpdCheckOffSet: found line: %s", line); - - if (nw > 5 && act > 0) { - if (lsec == Sec) { - if (lsec == 3) { - sscanf(line, "%d %d %d %d %4095s %4095s %d %4095s %19s %4095s", - &lsec, &act, &gRSAKey, &remid, host, usr, &shmid, subj, tkn, dumm); - if ((remid == RemId) - && !strcmp(host, Host) && !strcmp(subj, User)) { - goodOfs = 1; - goto found; - } - } else { - if ((remid == RemId) && - !strcmp(host, Host) && !strcmp(usr, User)) { - goodOfs = 1; - goto found; - } - } - } - } - } - } - - found: - // unlock the file - lseek(itab, 0, SEEK_SET); - if (lockf(itab, F_ULOCK, (off_t) 1) == -1) { - ErrorInfo("RpcCheckOffSet: error unlocking %s", - gRpdAuthTab.c_str()); - } - // closing file ... - close(itab); - - // Read public key - std::string pukfile = gRpdKeyRoot; - pukfile.append(ItoA(*OffSet)); - if (gDebug > 2) - ErrorInfo("RpdCheckOffSet: RSAKey ofs file: %d %d '%s' ", - gRSAKey, ofs, pukfile.c_str()); - - struct passwd *pw = getpwnam(usr); - if (pw) { - uid_t fromUid = getuid(); - uid_t fromEUid = geteuid(); - // The check must be done with 'usr' UIDs to prevent - // unauthorized users from forcing the server to read - // manipulated key files. - if (fromUid == 0) - if (setresuid(pw->pw_uid, pw->pw_uid, fromEUid) == -1) - // Since we could not set the user IDs, we will - // not trust the client - goodOfs = 0; - - // Get the key now - if (goodOfs) - if (RpdGetRSAKeys(pukfile.c_str(), 1) < 1) - goodOfs = 0; - - // Reset original IDs - if (getuid() != fromUid) - if (setresuid(fromUid, fromEUid, pw->pw_uid) == -1) - goodOfs = 0; - - } else { - // Since we could not set the user IDs, we will - // not trust the client - goodOfs = 0; - if (gDebug > 0) - ErrorInfo("RpdCheckOffSet: error in getpwname(%s) (errno: %d)", - usr,GetErrno()); - } - - if (gDebug > 2) - ErrorInfo("RpdCheckOffSet: goodOfs: %d (active: %d)", - goodOfs, act); - - // Comunicate new offset to remote client - if (goodOfs) { - - // Rename the key file, if needed - if (*OffSet > 0 && *OffSet != ofs) { - if (RpdRenameKeyFile(*OffSet,ofs) > 0) { - goodOfs = 0; - // Error: set entry inactive - RpdCleanupAuthTab(Host,RemId,ofs); - } - } - - *OffSet = ofs; - // return token if requested - if (Token) { - const size_t tokenSize = strlen(tkn)+1; - *Token = new char[tokenSize]; - strlcpy(*Token,tkn,tokenSize); - } - if (Sec == 3) { - if (GlbsUser) { - const size_t glbsUserSize = strlen(usr)+1; - *GlbsUser = new char[glbsUserSize]; - strlcpy(*GlbsUser,usr,glbsUserSize); - } - if (ShmId) - *ShmId = shmid; - } - } - - return goodOfs; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Rename public file with new offset -/// Returns: 0 if OK -/// 1 if problems renaming - -int RpdRenameKeyFile(int oldofs, int newofs) -{ - int retval = 0; - - // Old name - std::string oldname = gRpdKeyRoot; - oldname.append(ItoA(oldofs)); - // New name - std::string newname = gRpdKeyRoot; - newname.append(ItoA(newofs)); - - if (rename(oldname.c_str(), newname.c_str()) == -1) { - if (gDebug > 0) - ErrorInfo("RpdRenameKeyFile: error renaming key file" - " %s to %s (errno: %d)", - oldname.c_str(),newname.c_str(),GetErrno()); - retval = 2; - } - - return retval; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check token validity. - -bool RpdCheckToken(char *token, char *tknref) -{ - // Get rid of '\n' - char *s = strchr(token, '\n'); - if (s) - *s = 0; - s = strchr(tknref, '\n'); - if (s) - *s = 0; - -#ifndef R__NOCRYPT - char *tkn_crypt = crypt(token, tknref); - int tlen = 13; -#else - char *tkn_crypt = rpdcrypt(token,gRndmSalt.c_str()); - int tlen = 16; -#endif - - if (gDebug > 2) - ErrorInfo("RpdCheckToken: ref:'%s' crypt:'%s'", tknref, tkn_crypt); - - if (!strncmp(tkn_crypt, tknref, tlen)) - return 1; - else - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check the requiring subject has already authenticated during this session -/// and its 'ticket' is still valid. - -int RpdReUseAuth(const char *sstr, int kind) -{ - int lenU, offset, opt; - gOffSet = -1; - gExistingAuth = 0; - int auth= 0; - - if (gDebug > 2) - ErrorInfo("RpdReUseAuth: analyzing: %s, %d", sstr, kind); - - char user[64]; - - // kClear - if (kind == kROOTD_USER) { - if (!(gReUseAllow & gAUTH_CLR_MSK)) { - return 0; // re-authentication required by administrator - } - gSec = 0; - // Decode subject string - sscanf(sstr, "%d %d %d %d %63s", &gRemPid, &offset, &opt, &lenU, user); - user[lenU] = '\0'; - if ((gReUseRequired = (opt & ROOT::Deprecated::kAUTH_REUSE_MSK))) { - gOffSet = offset; - if (gRemPid > 0 && gOffSet > -1) { - auth = - RpdCheckAuthTab(gSec, user, gOpenHost.c_str(), gRemPid, &gOffSet); - } - if ((auth == 1) && (offset != gOffSet)) - auth = 2; - // Fill gUser and free allocated memory - strlcpy(gUser, user, sizeof(gUser)); - } - } - - // Flag if existing token has been re-used - if (auth > 0) - gExistingAuth = 1; - - // Return value - return auth; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check if required auth method is allowed for 'Host'. -/// If 'yes', returns 0, if 'no', returns 1, the number of allowed -/// methods in NumAllow, and the codes of the allowed methods (in order -/// of preference) in AllowMeth. Memory for AllowMeth must be allocated -/// outside. Directives read from (in decreasing order of priority): -/// $ROOTDAEMONRC, $HOME/.rootdaemonrc (privately startd daemons only) -/// or $ROOTETCDIR/system.rootdaemonrc. - -int RpdCheckAuthAllow(int Sec, const char *Host) -{ - int retval = 1, found = 0; - - std::string theDaemonRc; - - // Check if a non-standard file has been requested - if (std::getenv("ROOTDAEMONRC")) - theDaemonRc = std::getenv("ROOTDAEMONRC"); - - if (theDaemonRc.length() <= 0) { - if (getuid()) { - // Check if user has a private daemon access file ... - struct passwd *pw = getpwuid(getuid()); - if (pw != 0) { - theDaemonRc = std::string(pw->pw_dir).append("/"); - theDaemonRc.append(gDaemonRc); - } else { - if (std::getenv("ROOTETCDIR")) { - theDaemonRc = std::string(std::getenv("ROOTETCDIR")).append("/system"); - theDaemonRc.append(gDaemonRc); - } else - theDaemonRc = std::string("/etc/root/system").append(gDaemonRc); - } - } else { - // If running as super-user, check system file only - if (std::getenv("ROOTETCDIR")) { - theDaemonRc = std::string(std::getenv("ROOTETCDIR")).append("/system"); - theDaemonRc.append(gDaemonRc); - } else - theDaemonRc = std::string("/etc/root/system").append(gDaemonRc); - } - } - if (gDebug > 2) - ErrorInfo("RpdCheckAuthAllow: Checking file: %s for meth:%d" - " host:%s (gNumAllow: %d)", - theDaemonRc.c_str(), Sec, Host, gNumAllow); - - // Check if info already loaded (not first call ...) - if (gMethInit == 1) { - - // Look for the method in the allowed list and flag this method - // as tried, if found ... - int newtry = 0, i; - for (i = 0; i < gNumAllow; i++) { - if (gTriedMeth[i] == 0 && gAllowMeth[i] == Sec) { - newtry = 1; - gTriedMeth[i] = 1; - gNumLeft--; - } - } - if (newtry == 0) { - ErrorInfo - ("RpdCheckAuthAllow: new auth method proposed by %s", - " client not in the list or already attempted"); - return retval; - } - retval = 0; - - } else { - - // Open file - FILE *ftab = fopen(theDaemonRc.c_str(), "r"); - if (ftab == 0) { - if (GetErrno() == ENOENT) - ErrorInfo("RpdCheckAuthAllow: file %s does not exist", - theDaemonRc.c_str()); - else - ErrorInfo("RpdCheckAuthAllow: error opening %s (errno: %d)", - theDaemonRc.c_str(), GetErrno()); - } - // Now read the entry - char line[kMAXPATHLEN], host[kMAXPATHLEN], rest[kMAXPATHLEN], - cmth[kMAXPATHLEN]; - int nmet = 0, mth[6] = { 0 }; - - int cont = 0, jm = -1; - while (ftab && fgets(line, sizeof(line), ftab)) { - int i; - if (line[0] == '#') - continue; // skip comment lines - if (line[strlen(line) - 1] == '\n') - line[strlen(line) - 1] = '\0'; // get rid of '\n', if any ... - // Analyze the line now ... - int nw = 0; - char *pstr = line; - // Check if a continuation line - if (cont == 1) { - cont = 0; - strlcpy(rest, pstr, kMAXPATHLEN); - } else { - jm = -1; - // Get 'host' first ... - nw = sscanf(pstr, "%4095s %4095s", host, rest); - if (nw < 2) - continue; // no method defined for this host - pstr = line + strlen(host) + 1; - - // Check if a service is specified - char *pcol = strstr(host, ":"); - if (pcol) { - if (!strstr(pcol+1, gServName[gService].c_str())) - continue; - else - host[(int)(pcol-host)] = '\0'; - } - if (!host[0]) - strlcpy(host, "default", kMAXPATHLEN); - - if (gDebug > 2) - ErrorInfo("RpdCheckAuthAllow: found host: %s ", host); - - if (strcmp(host, "default")) { - // now check validity of 'host' format - if (!RpdCheckHost(Host,host)) { - goto next; - } - } else { - // This is a default entry: ignore it if a host-specific entry was already - // found, analyse it otherwise ... - if (found == 1) - goto next; - } - - // Reset mth[kMAXSEC] - nmet = 0; - for (i = 0; i < ROOT::Deprecated::kMAXSEC; i++) { - mth[i] = -1; - } - - } - - // We are at the end and there will be a continuation line ... - if (rest[0] == '\\') { - cont = 1; - continue; - } - - while (pstr != 0) { - int tmet = -1; - char *pd = 0, *pd2 = 0; - cmth[0] = '\0'; - rest[0] = '\0'; - nw = sscanf(pstr, "%4095s %4095s", cmth, rest); - if (!strcmp(cmth, "none")) { - nmet = 0; - goto nexti; - } - pd = strchr(cmth, ':'); - // Parse the method - char tmp[20]; - if (pd != 0) { - int mlen = pd - cmth; - strncpy(tmp, cmth, mlen); - tmp[mlen] = '\0'; - } else { - strlcpy(tmp, cmth, sizeof(tmp)); - } - - if (strlen(tmp) > 1) { - - for (tmet = 0; tmet < ROOT::Deprecated::kMAXSEC; tmet++) { - if (!rpdstrcasecmp(gAuthMeth[tmet].c_str(), tmp)) - break; - } - if (tmet < ROOT::Deprecated::kMAXSEC) { - if (gDebug > 2) - ErrorInfo("RpdCheckAuthAllow: tmet %d", tmet); - } else { - if (gDebug > 1) - ErrorInfo("RpdCheckAuthAllow: unknown methods" - " %s - ignore", tmp); - goto nexti; - } - - } else { - tmet = atoi(tmp); - } - jm = -1; - if (gDebug > 2) - ErrorInfo("RpdCheckAuthAllow: found method %d (have?:%d)", - tmet, (tmet >= 0 && tmet < ROOT::Deprecated::kMAXSEC) ? gHaveMeth[tmet] : 0); - if (tmet >= 0 && tmet < ROOT::Deprecated::kMAXSEC) { - if (gHaveMeth[tmet] == 1) { - int ii; - for (ii = 0; ii < nmet; ii++) { - if (mth[ii] == tmet) { - jm = ii; - } - } - } else - goto nexti; - } else - goto nexti; - if (jm == -1) { - // New method ... - mth[nmet] = tmet; - jm = nmet; - nmet++; - } - // Now parse users list, if any ... - while (pd != 0 && (int) (pd[1]) != 32) { - pd2 = strchr(pd + 1, ':'); - if (pd[1] == '-') { - pd += 2; - // Ignore - if (gUserIgnore[mth[jm]] == 0) { - gUserIgnLen[mth[jm]] = kMAXPATHLEN; - gUserIgnore[mth[jm]] = new char[gUserIgnLen[mth[jm]]]; - gUserIgnore[mth[jm]][0] = '\0'; - } - if (strlen(gUserIgnore[mth[jm]]) > - (gUserIgnLen[mth[jm]] - 10)) { - char *tmpUI = strdup(gUserIgnore[mth[jm]]); - free(gUserIgnore[mth[jm]]); - gUserIgnLen[mth[jm]] += kMAXPATHLEN; - gUserIgnore[mth[jm]] = new char[gUserIgnLen[mth[jm]]]; - strlcpy(gUserIgnore[mth[jm]], tmpUI, sizeof(gUserIgnLen[mth[jm]])); - free(tmpUI); - } - char usr[256]; - if (pd2 != 0) { - int ulen = pd2 - pd; - strncpy(usr, pd, ulen); - usr[ulen] = '\0'; - } else { - strlcpy(usr, pd, sizeof(usr)); - } - struct passwd *pw = getpwnam(usr); - if (pw != 0) - SPrintf(gUserIgnore[mth[jm]], gUserIgnLen[mth[jm]], "%s %d", - gUserIgnore[mth[jm]], (int)pw->pw_uid); - } else { - pd += 1; - if (pd[1] == '+') - pd += 1; - // Keep - if (gUserAllow[mth[jm]] == 0) { - gUserAlwLen[mth[jm]] = kMAXPATHLEN; - gUserAllow[mth[jm]] = new char[gUserAlwLen[mth[jm]]]; - gUserAllow[mth[jm]][0] = '\0'; - } - if (strlen(gUserAllow[mth[jm]]) > - (gUserAlwLen[mth[jm]] - 10)) { - char *tmpUI = strdup(gUserAllow[mth[jm]]); - free(gUserAllow[mth[jm]]); - gUserAlwLen[mth[jm]] += kMAXPATHLEN; - gUserAllow[mth[jm]] = new char[gUserAlwLen[mth[jm]]]; - strlcpy(gUserAllow[mth[jm]], tmpUI, sizeof(gUserAlwLen[mth[jm]])); - free(tmpUI); - } - char usr[256]; - if (pd2 != 0) { - int ulen = pd2 - pd; - strncpy(usr, pd, ulen); - usr[ulen] = '\0'; - } else { - strlcpy(usr, pd, sizeof(usr)); - } - struct passwd *pw = getpwnam(usr); - if (pw != 0) - SPrintf(gUserAllow[mth[jm]], gUserAlwLen[mth[jm]], "%s %d", - gUserAllow[mth[jm]], (int)pw->pw_uid); - } - pd = pd2; - } - // Get next item - nexti: - if (nw > 1 && (int) rest[0] != 92) { - pstr = strstr(pstr, rest); - } else { - if ((int) rest[0] == 92) - cont = 1; - pstr = 0; - } - } - if (gDebug > 2) { - ErrorInfo("RpdCheckAuthAllow: for host %s found %d methods", - host, nmet); - ErrorInfo("RpdCheckAuthAllow: %d %d %d %d %d %d", mth[0], - mth[1], mth[2], mth[3], mth[4], mth[5]); - } - // Found new entry matching: superseed previous result - found = 1; - retval = 1; - gNumAllow = gNumLeft = nmet; - for (i = 0; i < ROOT::Deprecated::kMAXSEC; i++) { - gAllowMeth[i] = -1; - gTriedMeth[i] = 0; - if (i < gNumAllow) { - gAllowMeth[i] = mth[i]; - if (Sec == mth[i]) { - retval = 0; - gNumLeft--; - gTriedMeth[i] = 1; - } - } - } - next: - continue; - } - - // closing file ... - if (ftab) - fclose(ftab); - - // Host specific directives have been checked for ... - gMethInit = 1; - - // Use defaults if nothing found - if (!found) { - if (gDebug > 2) - ErrorInfo - ("RpdCheckAuthAllow: no specific or 'default' entry found: %s", - "using system defaults"); - int i; - for (i = 0; i < gNumAllow; i++) { - if (Sec == gAllowMeth[i]) { - retval = 0; - gNumLeft--; - gTriedMeth[i] = 1; - } - } - - } - - } - if (gDebug > 2) { - ErrorInfo - ("RpdCheckAuthAllow: returning: %d (gNumAllow: %d, gNumLeft:%d)", - retval, gNumAllow, gNumLeft); - int i, jm; - for (i = 0; i < ROOT::Deprecated::kMAXSEC; i++) { - jm = gAllowMeth[i]; - if (gUserAlwLen[jm] > 0) - ErrorInfo("RpdCheckAuthAllow: users allowed for method %d: %s", - jm, gUserAllow[jm]); - } - for (i = 0; i < ROOT::Deprecated::kMAXSEC; i++) { - jm = gAllowMeth[i]; - if (gUserIgnLen[jm] > 0) - ErrorInfo("RpdCheckAuthAllow: users ignored for method %d: %s", - jm, gUserIgnore[jm]); - } - } - - return retval; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Checks if 'host' is compatible with 'Host' taking into account -/// wild cards in the host name -/// Returns 1 if successful, 0 otherwise ... - -int RpdCheckHost(const char *Host, const char *host) -{ - int rc = 1; - - // Strings must be both defined - if (!Host || !host) - return 0; - - // If host is a just wild card accept it - if (!strcmp(host,"*")) - return 1; - - // Try now to understand whether it is an address or a name ... - int name = 0, i = 0; - for (i = 0; i < (int) strlen(host); i++) { - if ((host[i] < 48 || host[i] > 57) && - host[i] != '*' && host[i] != '.') { - name = 1; - break; - } - } - - // If ref host is an IP, get IP of Host - char *hh; - if (!name) { - hh = RpdGetIP(Host); - if (gDebug > 2) - ErrorInfo("RpdCheckHost: Checking Host IP: %s", hh); - } else { - const size_t hhSize = strlen(Host)+1; - hh = new char[hhSize]; - strlcpy(hh,Host,hhSize); - if (gDebug > 2) - ErrorInfo("RpdCheckHost: Checking Host name: %s", hh); - } - - // Check if starts with wild - // Starting with '.' defines a full (sub)domain - int sos = 0; - if (host[0] == '*' || host[0] == '.') - sos = 1; - - // Check if ends with wild - // Ending with '.' defines a name - int eos = 0, le = strlen(host); - if (host[le-1] == '*' || host[le-1] == '.') - eos = 1; - - int first= 1; - int ends= 0; - int starts= 0; - const size_t hSize = strlen(host)+1; - char *h = new char[hSize]; - strlcpy(h,host,hSize); - char *tk = strtok(h,"*"); - while (tk) { - - char *ps = strstr(hh,tk); - if (!ps) { - rc = 0; - break; - } - if (!sos && first && ps == hh) - starts = 1; - first = 0; - - if (ps == hh + strlen(hh) - strlen(tk)) - ends = 1; - - tk = strtok(0,"*"); - - } - delete[] h; - delete[] hh; - - if ((!sos || !eos) && !starts && !ends) - rc = 0; - - return rc; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Get IP address of 'host' as a string. String must be deleted by -/// the user. - -char *RpdGetIP(const char *host) -{ - struct hostent *h; - unsigned long ip; - unsigned char ip_fld[4]; - - // Check server name - if ((h = gethostbyname(host)) == 0) { - ErrorInfo("RpdGetIP: unknown host %s", host); - return 0; - } - // Decode ... - ip = ntohl(*(unsigned long *) h->h_addr_list[0]); - ip_fld[0] = (unsigned char) ((0xFF000000 & ip) >> 24); - ip_fld[1] = (unsigned char) ((0x00FF0000 & ip) >> 16); - ip_fld[2] = (unsigned char) ((0x0000FF00 & ip) >> 8); - ip_fld[3] = (unsigned char) ((0x000000FF & ip)); - - // Prepare output - char *output = new char[20]; - SPrintf(output, 20, "%d.%d.%d.%d", - ip_fld[0], ip_fld[1], ip_fld[2], ip_fld[3]); - - // return - return output; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Send list of authentication methods not yet tried. - -void RpdSendAuthList() -{ - if (gDebug > 2) - ErrorInfo("RpdSendAuthList: analyzing (gNumLeft: %d)", gNumLeft); - - // Send Number of methods left - NetSend(gNumLeft, kROOTD_NEGOTIA); - - if (gNumLeft > 0) { - int i = 0; - std::string alist; - char cm[5]; - for (i = 0; i < gNumAllow; i++) { - if (gDebug > 2) - ErrorInfo("RpdSendAuthList: gTriedMeth[%d]: %d", i, - gTriedMeth[i]); - if (gTriedMeth[i] == 0) { - SPrintf(cm, 5, " %d",gAllowMeth[i]); - alist.append(cm); - } - } - NetSend(alist.c_str(), alist.length() + 1, kMESS_STRING); - if (gDebug > 2) - ErrorInfo("RpdSendAuthList: sent list: %s", alist.c_str()); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Authenticate via Kerberos. - -int RpdKrb5Auth(const char *) -{ - ::Error("RpdKrb5Auth", "Kerberos5 no longer supported by ROOT"); - return 1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Secure Remote Password protocol (no longer supported) - -int RpdSRPUser(const char *) -{ - ::Error("RpdSRPUser", "SRP no longer supported by ROOT"); - return 1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check if the requesting {host,user} can be granted immediate -/// login on the base of the information found in /etc/hosts.equiv -/// and/or $HOME/.rhosts. The two files must be trustable, i.e. owned -/// and modifiable only by 'root' and by 'user', respectively (0600). -/// Returns 1 in case access can be granted, 0 in any other case -/// (errout contains a code for error logging on the client side) -/// -/// NB: entries granting access in one of the two files cannot be -/// overriden in the other file; so, system admins cannot close -/// access from a host and user cannot stop access to their -/// account if the administrator has decided so; as an example, -/// if this entry is found in /etc/hosts.equiv -/// -/// remote.host.dom auser -/// -/// (allowing user named 'auser' from host 'remote.host.dom' to -/// login to any non-root local account without specifying a -/// password) the following entries in $home/.rhosts are ignored -/// -/// remote.host.dom -auser -/// -remote.host.dom -/// -/// and access to 'auser' is always granted. This is a "feature" -/// of ruserok. -/// - -int RpdCheckHostsEquiv(const char *host, const char *ruser, - const char *user, int &errout) -{ - int rc = 0; - - // Effective uid - int rootuser = 0; - if (!geteuid() && !getegid()) - rootuser = 1; - - // Check the files only if i) at least one exists; ii) those existing - // have the right permission settings - bool badfiles = 0; - int nfiles = 0; - - // Check system file /etc/hosts.equiv if non-root - char hostsequiv[20] = { "/etc/hosts.equiv" }; - if (!rootuser) { - - // Get info about the file ... - struct stat st; - if (stat(hostsequiv,&st) == -1) { - if (GetErrno() != ENOENT) { - ErrorInfo("RpdCheckHostsEquiv: cannot stat /etc/hosts.equiv" - " (errno: %d)",GetErrno()); - badfiles = 1; - } else - if (gDebug > 1) - ErrorInfo("RpdCheckHostsEquiv: %s does not exist", - hostsequiv); - } else { - - // Require 'root' ownership - if (st.st_uid || st.st_gid) { - if (gDebug > 0) - ErrorInfo("RpdCheckHostsEquiv: /etc/hosts.equiv not owned by" - " system (uid: %d, gid: %d)",st.st_uid,st.st_gid); - badfiles = 1; - } else { - - // Require WRITE permission only for owner - if ((st.st_mode & S_IWGRP) || (st.st_mode & S_IWOTH)) { - if (gDebug > 0) - ErrorInfo("RpdCheckHostsEquiv: group or others have write" - " permission on /etc/hosts.equiv: do not trust" - " it (g: %d, o: %d)", - (st.st_mode & S_IWGRP),(st.st_mode & S_IWOTH)); - badfiles = 1; - } else - // Good file - nfiles++; - } - } - } - - // Check local file - char rhosts[kMAXPATHLEN] = {0}; - if (!badfiles) { - - struct passwd *pw = getpwnam(user); - if (pw) { - int ldir = strlen(pw->pw_dir); - ldir = (ldir > kMAXPATHLEN - 9) ? (kMAXPATHLEN - 9) : ldir; - memcpy(rhosts,pw->pw_dir,ldir); - memcpy(rhosts+ldir,"/.rhosts",8); - rhosts[ldir+8] = 0; - if (gDebug > 2) - ErrorInfo("RpdCheckHostsEquiv: checking for user file %s ...",rhosts); - } else { - if (gDebug > 0) - ErrorInfo("RpdCheckHostsEquiv: cannot get user info with getpwnam" - " (errno: %d)",GetErrno()); - badfiles = 1; - } - - if (!badfiles) { - // Check the $HOME/.rhosts file ... ownership and protections - struct stat st; - if (stat(rhosts,&st) == -1) { - if (GetErrno() != ENOENT) { - ErrorInfo("RpdCheckHostsEquiv: cannot stat $HOME/.rhosts" - " (errno: %d)",GetErrno()); - badfiles = 1; - } else - ErrorInfo("RpdCheckHostsEquiv: %s/.rhosts does not exist", - pw->pw_dir); - } else { - - // Only use file when its access rights are 0600 - if (!S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) || - (st.st_mode & 0777) != (S_IRUSR | S_IWUSR)) { - if (gDebug > 0) - ErrorInfo("RpdCheckHostsEquiv: unsecure permission setting" - " found for $HOME/.rhosts: 0%o (must be 0600)", - (st.st_mode & 0777)); - badfiles = 1; - } else - // Good file - nfiles++; - } - } - } - - // if files are not available or have wrong permissions or are - // not accessible, give up - if (!nfiles) { - if (gDebug > 0) - ErrorInfo("RpdCheckHostsEquiv: no files to check"); - errout = 1; - if (badfiles) { - if (gDebug > 0) - ErrorInfo("RpdCheckHostsEquiv: config files cannot be used" - " (check permissions)"); - errout = 2; - } - return rc; - } - - // Ok, now use ruserok to find out if {host,ruser,user} - // is trusted -#if defined(__sgi) || defined(_AIX) - if (ruserok((char*)host,rootuser,(char*)ruser,(char*)user) == 0) { -#else - if (ruserok(host,rootuser,ruser,user) == 0) { -#endif - if (gDebug > 0) - ErrorInfo("RpdCheckHostsEquiv: remote user %s authorized to" - " access %s's area",ruser,user); - rc = 1; - } else { - if (gDebug > 0) - ErrorInfo("RpdCheckHostsEquiv: no special permission from" - " %s or %s",hostsequiv,rhosts); - errout = 3; - } - - return rc; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check received user's password against password in $HOME/.rootdpass. -/// The password is retrieved in RpdUser and temporarly saved in gPasswd. -/// Returns 1 in case of success authentication, 0 otherwise. - -int RpdCheckSpecialPass(const char *passwd) -{ - // Check inputs - if (!passwd) - return 0; - - // and the saved the password - if (strlen(gPasswd) <= 0) - return 0; - - // Ok, point to the saved passwd (retrieved in RpdUser) - char *rootdpass = gPasswd; - int n = 0; - - if (gClientProtocol > 8 && gSaltRequired > 0) { - n = strlen(rootdpass); - if (strncmp(passwd, rootdpass, n + 1) != 0) { - if (gDebug > 0) - ErrorInfo("RpdCheckSpecialPass: wrong password"); - rpdmemset((volatile void *)rootdpass,0,n); - return 0; - } - } else { -#ifndef R__NOCRYPT - char *pass_crypt = crypt(passwd, rootdpass); -#else - char *pass_crypt = (char *)passwd; -#endif - n = strlen(rootdpass); - if (strncmp(pass_crypt, rootdpass, n+1) != 0) { - if (gDebug > 0) - ErrorInfo("RpdCheckSpecialPass: wrong password"); - rpdmemset((volatile void *)rootdpass,0,n); - return 0; - } - } - - if (gDebug > 0) - ErrorInfo - ("RpdCheckSpecialPass: user %s authenticated via ~/.rootdpass", - gUser); - - rpdmemset((volatile void *)rootdpass,0,n); - return 1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check user's password. - -int RpdPass(const char *pass, int errheq) -{ - char passwd[128]; - char *passw; - char *pass_crypt; - struct passwd *pw; -#ifdef R__SHADOWPW - struct spwd *spw; -#endif - int afs_auth = 0; - - if (gDebug > 2) - ErrorInfo("RpdPass: Enter (pass length: %d)", (int)strlen(pass)); - - int auth = 0; - errheq = (errheq > -1 && errheq < 4) ? errheq : 0; - if (!*gUser) { - if (gClientProtocol > 11) - NetSend(gUsrPwdErr[0][errheq], kROOTD_ERR); - else - NetSend(kErrFatal, kROOTD_ERR); - if (gDebug > 0) - ErrorInfo("RpdPass: user needs to be specified first"); - return auth; - } - - if (!pass) { - if (gClientProtocol > 11) - NetSend(gUsrPwdErr[1][errheq], kROOTD_ERR); - else - NetSend(kErrNoPasswd, kROOTD_ERR); - if (gDebug > 0) - ErrorInfo("RpdPass: no password specified"); - return auth; - } - int n = strlen(pass); - // Passwd length should be in the correct range ... - if (!n) { - if (gClientProtocol > 11) - NetSend(gUsrPwdErr[1][errheq], kROOTD_ERR); - else - NetSend(kErrBadPasswd, kROOTD_ERR); - if (gDebug > 0) - ErrorInfo("RpdPass: null passwd not allowed"); - return auth; - } - if (n > (int) sizeof(passwd)) { - if (gClientProtocol > 11) - NetSend(gUsrPwdErr[1][errheq], kROOTD_ERR); - else - NetSend(kErrBadPasswd, kROOTD_ERR); - if (gDebug > 0) - ErrorInfo("RpdPass: passwd too long"); - return auth; - } - // Inversion is done in RpdUser, if needed - strlcpy(passwd, pass, sizeof(passwd)); - - // Special treatment for anonimous ... - if (gAnon) { - strlcpy(gPasswd, passwd, sizeof(gPasswd)); - goto authok; - } - // ... and SpecialPass ... - if (RpdCheckSpecialPass(passwd)) { - goto authok; - } - // Get local passwd info for gUser - if (!(pw = getpwnam(gUser))) { - ErrorInfo("RpdPass: getpwnam failed!"); - return auth; - } - -#ifdef R__SHADOWPW - // System V Rel 4 style shadow passwords - if ((spw = getspnam(gUser)) == 0) { - if (gDebug > 0) - ErrorInfo("RpdPass: Shadow passwd not available for user %s", - gUser); - passw = pw->pw_passwd; - } else - passw = spw->sp_pwdp; -#else - passw = pw->pw_passwd; -#endif -#ifndef R__NOCRYPT - if (gClientProtocol <= 8 || !gSaltRequired) { - char salt[20] = {0}; - int lenS = 2; - if (!strncmp(passw, "$1$", 3)) { - // Shadow passwd - char *pd = strstr(passw + 4, "$"); - lenS = (int) (pd - passw); - strncpy(salt, passw, lenS); - } else - strncpy(salt, passw, lenS); - salt[lenS] = 0; - pass_crypt = crypt(passwd, salt); // Comment this - } else { - pass_crypt = passwd; - } -#else - pass_crypt = passwd; -#endif - n = strlen(passw); - if (strncmp(pass_crypt, passw, n + 1) != 0) { - if (gClientProtocol > 11) - NetSend(gUsrPwdErr[1][errheq], kROOTD_ERR); - else - NetSend(kErrBadPasswd, kROOTD_ERR); - if (gDebug > 0) - ErrorInfo("RpdPass: invalid password for user %s", gUser); - return auth; - } - if (gDebug > 2) - ErrorInfo("RpdPass: valid password for user %s", gUser); - - authok: - auth = afs_auth ? 5 : 1; - gSec = 0; - - if (gClientProtocol > 8) { - // Set an entry in the auth tab file for later (re)use, if required ... - int offset = -1; - char *token = 0; - char line[kMAXPATHLEN]; - if ((gReUseAllow & gAUTH_CLR_MSK) && gReUseRequired) { - - SPrintf(line, kMAXPATHLEN, "0 1 %d %d %s %s", - gRSAKey, gRemPid, gOpenHost.c_str(), gUser); - if (!afs_auth) - offset = RpdUpdateAuthTab(1, line, &token); - if (gDebug > 2) - ErrorInfo("RpdPass: got offset %d", offset); - - // Comunicate login user name to client - SPrintf(line, kMAXPATHLEN, "%s %d", gUser, offset); - if (gDebug > 2) - ErrorInfo("RpdPass: sending back line %s", line); - NetSend(strlen(line), kROOTD_PASS); // Send message length first - NetSend(line, kMESS_STRING); - - if (offset > -1) { - if (gDebug > 2) - ErrorInfo("RpdPass: sending token %s (Crypt: %d)", token, - gCryptRequired); - if (gCryptRequired) { - // Send over the token - if (RpdSecureSend(token) == -1) { - if (gDebug > 0) - ErrorInfo("RpdPass: problems secure-sending token" - " - may result in corrupted token"); - } - } else { - // Send token inverted - for (int i = 0; i < (int) strlen(token); i++) { - token[i] = ~token[i]; - } - NetSend(token, kMESS_STRING); - } - delete[] token; - } - gOffSet = offset; - - } else { - // Comunicate login user name to client - SPrintf(line, kMAXPATHLEN, "%s -1", gUser); - if (gDebug > 2) - ErrorInfo("RpdPass: sending back line %s", line); - NetSend(strlen(line), kROOTD_PASS); // Send message length first - NetSend(line, kMESS_STRING); - } - } - - return auth; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Prepare for globus authentication: check hostcer.conf and get -/// the credential handle. This is run once at daemon start-up - -int RpdGlobusInit() -{ - ::Error("RpdGlobusInit", "Globus is no longer supported by ROOT"); - return 1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Authenticate via Globus. - -int RpdGlobusAuth(const char *) -{ - ::Error("RpdGlobusInit", "Globus is no longer supported by ROOT"); - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// RFIO protocol (no longer supported by ROOT) - -int RpdRfioAuth(const char *) -{ - ::Error("RpdRfioAuth", "RfioAuth no longer supported by ROOT"); - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Terminate correctly by cleaning up the auth table and closing the file. -/// Called upon receipt of a kROOTD_CLEANUP and on SIGPIPE. - -void RpdAuthCleanup(const char *sstr, int opt) -{ - int rpid = 0, sec = -1, offs = -1, nw = 0; - char usr[64] = {0}; - if (sstr) - nw = sscanf(sstr, "%d %d %d %63s", &rpid, &sec, &offs, usr); - - // Turn back to superuser for cleaning, if the case - if (getuid() == 0) { - if (setresgid(0, 0, 0) == -1) - if (gDebug > 0) - ErrorInfo("RpdAuthCleanup: can't setgid to superuser"); - if (setresuid(0, 0, 0) == -1) - if (gDebug > 0) - ErrorInfo("RpdAuthCleanup: can't setuid to superuser"); - } - if (opt == 0) { - RpdCleanupAuthTab("all", 0, -1); // Cleanup everything (SIGPIPE) - ErrorInfo("RpdAuthCleanup: cleanup ('all',0) done"); - } else if (opt == 1) { - if (nw == 1) { - // host specific cleanup - RpdCleanupAuthTab(gOpenHost.c_str(), rpid, -1); - ErrorInfo("RpdAuthCleanup: cleanup ('%s',%d) done", - gOpenHost.c_str(), rpid); - } else if (nw == 4) { - // (host,usr,method) specific cleanup - if (RpdCheckOffSet(sec,usr,gOpenHost.c_str(),rpid,&offs,0,0,0)) { - RpdCleanupAuthTab(gOpenHost.c_str(), rpid, offs); - ErrorInfo("RpdAuthCleanup: cleanup (%s,%d,%d,%d,%s) done", - gOpenHost.c_str(), rpid, sec, offs, usr); - } else { - ErrorInfo("RpdAuthCleanup: cleanup not done: %s", - "wrong offset or already cleaned up"); - } - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -void RpdInitAuth() -{ - // Size check done in RpdUpdateAuthTab(1,...) - - // Reset - int i; - gNumAllow = gNumLeft = 0; - for (i = 0; i < ROOT::Deprecated::kMAXSEC; i++) { - gAllowMeth[i] = -1; - gHaveMeth[i] = 1; - } - - // List of default authentication methods - RpdDefaultAuthAllow(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check configuration options and running daemons to build a default list -/// of secure methods. - -void RpdDefaultAuthAllow() -{ - if (gDebug > 2) - ErrorInfo("RpdDefaultAuthAllow: Enter"); - - // UsrPwdClear - gAllowMeth[gNumAllow] = 0; - gNumAllow++; - gNumLeft++; - - // No SRP method - gHaveMeth[1] = 0; - - // No Kerberos method - gHaveMeth[2] = 0; - - // No Globus method - gHaveMeth[3] = 0; - - if (gDebug > 2) { - int i; - std::string temp; - char cm[5]; - if (gNumAllow == 0) - temp.append("none"); - for (i = 0; i < gNumAllow; i++) { - SPrintf(cm, 5, " %3d",gAllowMeth[i]); - temp.append(cm); - } - ErrorInfo - ("RpdDefaultAuthAllow: default list of secure methods available: %s", - temp.c_str()); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check the running of process 'daemon'. -/// Info got from 'ps ax'. - -int RpdCheckDaemon(const char *daemon) -{ - char cmd[kMAXPATHLEN] = { 0 }; - int ch, i = 0, cnt = 0; - - if (gDebug > 2) - ErrorInfo("RpdCheckDaemon: Enter ... %s", daemon); - - // Return if empty - if (daemon == 0 || !daemon[0]) - return cnt; - - // Build command - SPrintf(cmd, kMAXPATHLEN, "ps ax | grep %s 2>/dev/null", daemon); - - // Run it ... - FILE *fp = popen(cmd, "r"); - if (fp != 0) { - for (ch = fgetc(fp); ch != EOF; ch = fgetc(fp)) { - if (ch != 10) { - cmd[i++] = ch; - } else { - cmd[i] = '\0'; - if (strstr(cmd, "grep") == 0 && strstr(cmd, "rootd") == 0) { - cnt++; - } - i = 0; - } - } - if (i > 0) { - cmd[i] = '\0'; - cnt++; - } - pclose(fp); - if (gDebug > 2) - ErrorInfo("RpdCheckDaemon: found %d instances of daemon %s", - cnt, daemon); - - } else { - ErrorInfo("RpdCheckDaemon: problems executing cmd ..."); - } - return cnt; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check user id. If user id is not equal to rootd's effective uid, user -/// will not be allowed access, unless effective uid = 0 (i.e. root). - -int RpdUser(const char *sstr) -{ - const int kMaxBuf = 256; - char recvbuf[kMaxBuf]; - EMessageTypes kind; - struct passwd *pw; - if (gDebug > 2) - ErrorInfo("RpdUser: Enter ... %s", sstr); - - int auth = 0; - - // Nothing can be done if empty message - if (!*sstr) { - NetSend(kErrBadUser, kROOTD_ERR); - ErrorInfo("RpdUser: received empty string"); - return auth; - } - // Parse input message - char user[kMAXUSERLEN] = {0}; - char ruser[kMAXUSERLEN] = {0}; - if (gClientProtocol > 8) { - int ulen, ofs, opt, rulen; - // Decode subject string - int nw = sscanf(sstr, "%d %d %d %d %63s %d %63s", - &gRemPid, &ofs, &opt, &ulen, user, &rulen, ruser); - ulen = (ulen >= kMAXUSERLEN) ? kMAXUSERLEN-1 : ulen; - rulen = (rulen >= kMAXUSERLEN) ? kMAXUSERLEN-1 : rulen; - user[ulen] = '\0'; - if (nw > 5) - ruser[rulen] = '\0'; - gReUseRequired = (opt & ROOT::Deprecated::kAUTH_REUSE_MSK); - gCryptRequired = (opt & ROOT::Deprecated::kAUTH_CRYPT_MSK); - gSaltRequired = (opt & ROOT::Deprecated::kAUTH_SSALT_MSK); - gOffSet = ofs; -#ifdef R__SSL - if (gRSASSLKey) { - // Determine type of RSA key required - gRSAKey = (opt & kAUTH_RSATY_MSK) ? 2 : 1; - } else - gRSAKey = 1; -#else - gRSAKey = 1; -#endif - } else { - SPrintf(user,kMAXUSERLEN,"%s",sstr); - } - if (gDebug > 2) - ErrorInfo("RpdUser: gReUseRequired: %d gCryptRequired: %d gRSAKey: %d", - gReUseRequired, gCryptRequired, gRSAKey); - - ERootdErrors err = kErrNoUser; - if (gService == kROOTD) { - // Default anonymous account ... - if (!strcmp(user, "anonymous")) { - user[0] = '\0'; - strlcpy(user, "rootd", sizeof(user)); - } - } - - if ((pw = getpwnam(user)) == 0) { - NetSend(err, kROOTD_ERR); - ErrorInfo("RpdUser: user %s unknown", user); - return auth; - } - - // If server is not started as root and user is not same as the - // one who started rootd then authetication is not ok. - uid_t uid = getuid(); - if (uid && uid != pw->pw_uid) { - NetSend(kErrBadUser, kROOTD_ERR); - ErrorInfo("RpdUser: user not same as effective user of rootd"); - return auth; - } - - // Check if the administrator allows authentication - char cuid[20]; - SPrintf(cuid, 20, "%d", (int)pw->pw_uid); - if (gUserIgnLen[0] > 0 && strstr(gUserIgnore[0], cuid) != 0) { - NetSend(kErrNotAllowed, kROOTD_ERR); - ErrorInfo - ("RpdUser: user (%d,%s) not authorized to use UsrPwd method", - uid, pw->pw_name); - return auth; - } - if (gUserAlwLen[0] > 0 && strstr(gUserAllow[0], cuid) == 0) { - NetSend(kErrNotAllowed, kROOTD_ERR); - ErrorInfo - ("RpdUser: user (%d,%s) not authorized to use UsrPwd method", - uid, pw->pw_name); - return auth; - } - - // Check /etc/hosts.equiv and/or $HOME/.rhosts - int errheq = 0; - if (gCheckHostsEquiv && strlen(ruser)) { - if (RpdCheckHostsEquiv(gOpenHost.c_str(),ruser,user,errheq)) { - auth = 3; - strlcpy(gUser, user, sizeof(gUser)); - return auth; - } - } - - // Check if of type anonymous ... - if (!strcmp(pw->pw_shell, "/bin/false")) { - err = kErrNoAnon; - gAnon = 1; - gReUseRequired = 0; - } - - // Check if authorized - // If not anonymous, try to get passwd - // (if our system uses shadow passwds and we are not superuser - // we cannot authenticate users ...) - // char *passw = 0; - gPasswd[0] = 0; - char *passw = gPasswd; - int errrdp = 0; - if (gAnon == 0) { - - // Check ROOT specific passwd first - int rcsp = RpdRetrieveSpecialPass(user,gRootdPass.c_str(), - gPasswd,sizeof(gPasswd)); - if (rcsp < 0) - errrdp = (rcsp == -2) ? 3 : 0; - - if (!passw[0] || !strcmp(passw, "x")) { - -#ifdef R__SHADOWPW - struct spwd *spw = 0; - // System V Rel 4 style shadow passwords - if ((spw = getspnam(user)) == 0) { - if (gDebug > 0) { - ErrorInfo("RpdUser: Shadow passwd not accessible for user %s",user); - ErrorInfo("RpdUser: trying normal system passwd"); - } - } else - passw = spw->sp_pwdp; -#else - passw = pw->pw_passwd; -#endif - // Check if successful - if (!passw[0] || !strcmp(passw, "x")) { - if (gClientProtocol > 11) - NetSend(gUsrPwdErr[errrdp][errheq], kROOTD_ERR); - else - NetSend(kErrNotAllowed, kROOTD_ERR); - ErrorInfo("RpdUser: passwd hash not available for user %s", user); - ErrorInfo - ("RpdUser: user %s cannot be authenticated with this method", - user); - return auth; - } - } - } - // Ok: Save username and go to next steps - strlcpy(gUser, user, sizeof(gUser)); - - // Salt vars - char salt[30] = { 0 }; - char ctag[11] = { 0 }; - int rtag = 0; - int lenS = 0; - - if (gClientProtocol > 8) { - - // Prepare status flag to send back - if (gAnon == 1) { - // Anonymous user: we will receive a text pass in the form - // user@remote.host.dom - NetSend(-1, kROOTD_AUTH); - - } else { - - if (gCryptRequired) { - // Named user: first we receive a session public key - // Ask for the RSA key - NetSend(gRSAKey, kROOTD_RSAKEY); - - // Receive the key securely - if (RpdRecvClientRSAKey()) { - ErrorInfo("RpdUser: could not import a valid key -" - " switch off reuse for this session"); - gReUseRequired = 0; - } - - // We get a random tag - if (gClientProtocol > 11) { - RpdInitRand(); - rtag = rpd_rand(); - SPrintf(ctag, 11, "#%08x#",rtag); - } - - if (gSaltRequired) { - // The crypt man page says that alternative salts can be in the form '$1$...$'; - // but on Ubuntu 10.04 the salt are in the form '$j$...$' where j is 6 or other. - if (passw[0] == '$' && passw[2] == '$') { - // Shadow passwd - char *pd = strstr(passw + 4, "$"); - lenS = (int) (pd - passw); - strncpy(salt, passw, lenS); - salt[lenS] = 0; - } else { - lenS = 2; - strncpy(salt, passw, lenS); - salt[lenS] = 0; - } - - if (gDebug > 2) - ErrorInfo("RpdUser: salt: '%s' ",salt); - - // We add the random tag here - if (gClientProtocol > 11) { - strncat(salt, ctag, sizeof(salt) - sizeof(ctag) - 1); - salt[sizeof(salt) - 1] = '\0'; - } - - // Send it over encrypted - if (RpdSecureSend(salt) == -1) { - ErrorInfo("RpdUser: problems secure-sending salt -" - " may result in corrupted salt"); - } - } else { - if (gClientProtocol > 11) { - // We send the random tag here - if (RpdSecureSend(ctag) == -1) { - ErrorInfo("RpdUser: problems secure-sending rndmtag -" - " may result in corrupted rndmtag"); - } - } else - NetSend(0, kMESS_ANY); - } - } else { - // We continue the authentication process in clear - NetSend(0, kROOTD_AUTH); - } - } - - } else { - // If we are talking to a old client protocol - NetSend(0, kROOTD_AUTH); - } - - // Get the password hash or anonymous string - if (NetRecv(recvbuf, kMaxBuf, kind) < 0) { - NetSend(kErrFatal, kROOTD_ERR); - ErrorInfo("RpdUser: error receiving message"); - return auth; - } - if (kind != kROOTD_PASS) { - NetSend(kErrFatal, kROOTD_ERR); - ErrorInfo("RpdUser: received wrong message type: %d (expecting: %d)", - kind, (int) kROOTD_PASS); - return auth; - } - if (!strncmp(recvbuf,"-1",2)) { - if (gDebug > 0) - ErrorInfo("RpdUser: client did not send a password - return"); - return auth; - } - // Get passwd - char *passwd = 0; - int lpwd = 0; - if (gAnon == 0 && gClientProtocol > 8 && gCryptRequired) { - - // Receive encrypted pass or its hash - if (RpdSecureRecv(&passwd) == -1) { - ErrorInfo - ("RpdUser: problems secure-receiving pass hash - %s", - "may result in authentication failure"); - } - // Length of the password buffer - lpwd = strlen(passwd); - - // Check the random tag, if any - if (strlen(ctag)) { - - // Check first that there is enough space for the tag - int plen = lpwd; - if (plen > 9 && - passwd[plen-1] == '#' && passwd[plen-10] == '#') { - if (strncmp(ctag,&passwd[plen-10],10)) { - // The tag does not match; failure - if (gClientProtocol > 11) - NetSend(gUsrPwdErr[2][errheq], kROOTD_ERR); - else - NetSend(kErrBadPasswd, kROOTD_ERR); - ErrorInfo("RpdUser: rndm tag mis-match" - " (%s vs %s) - Failure",&passwd[plen-10],ctag); - delete[] passwd; - return auth; - } - - // Tag ok: drop it - plen -= 10; - passwd[plen] = 0; - - } else { - // The tag is not there or incomplete; failure - if (gClientProtocol > 11) - NetSend(gUsrPwdErr[2][errheq], kROOTD_ERR); - else - NetSend(kErrBadPasswd, kROOTD_ERR); - ErrorInfo("RpdUser: rndm tag missing or incomplete" - " (pw length: %d) - Failure", plen); - delete[] passwd; - return auth; - } - } - - // If we required an hash check that we got it - // (the client sends the passwd if the crypt version is different) - if (gSaltRequired && lenS) { - if (strncmp(passwd,salt,lenS)) - gSaltRequired = 0; - } - - } else { - - // Receive clear or anonymous pass - passwd = new char[strlen(recvbuf) + 1]; - - // Re-invert pass - int i, n = strlen(recvbuf); - for (i = 0; i < n; i++) - passwd[i] = ~recvbuf[i]; - passwd[i] = '\0'; - - if (gDebug > 2 && gAnon) - ErrorInfo("RpdUser: received anonymous pass: '%s'", passwd); - } - - // Check the passwd and login if ok ... - auth = RpdPass(passwd,errheq); - - // Erase memory used for password - passwd = (char *)rpdmemset((volatile void *)passwd,0,lpwd); - delete[] passwd; - - return auth; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Try a guess of the client protocol from what they sent over -/// the net ... - -int RpdGuessClientProt(const char *buf, EMessageTypes kind) -{ - if (gDebug > 2) - ErrorInfo("RpdGuessClientProt: Enter: buf: '%s', kind: %d", buf, - (int) kind); - - // Assume same version as us. - int proto = 9; - - // Clear authentication - if (kind == kROOTD_USER) { - char usr[64], rest[256]; - int ns = sscanf(buf, "%63s %255s", usr, rest); - if (ns == 1) - proto = 8; - } - - if (gDebug > 2) - ErrorInfo("RpdGuessClientProt: guess for gClientProtocol is %d", - proto); - - // Return the guess - return proto; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Allocates and Fills a NULL terminated buffer of length Len+1 with -/// Len random characters. -/// Return pointer to the buffer (to be deleted by the caller) -/// Opt = 0 any non dangerous char -/// 1 letters and numbers (upper and lower case) -/// 2 hex characters (upper and lower case) -/// 3 crypt like [a-zA-Z0-9./] - -char *RpdGetRandString(int Opt, int Len) -{ - unsigned int iimx[4][4] = { - { 0x0, 0xffffff08, 0xafffffff, 0x2ffffffe }, // Opt = 0 - { 0x0, 0x3ff0000, 0x7fffffe, 0x7fffffe }, // Opt = 1 - { 0x0, 0x3ff0000, 0x7e, 0x7e }, // Opt = 2 - { 0x0, 0x3ffc000, 0x7fffffe, 0x7fffffe } // Opt = 3 - }; - - const char *cOpt[4] = { "Any", "LetNum", "Hex", "Crypt" }; - - // Default option 0 - if (Opt < 0 || Opt > 3) { - Opt = 0; - if (gDebug > 2) - ErrorInfo("RpdGetRandString: Unknown option: %d : assume 0", Opt); - } - if (gDebug > 2) - ErrorInfo("RpdGetRandString: Enter ... Len: %d %s", Len, cOpt[Opt]); - - // Allocate buffer - char *buf = new char[Len + 1]; - - // Init Random machinery ... - if (!gRandInit) - RpdInitRand(); - - // randomize - int k = 0; - int i, j, l, m, frnd; - while (k < Len) { - frnd = rpd_rand(); - for (m = 7; m < 32; m += 7) { - i = 0x7F & (frnd >> m); - j = i / 32; - l = i - j * 32; - if ((iimx[Opt][j] & (1 << l))) { - buf[k] = i; - k++; - } - if (k == Len) - break; - } - } - - // NULL terminated - buf[Len] = 0; - if (gDebug > 2) - ErrorInfo("RpdGetRandString: got '%s' ", buf); - - return buf; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Get public key from file pubkey (Opt == 1) or string pubkey (Opt == 0). - -int RpdGetRSAKeys(const char *pubkey, int Opt) -{ - char str[kMAXPATHLEN] = { 0 }; - int keytype = 0; - - if (gDebug > 2) - ErrorInfo("RpdGetRSAKeys: enter: string len: %d, opt %d ", - gPubKeyLen, Opt); - - if (!pubkey) - return keytype; - - char *theKey = 0; - FILE *fKey = 0; - // Parse input type - if (Opt == 1) { - - // Ok, now open it - fKey = fopen(pubkey, "r"); - if (!fKey) { - if (GetErrno() == EACCES) { - struct passwd *pw = getpwuid(getuid()); - char *usr = 0; - if (pw) - usr = pw->pw_name; - ErrorInfo("RpdGetRSAKeys: access to key file %s denied" - " to user: %s", pubkey, (usr ? usr : (char *)"????")); - } else - ErrorInfo("RpdGetRSAKeys: cannot open key file" - " %s (errno: %d)", pubkey, GetErrno()); - return 0; - } - // Check first the permissions: should be 0600 - struct stat st; - if (fstat(fileno(fKey), &st) == -1) { - ErrorInfo("RpdGetRSAKeys: cannot stat descriptor %d" - " %s (errno: %d)", fileno(fKey), GetErrno()); - fclose(fKey); - return 0; - } - if (!S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) || - (st.st_mode & 0777) != (S_IRUSR | S_IWUSR)) { - ErrorInfo("RpdGetRSAKeys: key file %s: wrong permissions" - " 0%o (should be 0600)", pubkey, (st.st_mode & 0777)); - fclose(fKey); - return 0; - } - gPubKeyLen = fread((void *)str,1,sizeof(str),fKey); - if (gDebug > 2) - ErrorInfo("RpdGetRSAKeys: length of the read key: %d",gPubKeyLen); - - // This the key - theKey = str; - } else { - // the key is the argument - theKey = (char *)pubkey; - } - - if (gPubKeyLen > 0) { - - // Skip spaces at beginning, if any - int k = 0; - while (theKey[k] == 32) k++; - - keytype = gRSAKey; - - // The format of keytype 1 is ### - char *pd1 = 0, *pd2 = 0, *pd3 = 0; - pd1 = strstr(theKey, "#"); - if (pd1) pd2 = strstr(pd1 + 1, "#"); - if (pd2) pd3 = strstr(pd2 + 1, "#"); - if (keytype == 1) { - if (!pd1 || !pd2 || !pd3) { - if (gDebug > 0) - ErrorInfo("RpdGetRSAKeys: bad format for keytype %d" - " - exit", keytype); - keytype = 0; - } - } - if (keytype == 1) { - - if (gDebug > 2) - ErrorInfo("RpdGetRSAKeys: keytype %d ", keytype); - - // Get ... - int l1 = (int) (pd2 - pd1 - 1); - char *n_exp_RSA = new char[l1 + 1]; - strncpy(n_exp_RSA, pd1 + 1, l1); - n_exp_RSA[l1] = 0; - if (gDebug > 2) - ErrorInfo("RpdGetRSAKeys: got %d bytes for n_exp_RSA", - strlen(n_exp_RSA)); - // Now - int l2 = (int) (pd3 - pd2 - 1); - char *d_exp_RSA = new char[l2 + 1]; - strncpy(d_exp_RSA, pd2 + 1, l2); - d_exp_RSA[l2] = 0; - if (gDebug > 2) - ErrorInfo("RpdGetRSAKeys: got %d bytes for d_exp_RSA", - strlen(d_exp_RSA)); - - rsa_num_sget(&gRSA_n, n_exp_RSA); - rsa_num_sget(&gRSA_d, d_exp_RSA); - - delete[] n_exp_RSA; - delete[] d_exp_RSA; - - } else if (keytype == 2){ - -#ifdef R__SSL - // try SSL - if (gDebug > 2) - ErrorInfo("RpdGetRSAKeys: keytype %d ", keytype); - - // Now set the key locally in BF form - BF_set_key(&gBFKey, gPubKeyLen, (const unsigned char *)theKey); -#else - if (gDebug > 0) { - ErrorInfo("RpdGetRSAKeys: not compiled with SSL support:" - " you should not have got here!"); - } -#endif - } - } - - if (fKey) - fclose(fKey); - - return keytype; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Save RSA public key into file for later use by other rootd. -/// Return: 0 if ok -/// 1 if not ok -/// 2 if not ok because file already exists and cannot be -/// overwritten - -int RpdSavePubKey(const char *PubKey, int OffSet, char *user) -{ - int retval = 0; - - if (gRSAKey == 0 || OffSet < 0) - return 1; - - std::string pukfile = gRpdKeyRoot; - pukfile.append(ItoA(OffSet)); - - // Unlink the file first - if (unlink(pukfile.c_str()) == -1) { - if (GetErrno() != ENOENT) - // File exists and cannot overwritten by this process - return 2; - } - - // Create file - int ipuk = -1; - ipuk = open(pukfile.c_str(), O_WRONLY | O_CREAT, 0600); - if (ipuk == -1) { - ErrorInfo("RpdSavePubKey: cannot open file %s (errno: %d)", - pukfile.c_str(),GetErrno()); - if (GetErrno() == ENOENT) - return 2; - else - return 1; - } - - // If root process set ownership of the pub key to the user - if (getuid() == 0) { - struct passwd *pw = getpwnam(user); - if (pw) { - if (fchown(ipuk,pw->pw_uid,pw->pw_gid) == -1) { - ErrorInfo("RpdSavePubKey: cannot change ownership" - " of %s (errno: %d)",pukfile.c_str(),GetErrno()); - retval = 1; - } - } else { - ErrorInfo("RpdSavePubKey: getpwnam failure (errno: %d)",GetErrno()); - retval = 1; - } - } - - // Write the key if no error occurred - if (retval == 0) { - while (write(ipuk, PubKey, gPubKeyLen) < 0 && GetErrno() == EINTR) - ResetErrno(); - } - - // close the file - close(ipuk); - - // Over - return retval; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Encode null terminated str using the session private key indcated by Key -/// and sends it over the network. -/// Returns number of bytes sent.or -1 in case of error. - -int RpdSecureSend(char *str) -{ - char buftmp[ROOT::Deprecated::kMAXSECBUF]; - char buflen[20]; - - int ttmp = 0; - int nsen = -1; - - if (gRSAKey == 1) { - strncpy(buftmp, str, sizeof(buftmp) - 1); - buftmp[ROOT::Deprecated::kMAXSECBUF - 1] = '\0'; - ttmp = rsa_encode(buftmp, strlen(buftmp) + 1, gRSA_n, gRSA_d); - } else if (gRSAKey == 2) { -#ifdef R__SSL - ttmp = strlen(str); - if ((ttmp % 8) > 0) // It should be a multiple of 8! - ttmp = ((ttmp + 8)/8) * 8; - unsigned char iv[8]; - memset((void *)&iv[0],0,8); - BF_cbc_encrypt((const unsigned char *)str, (unsigned char *)buftmp, - strlen(str), &gBFKey, iv, BF_ENCRYPT); -#else - ErrorInfo("RpdSecureSend: Not compiled with SSL support:" - " you should not have got here! - return"); -#endif - } else { - ErrorInfo("RpdSecureSend: Unknown key option (%d) - return", - gRSAKey); - } - - // Send the buffer now - SPrintf(buflen, 20, "%d", ttmp); - NetSend(buflen, kROOTD_ENCRYPT); - nsen = NetSendRaw(buftmp, ttmp); - if (gDebug > 4) - ErrorInfo("RpdSecureSend: sent %d bytes (expected: %d) - keytype: %d", - nsen, ttmp, gRSAKey); - - return nsen; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receive buffer and decode it in str using key indicated by Key type. -/// Return number of received bytes or -1 in case of error. - -int RpdSecureRecv(char **str) -{ - char buftmp[ROOT::Deprecated::kMAXSECBUF]; - char buflen[20]; - - int nrec = -1; - // We must get a pointer ... - if (!str) - return nrec; - - if (gDebug > 2) - ErrorInfo("RpdSecureRecv: enter ... (key is %d)", gRSAKey); - - EMessageTypes kind; - NetRecv(buflen, 20, kind); - int len = atoi(buflen); - if (gDebug > 4) - ErrorInfo("RpdSecureRecv: got len '%s' %d ", buflen, len); - if (!strncmp(buflen, "-1", 2)) - return nrec; - - // receive the buffer - nrec = NetRecvRaw(buftmp,len); - - // decode it - if (gRSAKey == 1) { - rsa_decode(buftmp, len, gRSA_n, gRSA_d); - if (gDebug > 2) - ErrorInfo("RpdSecureRecv: Local: decoded string is %d bytes long", - strlen(buftmp)); - - // Prepare output - const size_t strSize = strlen(buftmp) + 1; - *str = new char[strSize]; - strlcpy(*str, buftmp, strSize); - } else if (gRSAKey == 2) { -#ifdef R__SSL - unsigned char iv[8]; - memset((void *)&iv[0],0,8); - *str = new char[nrec + 1]; - BF_cbc_encrypt((const unsigned char *)buftmp, (unsigned char *)(*str), - nrec, &gBFKey, iv, BF_DECRYPT); - (*str)[nrec] = '\0'; -#else - ErrorInfo("RpdSecureRecv: Not compiled with SSL support:" - " you should not have got here! - return"); -#endif - } else { - ErrorInfo("RpdSecureRecv: Unknown key option (%d) - return", - gRSAKey); - } - - return nrec; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Generate a valid pair of private/public RSA keys to protect for -/// authentication password and token exchange -/// Returns 1 if a good key pair is not found after kMAXRSATRIES attempts -/// Returns 0 if a good key pair is found -/// If setrndinit = 1, no futher init of the random engine - -int RpdGenRSAKeys(int setrndinit) -{ - if (gDebug > 2) - ErrorInfo("RpdGenRSAKeys: enter"); - - // Init Random machinery ... - if (!gRandInit) - RpdInitRand(); - gRandInit = setrndinit; - -#ifdef R__NOCRYPT - // Generate a random salt - char *rsalt = RpdGetRandString(3,8); - if (rsalt) { - gRndmSalt = std::string(rsalt); - delete[] rsalt; - } else { - if (gDebug > 0) - ErrorInfo("RpdGenRSAKeys: could not generate random salt"); - } -#endif - -#ifdef R__SSL - // Generate also the SSL key - if (gDebug > 2) - ErrorInfo("RpdGenRSAKeys: Generate RSA SSL keys"); - - // Init SSL ... - SSL_library_init(); - - // ... and its error strings - SSL_load_error_strings(); - - // Load Ciphers - OpenSSL_add_all_ciphers(); - - // Number of bits for key - Int_t nbits = 1024; - - // Public exponent - Int_t pubex = 17; - - // Init random engine - char *rbuf = RpdGetRandString(0,40); - RAND_seed(rbuf,strlen(rbuf)); - - // Generate Key - gRSASSLKey = RSA_generate_key(nbits,pubex,0,0); - - // Bio for exporting the pub key - BIO *bkey = BIO_new(BIO_s_mem()); - - // Write public key to BIO - PEM_write_bio_RSAPublicKey(bkey,gRSASSLKey); - - // Read key from BIO to buf - Int_t sbuf = 2*RSA_size(gRSASSLKey); - char *kbuf = new char[sbuf]; - BIO_read(bkey,(void *)kbuf,sbuf); - BIO_free(bkey); - - // Prepare export - gRSAPubExport[1].len = sbuf; - gRSAPubExport[1].keys = new char[gRSAPubExport[1].len + 2]; - strncpy(gRSAPubExport[1].keys,kbuf,gRSAPubExport[1].len); - gRSAPubExport[1].keys[gRSAPubExport[1].len-1] = '\0'; - delete[] kbuf; - if (gDebug > 2) - ErrorInfo("RpdGenRSAKeys: SSL: export pub:\n%.*s", - gRSAPubExport[1].len,gRSAPubExport[1].keys); - - // We have at least one key - gRSAInit = 1; - -#endif - - // Sometimes some bunch is not decrypted correctly - // That's why we make retries to make sure that encryption/decryption - // works as expected - bool notOK = 1; - rsa_NUMBER p1, p2, rsa_n, rsa_e, rsa_d; - int l_n = 0, l_d = 0; -#if R__RSADEB - Int_t l_e = 0; - char buf[rsa_STRLEN]; -#endif - char buf_n[rsa_STRLEN], buf_e[rsa_STRLEN], buf_d[rsa_STRLEN]; - - int nAttempts = 0; - int thePrimeLen = ROOT::Deprecated::kPRIMELENGTH; - int thePrimeExp = ROOT::Deprecated::kPRIMEEXP + 5; // Prime probability = 1-0.5^thePrimeExp - while (notOK && nAttempts < ROOT::Deprecated::kMAXRSATRIES) { - - nAttempts++; - if (gDebug > 2 && nAttempts > 1) { - ErrorInfo("RpdGenRSAKeys: retry no. %d",nAttempts); - srand(rpd_rand()); - } - - // Valid pair of primes - p1 = rsa_genprim(thePrimeLen, thePrimeExp); - p2 = rsa_genprim(thePrimeLen+1, thePrimeExp); - - // Retry if equal - int nPrimes = 0; - while (rsa_cmp(&p1, &p2) == 0 && nPrimes < ROOT::Deprecated::kMAXRSATRIES) { - nPrimes++; - if (gDebug > 2) - ErrorInfo("RpdGenRSAKeys: equal primes: regenerate (%d times)",nPrimes); - srand(rpd_rand()); - p1 = rsa_genprim(thePrimeLen, thePrimeExp); - p2 = rsa_genprim(thePrimeLen+1, thePrimeExp); - } - -#if R__RSADEB - if (gDebug > 2) { - rsa_num_sput(&p1, buf, rsa_STRLEN); - ErrorInfo("RpdGenRSAKeys: local: p1: '%s' ", buf); - rsa_num_sput(&p2, buf, rsa_STRLEN); - ErrorInfo("RpdGenRSAKeys: local: p2: '%s' ", buf); - } -#endif - - // Generate keys - if (rsa_genrsa(p1, p2, &rsa_n, &rsa_e, &rsa_d)) { - if (gDebug > 0) - ErrorInfo("RpdGenRSAKeys: genrsa: attempt %d to generate" - " keys failed",nAttempts); - continue; - } - - // Determine their lengths - rsa_num_sput(&rsa_n, buf_n, rsa_STRLEN); - l_n = strlen(buf_n); - rsa_num_sput(&rsa_e, buf_e, rsa_STRLEN); -#if R__RSADEB - l_e = strlen(buf_e); -#endif - rsa_num_sput(&rsa_d, buf_d, rsa_STRLEN); - l_d = strlen(buf_d); - -#if R__RSADEB - if (gDebug > 2) { - ErrorInfo("RpdGenRSAKeys: local: n: '%s' length: %d", buf_n, l_n); - ErrorInfo("RpdGenRSAKeys: local: e: '%s' length: %d", buf_e, l_e); - ErrorInfo("RpdGenRSAKeys: local: d: '%s' length: %d", buf_d, l_d); - } -#endif - if (rsa_cmp(&rsa_n, &rsa_e) <= 0) - continue; - if (rsa_cmp(&rsa_n, &rsa_d) <= 0) - continue; - - // Now we try the keys - char test[2 * rsa_STRLEN] = "ThisIsTheStringTest01203456-+/"; - Int_t lTes = 31; - char *dumT = RpdGetRandString(0, lTes - 1); - strncpy(test, dumT, lTes); - delete[]dumT; - char buf[2 * rsa_STRLEN]; - if (gDebug > 3) - ErrorInfo("RpdGenRSAKeys: local: test string: '%s' ", test); - - // Private/Public - strncpy(buf, test, lTes); - buf[lTes] = 0; - - // Try encryption with private key - int lout = rsa_encode(buf, lTes, rsa_n, rsa_e); - if (gDebug > 3) - ErrorInfo("GenRSAKeys: local: length of crypted string: %d bytes", lout); - - // Try decryption with public key - rsa_decode(buf, lout, rsa_n, rsa_d); - buf[lTes] = 0; - if (gDebug > 3) - ErrorInfo("RpdGenRSAKeys: local: after private/public : '%s' ", buf); - - if (strncmp(test, buf, lTes)) - continue; - - // Public/Private - strncpy(buf, test, lTes); - buf[lTes] = 0; - - // Try encryption with public key - lout = rsa_encode(buf, lTes, rsa_n, rsa_d); - if (gDebug > 3) - ErrorInfo("RpdGenRSAKeys: local: length of crypted string: %d bytes ", - lout); - - // Try decryption with private key - rsa_decode(buf, lout, rsa_n, rsa_e); - buf[lTes] = 0; - if (gDebug > 3) - ErrorInfo("RpdGenRSAKeys: local: after public/private : '%s' ", buf); - - if (strncmp(test, buf, lTes)) - continue; - - notOK = 0; - } - - if (notOK) { - ErrorInfo("RpdGenRSAKeys: unable to generate good RSA key pair" - " (%d attempts)- return",ROOT::Deprecated::kMAXRSATRIES); - return 1; - } - - // Save Private key - rsa_assign(&gRSAPriKey.n, &rsa_n); - rsa_assign(&gRSAPriKey.e, &rsa_e); - - // Save Public key - rsa_assign(&gRSAPubKey.n, &rsa_n); - rsa_assign(&gRSAPubKey.e, &rsa_d); - -#if R__RSADEB - if (gDebug > 2) { - // Determine their lengths - ErrorInfo("RpdGenRSAKeys: local: generated keys are:"); - ErrorInfo("RpdGenRSAKeys: local: n: '%s' length: %d", buf_n, l_n); - ErrorInfo("RpdGenRSAKeys: local: e: '%s' length: %d", buf_e, l_e); - ErrorInfo("RpdGenRSAKeys: local: d: '%s' length: %d", buf_d, l_d); - } -#endif - // Export form - gRSAPubExport[0].len = l_n + l_d + 4; - if (gRSAPubExport[0].keys) - delete[] gRSAPubExport[0].keys; - gRSAPubExport[0].keys = new char[gRSAPubExport[0].len]; - - gRSAPubExport[0].keys[0] = '#'; - memcpy(gRSAPubExport[0].keys + 1, buf_n, l_n); - gRSAPubExport[0].keys[l_n + 1] = '#'; - memcpy(gRSAPubExport[0].keys + l_n + 2, buf_d, l_d); - gRSAPubExport[0].keys[l_n + l_d + 2] = '#'; - gRSAPubExport[0].keys[l_n + l_d + 3] = 0; -#if R__RSADEB - if (gDebug > 2) - ErrorInfo("RpdGenRSAKeys: local: export pub: '%s'", - gRSAPubExport[0].keys); -#else - if (gDebug > 2) - ErrorInfo("RpdGenRSAKeys: local: export pub length: %d bytes", - gRSAPubExport[0].len); -#endif - - gRSAInit = 1; - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Generates local public/private RSA key pair -/// Send request for Client Public Key and Local public key -/// Receive encoded Client Key -/// Decode Client public key -/// NB: key is not saved to file here - -int RpdRecvClientRSAKey() -{ - if (gRSAInit == 0) { - // Generate Local RSA keys for the session - if (RpdGenRSAKeys(1)) { - ErrorInfo("RpdRecvClientRSAKey: unable to generate local keys"); - return 1; - } - } - - // Send server public key - int key = gRSAKey - 1; - NetSend(gRSAPubExport[key].keys, gRSAPubExport[key].len, kROOTD_RSAKEY); - - // Receive length of message with encode client public key - EMessageTypes kind; - char buflen[40]; - NetRecv(buflen, 20, kind); - gPubKeyLen = atoi(buflen); - if (gDebug > 3) - ErrorInfo("RpdRecvClientRSAKey: got len '%s' %d ", buflen, gPubKeyLen); - - int nrec = 0; - - if (gRSAKey == 1) { - - // Receive and decode encoded public key - nrec = NetRecvRaw(gPubKey, gPubKeyLen); - - rsa_decode(gPubKey, gPubKeyLen, gRSAPriKey.n, gRSAPriKey.e); - if (gDebug > 2) - ErrorInfo("RpdRecvClientRSAKey: Local: decoded string is %d bytes long ", - strlen(gPubKey)); - gPubKeyLen = strlen(gPubKey); - - } else if (gRSAKey == 2) { -#ifdef R__SSL - int ndec = 0; - int lcmax = RSA_size(gRSASSLKey); - char btmp[kMAXSECBUF]; - int nr = gPubKeyLen; - int kd = 0; - while (nr > 0) { - // Receive and decode encoded public key - nrec += NetRecvRaw(btmp, lcmax); - if ((ndec = RSA_private_decrypt(lcmax,(unsigned char *)btmp, - (unsigned char *)&gPubKey[kd], - gRSASSLKey, - RSA_PKCS1_PADDING)) < 0) { - char errstr[120]; - ERR_error_string(ERR_get_error(), errstr); - ErrorInfo("RpdRecvClientRSAKey: SSL: error: '%s' ",errstr); - } - nr -= lcmax; - kd += ndec; - } - gPubKeyLen = kd; -#else - if (gDebug > 0) - ErrorInfo("RpdRecvClientRSAKey: not compiled with SSL support" - ": you should not have got here!"); - return 1; -#endif - } else { - if (gDebug > 0) - ErrorInfo("RpdRecvClientRSAKey: unknown key type (%d)", gRSAKey); - } - - - // Import Key and Determine key type - if (RpdGetRSAKeys(gPubKey, 0) != gRSAKey) { - ErrorInfo("RpdRecvClientRSAKey:" - " could not import a valid key (type %d)",gRSAKey); - char *elogfile = new char[gRpdKeyRoot.length() + 11]; - SPrintf(elogfile, gRpdKeyRoot.length() + 11, "%.*serr.XXXXXX", (int)gRpdKeyRoot.length(), gRpdKeyRoot.c_str()); - mode_t oldumask = umask(0700); - int ielog = mkstemp(elogfile); - umask(oldumask); - if (ielog != -1) { - char line[kMAXPATHLEN] = {0}; - // - SPrintf(line,kMAXPATHLEN, - " + RpdRecvClientRSAKey: error importing key\n + type: %d\n" - " + length: %d\n + key: %s\n + (%d bytes were received)", - gRSAKey, gPubKeyLen, gPubKey, nrec); - while (write(ielog, line, strlen(line)) < 0 && GetErrno() == EINTR) - ResetErrno(); - close (ielog); - } - delete [] elogfile; - return 2; - } - - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Init random machine. - -void RpdInitRand() -{ - const char *randdev = "/dev/urandom"; - - int fd; - unsigned int seed; - if ((fd = open(randdev, O_RDONLY)) != -1) { - if (gDebug > 2) - ErrorInfo("RpdInitRand: taking seed from %s", randdev); - if (read(fd, &seed, sizeof(seed))) {;} - close(fd); - } else { - if (gDebug > 2) - ErrorInfo("RpdInitRand: %s not available: using time()", randdev); - seed = time(0); //better use times() + win32 equivalent - } - srand(seed); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Handle user authentication. - -int RpdAuthenticate() -{ - char buf[kMAXRECVBUF]; - EMessageTypes kind; - -//#define R__DEBUG -#ifdef R__DEBUG - int debug = 1; - while (debug) - ; -#endif - - // Reset gAuth (if we have been called this means that we need - // to check at least that a valid authentication exists ...) - int auth = 0; - - while (!auth) { - - // Receive next - if (!gClientOld) { - if (NetRecv(buf, kMAXRECVBUF, kind) < 0) { - Error(gErr, -1, "RpdAuthenticate: error receiving message"); - return auth; - } - } else { - strlcpy(buf,gBufOld, sizeof(buf)); - kind = gKindOld; - gBufOld[0] = '\0'; - gClientOld = 0; - } - - // If this is a rootd contacted via a TNetXNGFile we need to - // receive again the buffer - if (gService == kROOTD && kind == kROOTD_PROTOCOL) { - if (NetRecv(buf, kMAXRECVBUF, kind) < 0) { - Error(gErr, -1, "RpdAuthenticate: error receiving message"); - return auth; - } - } - - // Decode the method ... - gAuthProtocol = RpdGetAuthMethod(kind); - - if (gDebug > 2) { - if (kind != kROOTD_PASS) { - ErrorInfo("RpdAuthenticate got: %d -- %s", kind, buf); - } else { - ErrorInfo("RpdAuthenticate got: %d ", kind); - } - } - - // Guess the client procotol if not received via Rootd - if (gClientProtocol == 0) - gClientProtocol = RpdGuessClientProt(buf, kind); - - // If the client supports it check if we accept the method proposed; - // if not send back the list of accepted methods, if any ... - if (gAuthProtocol != -1 && gClientProtocol > 8) { - - // Check if accepted ... - if (RpdCheckAuthAllow(gAuthProtocol, gOpenHost.c_str())) { - if (gNumAllow>0) { - if (gAuthListSent == 0) { - if (gDebug > 0) - ErrorInfo("Authenticate: %s method not" - " accepted from host: %s", - gAuthMeth[gAuthProtocol].c_str(), - gOpenHost.c_str()); - NetSend(kErrNotAllowed, kROOTD_ERR); - RpdSendAuthList(); - gAuthListSent = 1; - goto next; - } else { - Error(gErr,kErrNotAllowed,"Authenticate: method not" - " in the list sent to the client"); - return auth; - } - } else { - Error(gErr,kErrConnectionRefused,"Authenticate:" - " connection refused from host %s", gOpenHost.c_str()); - return auth; - } - } - - // Then check if a previous authentication exists and is valid - if ((auth = RpdReUseAuth(buf, kind))) - goto next; - } - - // Reset global variable - auth = 0; - - switch (kind) { - case kROOTD_USER: - auth = RpdUser(buf); - break; - case kROOTD_PASS: - auth = RpdPass(buf); - break; - case kROOTD_CLEANUP: - RpdAuthCleanup(buf,1); - ErrorInfo("RpdAuthenticate: authentication stuff cleaned - exit"); - // Fallthrough next case now to free the keys - case kROOTD_BYE: - RpdFreeKeys(); - return auth; - default: - Error(gErr,-1,"RpdAuthenticate: received bad opcode %d", kind); - return auth; - } - - if (gClientProtocol > 8) { - - // If failure prepare or continue negotiation - int doneg = (gAuthProtocol != -1 || kind == kROOTD_PASS); - if (gDebug > 2 && doneg) - ErrorInfo("RpdAuthenticate: kind:%d meth:%d auth:%d gNumLeft:%d", - kind, gAuthProtocol, auth, gNumLeft); - - // If authentication failure, check if other methods could be tried ... - if (auth == 0 && doneg) { - if (gNumLeft > 0) { - if (gAuthListSent == 0) { - RpdSendAuthList(); - gAuthListSent = 1; - } else - NetSend(-1, kROOTD_NEGOTIA); - } else { - NetSend(0, kROOTD_NEGOTIA); - Error(gErr, -1, "RpdAuthenticate: authentication failed"); - return auth; - } - } - } -next: - continue; - } - - return auth; -} -//////////////////////////////////////////////////////////////////////////////// -/// Free space allocated for encryption keys - -void RpdFreeKeys() -{ - if (gRSAPubExport[0].keys) delete[] gRSAPubExport[0].keys; - if (gRSAPubExport[1].keys) delete[] gRSAPubExport[1].keys; -#ifdef R__SSL - RSA_free(gRSASSLKey); -#endif -} - -//////////////////////////////////////////////////////////////////////////////// -/// Receives client protocol and returns daemon protocol. -/// Returns: 0 if ok -/// -1 if any error occurred -/// -2 if special action (e.g. cleanup): no need to continue - -int RpdProtocol(int ServType) -{ - int rc = 0; - -//#define R__DEBUG -#ifdef R__DEBUG - int debug = 1; - while (debug) - ; -#endif - - if (gDebug > 2) - ErrorInfo("RpdProtocol: Enter: server type = %d", ServType); - - int readbuf = 1; - EMessageTypes kind; - char proto[kMAXRECVBUF]; - - // For backward compatibility, for rootd we need to understand - // whether we are talking to a OLD client: protocol information is - // available only later on ... - int lbuf[2]; - if (NetRecvRaw(lbuf, sizeof(lbuf)) < 0) { - NetSend(kErrFatal, kROOTD_ERR); - ErrorInfo("RpdProtocol: error receiving message"); - return -1; - } - - // if kind is {kROOTD_PROTOCOL, kROOTD_CLEANUP} - // receive the rest - kind = (EMessageTypes) ntohl(lbuf[1]); - int len = ntohl(lbuf[0]); - if (gDebug > 1) - ErrorInfo("RpdProtocol: kind: %d %d",kind,len); - if (kind == kROOTD_PROTOCOL || kind == kROOTD_CLEANUP) { - // Receive the rest - char *buf = 0; - len -= sizeof(int); - if (gDebug > 1) - ErrorInfo("RpdProtocol: len: %d",len); - if (len) { - buf = new char[len]; - if (NetRecvRaw(buf, len) < 0) { - NetSend(kErrFatal, kROOTD_ERR); - ErrorInfo("RpdProtocol: error receiving message"); - delete[] buf; - return -1; - } - strlcpy(proto, buf, sizeof(proto)); - } else { - // Empty buffer - proto[0] = '\0'; - } - if (gDebug > 1) - ErrorInfo("RpdProtocol: proto buff: %s", buf ? buf : "---"); - // Copy buffer for later use - readbuf = 0; - if (buf) delete[] buf; - } else if (ServType == kROOTD && kind == 0 && len == 0) { - // TNetFile via TNetXNGFile: receive client protocol - // read first next 12 bytes and discard them - int llen = 12; - char *buf = new char[llen]; - if (NetRecvRaw(buf, llen) < 0) { - NetSend(kErrFatal, kROOTD_ERR); - ErrorInfo("RpdProtocol: error receiving message"); - if (buf) delete[] buf; - return -1; - } - if (buf) delete[] buf; - // Send back the 'type' - int type = htonl(8); - if (NetSendRaw(&type,sizeof(type)) < 0) { - NetSend(kErrFatal, kROOTD_ERR); - ErrorInfo("RpdProtocol: error sending type to TNetXNGFile"); - return -1; - } - // Now read the client protocol - llen = 4; - buf = new char[llen]; - if (NetRecvRaw(buf,llen) < 0) { - NetSend(kErrFatal, kROOTD_ERR); - ErrorInfo("RpdProtocol: error receiving message"); - delete[] buf; - return -1; - } - strlcpy(proto,buf, sizeof(proto)); - kind = kROOTD_PROTOCOL; - readbuf = 0; - delete[] buf; - } else { - // Need to open parallel sockets first - int size = ntohl(lbuf[1]); - // Read port - int port; - if (NetRecvRaw(&port, sizeof(int)) < 0) { - NetSend(kErrFatal, kROOTD_ERR); - ErrorInfo("RpdProtocol: error receiving message"); - return -1; - } - port = ntohl(port); - if (gDebug > 0) - ErrorInfo("RpdProtocol: port = %d, size = %d", port, size); - if (size > 1) - NetParOpen(port, size); - } - - int done = 0; - gClientOld = 0; - while (!done) { - - // Receive next - if (readbuf) { - if (NetRecv(proto, kMAXRECVBUF, kind) < 0) { - ErrorInfo("RpdProtocol: error receiving message"); - return -1; - } - } - readbuf = 1; - - switch(kind) { - - case kROOTD_CLEANUP: - RpdAuthCleanup(proto,1); - ErrorInfo("RpdProtocol: authentication stuff cleaned"); - done = 1; - rc = -2; - break; - case kROOTD_BYE: - RpdFreeKeys(); - NetClose(); - done = 1; - rc = -2; - break; - case kROOTD_PROTOCOL: - - if (strlen(proto) > 0) { - gClientProtocol = atoi(proto); - } else { - if (ServType == kROOTD) { - // This is an old (TNetFile,TFTP) client: - // send our protocol first ... - if (NetSend(gServerProtocol, kROOTD_PROTOCOL) < 0) { - ErrorInfo("RpdProtocol: error sending kROOTD_PROTOCOL"); - rc = -1; - } - // ... and receive protocol via kROOTD_PROTOCOL2 - if (NetRecv(proto, kMAXRECVBUF, kind) < 0) { - ErrorInfo("RpdProtocol: error receiving message"); - rc = -1; - } - if (kind != kROOTD_PROTOCOL2) { - strlcpy(gBufOld, proto, sizeof(gBufOld)); - gKindOld = kind; - gClientOld = 1; - gClientProtocol = 0; - } else - gClientProtocol = atoi(proto); - } else - gClientProtocol = 0; - } - if (!gClientOld) { - // send our protocol - // if we do not require authentication say it here - Int_t protoanswer = gServerProtocol; - if (!gRequireAuth && gClientProtocol > 10) - protoanswer += 1000; - // Notify - if (gDebug > 0) { - ErrorInfo("RpdProtocol: gClientProtocol = %d", - gClientProtocol); - ErrorInfo("RpdProtocol: Sending gServerProtocol = %d", - protoanswer); - } - if (NetSend(protoanswer, kROOTD_PROTOCOL) < 0) { - ErrorInfo("RpdProtocol: error sending kROOTD_PROTOCOL"); - rc = -1; - } - } - done = 1; - break; - default: - ErrorInfo("RpdProtocol: received bad option (%d)",kind); - rc = -1; - done = 1; - break; - } // Switch - - } // done - - return rc; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Authentication was successful, set user environment. - -int RpdLogin(int ServType, int auth) -{ -// if (gDebug > 2) - ErrorInfo("RpdLogin: enter: Server: %d, gUser: %s, auth: %d", - ServType, gUser, auth); - - // Login only if requested - if (gDoLogin == 0) - return -2; - - struct passwd *pw = getpwnam(gUser); - - if (!pw) { - ErrorInfo("RpdLogin: user %s does not exist locally\n", gUser); - return -1; - } - - if (getuid() == 0) { - // Anonymous users are confined to their corner - if (gAnon) { - // We need to do it before chroot, otherwise it does not work - if (chdir(pw->pw_dir) == -1) { - ErrorInfo("RpdLogin: can't change directory to %s (errno: %d)", - pw->pw_dir, errno); - return -1; - } - if (chroot(pw->pw_dir) == -1) { - ErrorInfo("RpdLogin: can't chroot to %s", pw->pw_dir); - return -1; - } - } - - // set access control list from /etc/initgroup - initgroups(gUser, pw->pw_gid); - - // set uid and gid - if (setresgid(pw->pw_gid, pw->pw_gid, 0) == -1) { - ErrorInfo("RpdLogin: can't setgid for user %s", gUser); - return -1; - } - if (setresuid(pw->pw_uid, pw->pw_uid, 0) == -1) { - ErrorInfo("RpdLogin: can't setuid for user %s", gUser); - return -1; - } - } - - if (ServType == 2) { - // set HOME env - char *home = new char[8+strlen(pw->pw_dir)]; - SPrintf(home, 8+strlen(pw->pw_dir), "HOME=%s", pw->pw_dir); - putenv(home); - } - - // Change user's HOME, if required (for anon it is already done) - if (gDoLogin == 2 && !gAnon) { - if (chdir(pw->pw_dir) == -1) { - ErrorInfo("RpdLogin: can't change directory to %s (errno: %d)", - pw->pw_dir, errno); - return -1; - } - } - - umask(022); - - // Notify authentication to client ... - NetSend(auth, kROOTD_AUTH); - // Send also new offset if it changed ... - if (auth == 2) NetSend(gOffSet, kROOTD_AUTH); - - if (gDebug > 0) - ErrorInfo("RpdLogin: user %s logged in", gUser); - - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Perform the action needed to commence the new session: -/// Version called by TServerSocket. -/// - set debug flag -/// - check authentication table -/// - Inquire protocol -/// - authenticate the client -/// Returns logged-in user, the remote client procotol cproto, -/// the authentication protocol (ROOT internal) number is returned -/// in meth, type indicates the kind of authentication: -/// 0 = new authentication -/// 1 = existing authentication -/// 2 = existing authentication with updated offset -/// and the crypted-token in ctoken (used later for cleaning). -/// Called just after opening the connection - -int RpdInitSession(int servtype, std::string &user, - int &cproto, int &meth, int &type, std::string &ctoken) -{ - std::string pwd; - int auth = RpdInitSession(servtype,user,cproto,meth,pwd); - if (auth == 1) - if (gExistingAuth) - type = 1; - else - type = 0; - else if (auth == 2) - type = 2; - ctoken = gCryptToken; - - return auth; -} -//////////////////////////////////////////////////////////////////////////////// -/// Perform the action needed to commence the new session: -/// - set debug flag -/// - check authentication table -/// - Inquire protocol -/// - authenticate the client -/// - login the client -/// Returns 0 in presence of a server. -/// Returns logged-in user, the remote client procotol cproto, the -/// client kind of user anon and, if anonymous user, the client passwd. -/// If TServerSocket (servtype==kSOCKD), the protocol number is returned -/// in anon. -/// Called just after opening the connection - -int RpdInitSession(int servtype, std::string &user, - int &cproto, int &anon, std::string &passwd) -{ - if (gDebug > 2) - ErrorInfo("RpdInitSession: %s", gServName[servtype].c_str()); - - int retval = 0; - - // CleanUp authentication table, if needed or required ... - RpdInitAuth(); - - // Get Host name - NetGetRemoteHost(gOpenHost); - - // Get protocol first - // Failure typically indicate special actions like cleanup - // which do not need additional work - // The calling program will then decide what to do - int rcp = RpdProtocol(servtype); - if (rcp != 0) { - if (rcp == -1) - ErrorInfo("RpdInitSession: error getting remote protocol"); - else if (rcp != -2) - ErrorInfo("RpdInitSession: unknown error from RpdProtocol"); - return rcp; - } - - // Check if authentication is required - // Old clients do not support no authentication mode - bool runAuth = (gClientProtocol < 11 || gRequireAuth) ? 1 : 0; - - // user authentication (does not return in case of failure) - int auth = 0; - if (runAuth) { - auth = RpdAuthenticate(); - if (auth == 0) { - ErrorInfo("RpdInitSession: unsuccessful authentication attempt"); - return -1; - } - } else { - auth = RpdNoAuth(servtype); - } - - // Login the user (if in rootd environment) - if (gDoLogin > 0) { - if (RpdLogin(servtype,auth) != 0) { - ErrorInfo("RpdInitSession: unsuccessful login attempt"); - // Notify failure to client ... - NetSend(0, kROOTD_AUTH); - return -1; - } - } else { - // Notify authentication to client ... - NetSend(auth, kROOTD_AUTH); - // Send also new offset if it changed ... - if (auth == 2) - NetSend(gOffSet, kROOTD_AUTH); - if (gDebug > 0) - ErrorInfo("RpdInitSession: User '%s' authenticated", gUser); - retval = auth; - } - - // Output vars - user = std::string(gUser); - cproto = gClientProtocol; - if (servtype == kSOCKD) - anon = gSec; - else - anon = gAnon; - if (gAnon) - passwd = std::string(gPasswd); - - return retval; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Perform the action needed to commence the new session: -/// - set debug flag -/// - check authentication table -/// - Inquire protocol -/// - authenticate the client -/// - login the client -/// Returns 0 in presence of a master server. -/// Returns logged-in user and remote process id in rid -/// Called just after opening the connection - -int RpdInitSession(int servtype, std::string &user, int &rid) -{ - int dum1 = 0, dum2 = 0; - std::string dum3; - rid = gRemPid; - return RpdInitSession(servtype,user,dum1,dum2,dum3); - -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Perform entrance formalities in case of no authentication -/// mode, i.e. get target user and check if authorized -/// Don't return if something goes wrong - -int RpdNoAuth(int servtype) -{ - if (gDebug > 1) - ErrorInfo("RpdNoAuth: no authentication required"); - - // Special value for this case - int auth = 0; - - // Receive target username - if (servtype == kROOTD) { - - char buf[kMAXPATHLEN]; - EMessageTypes kind; - if (NetRecv(buf, kMAXPATHLEN, kind) < 0) { - NetSend(kErrBadMess, kROOTD_ERR); - ErrorInfo("RpdNoAuth: error receiving target user"); - goto quit; - } - - if (kind == kROOTD_BYE) - goto quit; - - if (kind != kROOTD_USER) { - NetSend(kErrBadOp, kROOTD_ERR); - ErrorInfo("RpdNoAuth: protocol error:" - " received msg type: %d, expecting: %d", kind, kROOTD_USER); - goto quit; - } - - // Decode buffer - char ruser[kMAXUSERLEN], user[kMAXUSERLEN]; - int nw = sscanf(buf,"%64s %64s",ruser,user); - if (nw <= 0 || !strcmp(ruser,"-1")) { - NetSend(kErrBadMess, kROOTD_ERR); - ErrorInfo("RpdNoAuth: received uncorrect information: %s", buf); - goto quit; - } - // If target user not send, assume user == ruser - if (nw == 1) - snprintf(user,kMAXUSERLEN,"%s",ruser); - - struct passwd *pw = 0; - if ((pw = getpwnam(user)) == 0) { - NetSend(kErrNoUser, kROOTD_ERR); - ErrorInfo("RpdNoAuth: user %s unknown", user); - goto quit; - } - - // If server is not started as root, require user to be the same - // as the one who started rootd - uid_t uid = getuid(); - if (uid && uid != pw->pw_uid) { - NetSend(kErrBadUser, kROOTD_ERR); - ErrorInfo("RpdNoAuth: user not same as effective user of rootd"); - goto quit; - } - - if (gDebug > 2) - ErrorInfo("RpdNoAuth: remote user: %s, target user: %s",ruser,user); - - SPrintf(gUser, 63, "%s", user); - } - - auth = 4; - - quit: - return auth; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Change current user id to uid (and gid). - -int RpdSetUid(int uid) -{ - if (gDebug > 2) - ErrorInfo("RpdSetUid: enter ...uid: %d", uid); - - struct passwd *pw = getpwuid(uid); - - if (!pw) { - ErrorInfo("RpdSetUid: uid %d does not exist locally", uid); - return -1; - } else if (chdir(pw->pw_dir) == -1) { - ErrorInfo("RpdSetUid: can't change directory to %s", pw->pw_dir); - return -1; - } - - if (getuid() == 0) { - - // set access control list from /etc/initgroup - initgroups(pw->pw_name, pw->pw_gid); - - // set uid and gid - if (setresgid(pw->pw_gid, pw->pw_gid, 0) == -1) { - ErrorInfo("RpdSetUid: can't setgid for uid %d", uid); - return -1; - } - if (setresuid(pw->pw_uid, pw->pw_uid, 0) == -1) { - ErrorInfo("RpdSetUid: can't setuid for uid %d", uid); - return -1; - } - } - - if (gDebug > 0) - ErrorInfo("RpdSetUid: uid set (%d,%s)", uid, pw->pw_name); - - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Change defaults job control options. - -void RpdInit(EService serv, int pid, int sproto, unsigned int options, - int rumsk, int, const char *tmpd, const char * /* asrpp */, int login) -{ - gService = serv; - gParentId = pid; - gServerProtocol = sproto; - gReUseAllow = rumsk; - gDoLogin = login; - - // Parse options - gCheckHostsEquiv= (bool)((options & kDMN_HOSTEQ) != 0); - gRequireAuth = (bool)((options & kDMN_RQAUTH) != 0); - gSysLog = (bool)((options & kDMN_SYSLOG) != 0); - - if (tmpd && strlen(tmpd)) { - gTmpDir = tmpd; - gRpdAuthTab = gTmpDir + gAuthTab; - gRpdKeyRoot = gTmpDir + gKeyRoot; - } - // Auth Tab and public key files are exclusive to this family - gRpdAuthTab.append("."); - gRpdAuthTab.append(ItoA(getuid())); - gRpdKeyRoot.append(ItoA(getuid())); - gRpdKeyRoot.append("_"); - - if (gDebug > 0) { - ErrorInfo("RpdInit: gService= %s, gSysLog= %d", - gServName[gService].c_str(), gSysLog); - ErrorInfo("RpdInit: gParentId= %d", gParentId); - ErrorInfo("RpdInit: gRequireAuth= %d, gCheckHostEquiv= %d", - gRequireAuth, gCheckHostsEquiv); - ErrorInfo("RpdInit: gReUseAllow= 0x%x", gReUseAllow); - ErrorInfo("RpdInit: gServerProtocol= %d", gServerProtocol); - ErrorInfo("RpdInit: gDoLogin= %d", gDoLogin); - if (tmpd) - ErrorInfo("RpdInit: gTmpDir= %s", gTmpDir.c_str()); - } -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Acts like snprintf with some printout in case of error if required -/// Returns number of characters printed (excluding the trailing `\0'). -/// Returns 0 is buf or size are not defined or inconsistent. -/// Returns -1 if the buffer is truncated. - -int SPrintf(char *buf, size_t size, const char *va_(fmt), ...) -{ - // Check buf - if (!buf) { - if (gDebug > 0) - ErrorInfo("SPrintf: buffer not allocated: do nothing"); - return 0; - } - - // Check size - if (size < 1) { - if (gDebug > 0) - ErrorInfo("SPrintf: cannot determine buffer size (%d): do nothing",size); - return 0; - } - - // Now fill buf - va_list ap; - va_start(ap,va_(fmt)); - int np = vsnprintf(buf, size, fmt, ap); - va_end(ap); - - if (np == -1 && gDebug > 0) - ErrorInfo("SPrintf: buffer truncated (%s)",buf); - - return np; -} - - -//////////////////////////////////////////////////////////////////////////////// -/// Return pointer to a static string containing the string -/// version of integer 'i', up to a max of kMAXCHR (=30) -/// characters; returns "-1" if more chars are needed. - -char *ItoA(int i) -{ - const int kMAXCHR = 30; - static char str[kMAXCHR]; - - // This is the number of characters we need - int nchr = (int)log10(double(i)) + 1; - if (nchr > kMAXCHR) - strlcpy(str,"-1", sizeof(str)); - else - snprintf(str,30,"%d",i); - - return str; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set global pointers to error handler functions - -void RpdSetErrorHandler(ErrorHandler_t err, ErrorHandler_t sys, ErrorHandler_t fatal) -{ - gErr = err; - gErrSys = sys; - gErrFatal = fatal; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Retrieve specific ROOT password from $HOME/fpw, if any. -/// To avoid problems with NFS-root-squashing, if 'root' changes temporarly the -/// uid/gid to those of the target user (usr). -/// If OK, returns pass length and fill 'pass' with the password, null-terminated. -/// ('pass' is allocated externally to contain max lpwmax bytes). -/// If the file does not exists, return 0 and an empty pass. -/// If any problems with the file occurs, return a negative -/// code, -2 indicating wrong file permissions. -/// If any problem with changing ugid's occurs, prints a warning trying anyhow -/// to read the password hash. - -int RpdRetrieveSpecialPass(const char *usr, const char *fpw, char *pass, int lpwmax) -{ - int rc = -1; - int len = 0, n = 0, fid = -1; - - // Check inputs - if (!usr || !pass) { - if (gDebug > 0) - ErrorInfo("RpdRetrieveSpecialPass: invalid arguments:" - " us:%p, sp:%p", usr, pass); - return rc; - } - - struct passwd *pw = getpwnam(usr); - if (!pw) { - if (gDebug > 0) - ErrorInfo("RpdRetrieveSpecialPass: user '%s' does not exist", usr); - return rc; - } - - // target and actual uid - int uid = pw->pw_uid; - int ouid = getuid(); - - // Temporary change to target user ID to avoid NFS squashing problems - if (ouid == 0) { - - // set access control list from /etc/initgroup - if (initgroups(pw->pw_name, pw->pw_gid) == -1) - ErrorInfo("RpdRetrieveSpecialPass: can't initgroups for uid %d" - " (errno: %d)", uid, GetErrno()); - // set uid and gid - if (setresgid(pw->pw_gid, pw->pw_gid, 0) == -1) - ErrorInfo("RpdRetrieveSpecialPass: can't setgid for gid %d" - " (errno: %d)", pw->pw_gid, GetErrno()); - if (setresuid(pw->pw_uid, pw->pw_uid, 0) == -1) - ErrorInfo("RpdRetrieveSpecialPass: can't setuid for uid %d" - " (errno: %d)", uid, GetErrno()); - } - - // The file now - char rootdpass[kMAXPATHLEN]; - SPrintf(rootdpass, kMAXPATHLEN, "%s/%s", pw->pw_dir, fpw); - - if (gDebug > 0) - ErrorInfo - ("RpdRetrieveSpecialPass: checking file %s for user %s",rootdpass, - pw->pw_name); - - - if ((fid = open(rootdpass, O_RDONLY)) == -1) { - ErrorInfo("RpdRetrieveSpecialPass: cannot open password file" - " %s (errno: %d)", rootdpass, GetErrno()); - rc = -1; - goto back; - } - // Check first the permissions: should be 0600 - struct stat st; - if (fstat(fid, &st) == -1) { - ErrorInfo("RpdRetrieveSpecialPass: cannot stat descriptor %d" - " %s (errno: %d)", fid, GetErrno()); - close(fid); - rc = -1; - goto back; - } - if (!S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) || - (st.st_mode & (S_IWGRP | S_IWOTH | S_IRGRP | S_IROTH)) != 0) { - ErrorInfo("RpdRetrieveSpecialPass: pass file %s: wrong permissions" - " 0%o (should be 0600)", rootdpass, (st.st_mode & 0777)); - ErrorInfo("RpdRetrieveSpecialPass: %d %d", - S_ISREG(st.st_mode),S_ISDIR(st.st_mode)); - close(fid); - rc = -2; - goto back; - } - - if ((n = read(fid, pass, lpwmax - 1)) <= 0) { - close(fid); - ErrorInfo("RpdRetrieveSpecialPass: cannot read password file" - " %s (errno: %d)", rootdpass, GetErrno()); - rc = -1; - goto back; - } - close(fid); - - // Get rid of special trailing chars - len = n; - while (len-- && (pass[len] == '\n' || pass[len] == 32)) - pass[len] = 0; - - // Null-terminate - pass[++len] = 0; - rc = len; - - back: - // Change back uid's - if (ouid == 0) { - // set uid and gid - if (setresgid(0, 0, 0) == -1) - ErrorInfo("RpdRetrieveSpecialPass: can't re-setgid for gid 0" - " (errno: %d)", GetErrno()); - if (setresuid(0, 0, 0) == -1) - ErrorInfo("RpdRetrieveSpecialPass: can't re-setuid for uid 0" - " (errno: %d)", GetErrno()); - } - - // We are done - return rc; -} - -} // namespace ROOT From 3a1d49f12e6314979f589845f810704e18355b07 Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 22:23:32 +0200 Subject: [PATCH 09/11] [core] remove deprecated TVirtualAuth --- core/base/CMakeLists.txt | 1 - core/base/inc/LinkDef3.h | 1 - core/base/inc/TVirtualAuth.h | 51 ------------------------------------ net/net/src/TSocket.cxx | 1 - 4 files changed, 54 deletions(-) delete mode 100644 core/base/inc/TVirtualAuth.h diff --git a/core/base/CMakeLists.txt b/core/base/CMakeLists.txt index c78f15eed82d1..e31697bcebe70 100644 --- a/core/base/CMakeLists.txt +++ b/core/base/CMakeLists.txt @@ -99,7 +99,6 @@ set(BASE_HEADERS TUrl.h TUUID.h TVersionCheck.h - TVirtualAuth.h TVirtualFFT.h TVirtualGL.h TVirtualMonitoring.h diff --git a/core/base/inc/LinkDef3.h b/core/base/inc/LinkDef3.h index 886df79ea99d8..abfa3f571dd01 100644 --- a/core/base/inc/LinkDef3.h +++ b/core/base/inc/LinkDef3.h @@ -163,7 +163,6 @@ #pragma link C++ class TFileInfo+; #pragma link C++ class TFileInfoMeta+; #pragma link C++ class TFileCollection+; -#pragma link C++ class ROOT::Deprecated::TVirtualAuth; #pragma link C++ class TVirtualMutex; #pragma link C++ class ROOT::TVirtualRWMutex; #pragma link C++ class TLockGuard; diff --git a/core/base/inc/TVirtualAuth.h b/core/base/inc/TVirtualAuth.h deleted file mode 100644 index fe87432830e28..0000000000000 --- a/core/base/inc/TVirtualAuth.h +++ /dev/null @@ -1,51 +0,0 @@ -// Author: G. Ganis 08/07/05 - -/************************************************************************* - * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_TVirtualAuth -#define ROOT_TVirtualAuth - -////////////////////////////////////////////////////////////////////////// -// // -// TVirtualAuth // -// // -// Abstract interface for client authentication code. // -// // -////////////////////////////////////////////////////////////////////////// - -#include "Rtypes.h" - -class TSocket; - -namespace ROOT::Deprecated { - -class TSecContext; - -class TVirtualAuth { - -public: - TVirtualAuth() {} - virtual ~TVirtualAuth() {} - - virtual TSecContext *Authenticate(TSocket *, const char *host, - const char *user, Option_t *options) = 0; - virtual Int_t ClientVersion() = 0; - virtual void ErrorMsg(const char *where, Int_t ecode) = 0; - virtual const char *Name() = 0; - - ClassDef(TVirtualAuth,0) // client auth interface -}; - -} // namespace ROOT::Deprecated - -using TVirtualAuth R__DEPRECATED(6, 42, "TVirtualAuth is deprecated. ROOT will not provide " - "socket authentication anymore but assumes that TSocket connections are between trusted processes. " - "Consider using SSH tunneling if you need secure network connections.") = ROOT::Deprecated::TVirtualAuth; - -#endif diff --git a/net/net/src/TSocket.cxx b/net/net/src/TSocket.cxx index 04ae654abe46d..ee0045da625ba 100644 --- a/net/net/src/TSocket.cxx +++ b/net/net/src/TSocket.cxx @@ -33,7 +33,6 @@ TUnixSystem or TWinNTSystem). #include "TString.h" #include "TSystem.h" #include "TUrl.h" -#include "TVirtualAuth.h" #include "TStreamerInfo.h" #include "TProcessID.h" From 3316b81aaead4fb37425f77bc762beb63ef2aa33 Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 22:18:23 +0200 Subject: [PATCH 10/11] [net] remove deprecated security context from T(Server)Socket --- net/net/inc/TServerSocket.h | 4 +--- net/net/inc/TSocket.h | 19 +------------------ net/net/src/TPSocket.cxx | 1 - net/net/src/TServerSocket.cxx | 19 +------------------ net/net/src/TSocket.cxx | 19 ------------------- 5 files changed, 3 insertions(+), 59 deletions(-) diff --git a/net/net/inc/TServerSocket.h b/net/net/inc/TServerSocket.h index 65081a509288d..cc401ce438809 100644 --- a/net/net/inc/TServerSocket.h +++ b/net/net/inc/TServerSocket.h @@ -33,9 +33,7 @@ class TSeqCollection; class TServerSocket : public TSocket { private: - TSeqCollection *fSecContexts; // List of TSecContext with cleanup info - - TServerSocket() : fSecContexts(nullptr) {} + TServerSocket() = default; TServerSocket(const TServerSocket &); void operator=(const TServerSocket &); diff --git a/net/net/inc/TSocket.h b/net/net/inc/TSocket.h index 74a250e4ea02d..7a9b66b165a90 100644 --- a/net/net/inc/TSocket.h +++ b/net/net/inc/TSocket.h @@ -30,24 +30,15 @@ #include "TBits.h" #include "TInetAddress.h" #include "MessageTypes.h" -#include "TSecContext.h" #include "TTimeStamp.h" #include "TVirtualMutex.h" class TMessage; class TSocket; -namespace ROOT::Deprecated { -struct TSocketFriend { - static void SetSecContext(TSocket &s, TSecContext *ctx); - static TSecContext *GetSecContext(const TSocket &s); -}; -} // namespace ROOT::Deprecated - class TSocket : public TNamed { friend class TServerSocket; -friend struct ROOT::Deprecated::TSocketFriend; public: enum EStatusBits { kIsUnix = BIT(16), // set if unix socket @@ -75,8 +66,6 @@ friend struct ROOT::Deprecated::TSocketFriend; Int_t fCompress; // Compression level and algorithm TInetAddress fLocalAddress; // local internet address and port # Int_t fRemoteProtocol; // protocol of remote daemon - ROOT::Deprecated::TSecContext *fSecContext; // after a successful Authenticate call - // points to related security context TString fService; // name of service (matches remote port #) EServiceType fServType; // remote service type Int_t fSocket; // socket descriptor @@ -94,7 +83,7 @@ friend struct ROOT::Deprecated::TSocketFriend; static Int_t fgClientProtocol; // client "protocol" version TSocket() : fAddress(), fBytesRecv(0), fBytesSent(0), fCompress(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal), - fLocalAddress(), fRemoteProtocol(), fSecContext(nullptr), fService(), + fLocalAddress(), fRemoteProtocol(), fService(), fServType(kSOCKD), fSocket(-1), fTcpWindowSize(0), fUrl(), fBitsInfo(), fUUIDs(nullptr), fLastUsageMtx(nullptr), fLastUsage() {} @@ -136,9 +125,6 @@ friend struct ROOT::Deprecated::TSocketFriend; Int_t GetErrorCode() const; virtual Int_t GetOption(ESockOptions opt, Int_t &val); Int_t GetRemoteProtocol() const { return fRemoteProtocol; } - ROOT::Deprecated::TSecContext *GetSecContext() const - R__DEPRECATED(6, 42, "TSocket::GetSecContext is deprecated") - { return ROOT::Deprecated::TSocketFriend::GetSecContext(*this); } Int_t GetTcpWindowSize() const { return fTcpWindowSize; } TTimeStamp GetLastUsage() { R__LOCKGUARD2(fLastUsageMtx); return fLastUsage; } const char *GetUrl() const { return fUrl.Data(); } @@ -162,9 +148,6 @@ friend struct ROOT::Deprecated::TSocketFriend; void SetCompressionSettings(Int_t settings = ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault); virtual Int_t SetOption(ESockOptions opt, Int_t val); void SetRemoteProtocol(Int_t rproto) { fRemoteProtocol = rproto; } - void SetSecContext(ROOT::Deprecated::TSecContext *ctx) - R__DEPRECATED(6, 42, "TSocket::SetSecContext is deprecated") - { ROOT::Deprecated::TSocketFriend::SetSecContext(*this, ctx); } void SetService(const char *service) { fService = service; } void SetServType(Int_t st) { fServType = (EServiceType)st; } void SetUrl(const char *url) { fUrl = url; } diff --git a/net/net/src/TPSocket.cxx b/net/net/src/TPSocket.cxx index 1895140674716..a5e180dc32e70 100644 --- a/net/net/src/TPSocket.cxx +++ b/net/net/src/TPSocket.cxx @@ -154,7 +154,6 @@ TPSocket::TPSocket(const char *host, Int_t /* port */, Int_t size, TSocket *sock fBytesSent = sock->GetBytesSent(); fBytesRecv = sock->GetBytesRecv(); fCompress = sock->GetCompressionSettings(); - fSecContext = ROOT::Deprecated::TSocketFriend::GetSecContext(*sock); fRemoteProtocol = sock->GetRemoteProtocol(); fServType = (TSocket::EServiceType)sock->GetServType(); fTcpWindowSize = sock->GetTcpWindowSize(); diff --git a/net/net/src/TServerSocket.cxx b/net/net/src/TServerSocket.cxx index d31f9455234af..848c652a875b8 100644 --- a/net/net/src/TServerSocket.cxx +++ b/net/net/src/TServerSocket.cxx @@ -31,9 +31,6 @@ to the requester. The actual work is done via the TSystem class #include "TROOT.h" #include "TError.h" #include -#include "TVirtualMutex.h" - -TVirtualMutex *gSrvAuthenticateMutex = 0; //////////////////////////////////////////////////////////////////////////////// /// Create a server socket object for a named service. Set reuse to true @@ -64,9 +61,6 @@ TServerSocket::TServerSocket(const char *service, Bool_t reuse, Int_t backlog, SetName("ServerSocket"); - fSecContext = 0; - fSecContexts = new TList; - // If this is a local path, try announcing a UNIX socket service ResetBit(TSocket::kIsUnix); if (service && (!gSystem->AccessPathName(service) || @@ -129,8 +123,6 @@ TServerSocket::TServerSocket(Int_t port, Bool_t reuse, Int_t backlog, Int_t tcpw SetName("ServerSocket"); - fSecContext = 0; - fSecContexts = new TList; fService = gSystem->GetServiceByPort(port); SetTitle(fService); @@ -142,18 +134,10 @@ TServerSocket::TServerSocket(Int_t port, Bool_t reuse, Int_t backlog, Int_t tcpw } //////////////////////////////////////////////////////////////////////////////// -/// Destructor: cleanup authentication stuff (if any) and close +/// Destructor: close connection TServerSocket::~TServerSocket() { - R__LOCKGUARD2(gSrvAuthenticateMutex); - if (fSecContexts) { - // Remove the list - fSecContexts->Delete(); - SafeDelete(fSecContexts); - fSecContexts = 0; - } - Close(); } @@ -180,7 +164,6 @@ TSocket *TServerSocket::Accept(UChar_t /* opt */) if (soc == -2) { delete socket; return (TSocket*) -1; } socket->fSocket = soc; - socket->fSecContext = 0; socket->fService = fService; if (!TestBit(TSocket::kIsUnix)) socket->fAddress = gSystem->GetPeerName(socket->fSocket); diff --git a/net/net/src/TSocket.cxx b/net/net/src/TSocket.cxx index ee0045da625ba..8947ae1de0a38 100644 --- a/net/net/src/TSocket.cxx +++ b/net/net/src/TSocket.cxx @@ -38,17 +38,6 @@ TUnixSystem or TWinNTSystem). #include -void ROOT::Deprecated::TSocketFriend::SetSecContext(TSocket &s, TSecContext *ctx) -{ - s.fSecContext = ctx; -} - -ROOT::Deprecated::TSecContext *ROOT::Deprecated::TSocketFriend::GetSecContext(const TSocket &s) -{ - return s.fSecContext; -} - - ULong64_t TSocket::fgBytesSent = 0; ULong64_t TSocket::fgBytesRecv = 0; @@ -89,7 +78,6 @@ TSocket::TSocket(TInetAddress addr, const char *service, Int_t tcpwindowsize) R__ASSERT(gSystem); fService = service; - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; if (fService.Contains("root")) @@ -132,7 +120,6 @@ TSocket::TSocket(TInetAddress addr, Int_t port, Int_t tcpwindowsize) R__ASSERT(gSystem); fService = gSystem->GetServiceByPort(port); - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; if (fService.Contains("root")) @@ -173,7 +160,6 @@ TSocket::TSocket(const char *host, const char *service, Int_t tcpwindowsize) R__ASSERT(gSystem); fService = service; - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; if (fService.Contains("root")) @@ -227,7 +213,6 @@ TSocket::TSocket(const char *url, Int_t port, Int_t tcpwindowsize) TString host(TUrl(fUrl).GetHost()); fService = gSystem->GetServiceByPort(port); - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; if (fUrl.Contains("root")) @@ -267,7 +252,6 @@ TSocket::TSocket(const char *sockpath) : TNamed(sockpath, ""), fUrl = sockpath; fService = "unix"; - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; fAddress.fPort = -1; @@ -295,7 +279,6 @@ TSocket::TSocket(Int_t desc) : TNamed("", ""), fCompress(ROOT::RCompressionSetti R__ASSERT(gROOT); R__ASSERT(gSystem); - fSecContext = 0; fRemoteProtocol = 0; fService = (char *)kSOCKD; fServType = kSOCKD; @@ -328,7 +311,6 @@ TSocket::TSocket(Int_t desc, const char *sockpath) : TNamed(sockpath, ""), fUrl = sockpath; fService = "unix"; - fSecContext = 0; fRemoteProtocol= -1; fServType = kSOCKD; fAddress.fPort = -1; @@ -361,7 +343,6 @@ TSocket::TSocket(const TSocket &s) : TNamed(s) fBytesSent = s.fBytesSent; fBytesRecv = s.fBytesRecv; fCompress = s.fCompress; - fSecContext = s.fSecContext; fRemoteProtocol = s.fRemoteProtocol; fServType = s.fServType; fTcpWindowSize = s.fTcpWindowSize; From 6e91d9eeedcc3351fc198cac56a75a23a5728b13 Mon Sep 17 00:00:00 2001 From: Jakob Blomer Date: Thu, 30 Apr 2026 22:34:46 +0200 Subject: [PATCH 11/11] [core] remove deprecated TSecContext --- core/base/inc/TROOT.h | 9 - core/base/src/TROOT.cxx | 9 - net/net/CMakeLists.txt | 2 - net/net/inc/LinkDef.h | 2 - net/net/inc/TSecContext.h | 153 ---------------- net/net/src/TSecContext.cxx | 337 ------------------------------------ 6 files changed, 512 deletions(-) delete mode 100644 net/net/inc/TSecContext.h delete mode 100644 net/net/src/TSecContext.cxx diff --git a/core/base/inc/TROOT.h b/core/base/inc/TROOT.h index 80e6b00639cbd..db22582c668cd 100644 --- a/core/base/inc/TROOT.h +++ b/core/base/inc/TROOT.h @@ -104,15 +104,10 @@ namespace ROOT { } // namespace Experimental } -namespace ROOT::Deprecated::Internal { -TSeqCollection *GetListOfSecContexts(const TROOT &); -} // namespace ROOT::Deprecated::Internal - class TROOT : public TDirectory { friend class TCling; friend TROOT *ROOT::Internal::GetROOT2(); -friend TSeqCollection *ROOT::Deprecated::Internal::GetListOfSecContexts(const TROOT &); private: Int_t fLineIsProcessing = 0; ///< To synchronize multi-threads @@ -176,7 +171,6 @@ friend TSeqCollection *ROOT::Deprecated::Internal::GetListOfSecContexts(const TR TSeqCollection *fMessageHandlers = nullptr; ///< List of message handlers TSeqCollection *fStreamerInfo = nullptr; ///< List of active StreamerInfo classes TCollection *fClassGenerators = nullptr; ///< List of user defined class generators; - TSeqCollection *fSecContexts = nullptr; ///< List of security contexts (TSecContext) TSeqCollection *fClipboard = nullptr; ///< List of clipboard objects TSeqCollection *fDataSets = nullptr; ///< List of data sets (TDSet or TChain) AListOfEnums_t fEnums = nullptr; ///< List of enum types @@ -266,9 +260,6 @@ friend TSeqCollection *ROOT::Deprecated::Internal::GetListOfSecContexts(const TR TSeqCollection *GetListOfStreamerInfo() const { return fStreamerInfo; } TSeqCollection *GetListOfMessageHandlers() const { return fMessageHandlers; } TCollection *GetListOfClassGenerators() const { return fClassGenerators; } - TSeqCollection *GetListOfSecContexts() const - R__DEPRECATED(6, 42, "GetListOfSecContexts is deprecated. See README.AUTH for details.") - { return ROOT::Deprecated::Internal::GetListOfSecContexts(*this); } TSeqCollection *GetClipboard() const { return fClipboard; } TSeqCollection *GetListOfDataSets() const { return fDataSets; } TCollection *GetListOfEnums(Bool_t load = kFALSE); diff --git a/core/base/src/TROOT.cxx b/core/base/src/TROOT.cxx index ad60ba90bfc15..9ee7e332ca2b3 100644 --- a/core/base/src/TROOT.cxx +++ b/core/base/src/TROOT.cxx @@ -31,7 +31,6 @@ The following lists are accessible from gROOT object: gROOT->GetListOfFiles gROOT->GetListOfMappedFiles gROOT->GetListOfSockets - gROOT->GetListOfSecContexts gROOT->GetListOfCanvases gROOT->GetListOfStyles gROOT->GetListOfFunctions @@ -172,11 +171,6 @@ FARPROC dlsym(void *library, const char *function_name) #include "TWinNTSystem.h" #endif -TSeqCollection *ROOT::Deprecated::Internal::GetListOfSecContexts(const TROOT &r) -{ - return r.fSecContexts; -} - extern "C" void R__SetZipMode(int); static DestroyInterpreter_t *gDestroyInterpreter = nullptr; @@ -910,7 +904,6 @@ TROOT::TROOT(const char *name, const char *title, VoidFuncPtr_t *initfunc) : TDi fBrowsables = (TList*)setNameLocked(new TList, "Browsables"); fCleanups = setNameLocked(new THashList, "Cleanups"); fMessageHandlers = setNameLocked(new TList, "MessageHandlers"); - fSecContexts = setNameLocked(new TList, "SecContexts"); fClipboard = setNameLocked(new TList, "Clipboard"); fDataSets = setNameLocked(new TList, "DataSets"); fTypes = new TListOfTypes; fTypes->UseRWLock(); @@ -935,7 +928,6 @@ TROOT::TROOT(const char *name, const char *title, VoidFuncPtr_t *initfunc) : TDi fRootFolder->AddFolder("Handlers", "List of Message Handlers",fMessageHandlers); fRootFolder->AddFolder("Cleanups", "List of RecursiveRemove Collections",fCleanups); fRootFolder->AddFolder("StreamerInfo","List of Active StreamerInfo Classes",fStreamerInfo); - fRootFolder->AddFolder("SecContexts","List of Security Contexts",fSecContexts); fRootFolder->AddFolder("ROOT Memory","List of Objects in the gROOT Directory",fList); fRootFolder->AddFolder("ROOT Files","List of Connected ROOT Files",fFiles); @@ -1068,7 +1060,6 @@ TROOT::~TROOT() fClosedObjects->Delete("slow"); // and closed files fFiles->Delete("slow"); // and files SafeDelete(fFiles); - fSecContexts->Delete("slow"); SafeDelete(fSecContexts); // and security contexts fSockets->Delete(); SafeDelete(fSockets); // and sockets fMappedFiles->Delete("slow"); // and mapped files TSeqCollection *tl = fMappedFiles; fMappedFiles = nullptr; delete tl; diff --git a/net/net/CMakeLists.txt b/net/net/CMakeLists.txt index 19593b177dd56..7dab764e74190 100644 --- a/net/net/CMakeLists.txt +++ b/net/net/CMakeLists.txt @@ -37,7 +37,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(Net TParallelMergingFile.h TPServerSocket.h TPSocket.h - TSecContext.h TServerSocket.h TSocket.h TSQLColumnInfo.h @@ -59,7 +58,6 @@ ROOT_STANDARD_LIBRARY_PACKAGE(Net src/TParallelMergingFile.cxx src/TPServerSocket.cxx src/TPSocket.cxx - src/TSecContext.cxx src/TServerSocket.cxx src/TSocket.cxx src/TSQLColumnInfo.cxx diff --git a/net/net/inc/LinkDef.h b/net/net/inc/LinkDef.h index b059debfc4915..1f381b0a895c4 100644 --- a/net/net/inc/LinkDef.h +++ b/net/net/inc/LinkDef.h @@ -27,8 +27,6 @@ #pragma link C++ class TSQLTableInfo; #pragma link C++ class TSQLColumnInfo; #pragma link C++ class TSQLMonitoringWriter; -#pragma link C++ class ROOT::Deprecated::TSecContext; -#pragma link C++ class ROOT::Deprecated::TSecContextCleanup; #pragma link C++ class TFileStager; #pragma link C++ class TApplicationRemote; #pragma link C++ class TApplicationServer; diff --git a/net/net/inc/TSecContext.h b/net/net/inc/TSecContext.h deleted file mode 100644 index 1dde1a5cd9e4c..0000000000000 --- a/net/net/inc/TSecContext.h +++ /dev/null @@ -1,153 +0,0 @@ -// @(#)root/net:$Id$ -// Author: G. Ganis 31/03/2003 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -#ifndef ROOT_TSecContext -#define ROOT_TSecContext - - -////////////////////////////////////////////////////////////////////////// -// // -// TSecContext // -// // -// Contains details about successful authentications // -// Used by THostAuth // -// // -////////////////////////////////////////////////////////////////////////// - -#include "TObject.h" -#include "TString.h" -#include "TDatime.h" - -// Jan 1, 1995, 00:00:00 in sec from EPOCH (Jan 1, 1970) -R__EXTERN const TDatime kROOTTZERO; - -namespace ROOT::Deprecated { - -class TRootSecContext; - -class TSecContext : public TObject { - -friend class ROOT::Deprecated::TRootSecContext; - -private: - void *fContext; // ptr to specific sec context - TList *fCleanup; // Points to list with info for remote cleanup - TDatime fExpDate; // Expiring date (one sec precision) - TString fHost; // Remote host name - TString fID; // String identifying uniquely this context - Int_t fMethod; // Authentication method used - TString fMethodName; // Authentication method name - Int_t fOffSet; // offset in remote host auth tab file (in bytes) - TString fToken; // Token identifying this authentication - TString fUser; // Remote login username - - virtual Bool_t CleanupSecContext(Bool_t all); - void Cleanup(); - -protected: - TSecContext(const TSecContext&); - TSecContext& operator=(const TSecContext&); - -public: - - TSecContext(const char *url, Int_t meth, Int_t offset, - const char *id, const char *token, - TDatime expdate = kROOTTZERO, void *ctx = nullptr); - TSecContext(const char *user, const char *host, Int_t meth, Int_t offset, - const char *id, const char *token, - TDatime expdate = kROOTTZERO, void *ctx = nullptr); - virtual ~TSecContext(); - - void AddForCleanup(Int_t port, Int_t proto, Int_t type); - virtual const char *AsString(TString &out); - - virtual void DeActivate(Option_t *opt = "CR"); - void *GetContext() const { return fContext; } - TDatime GetExpDate() const { return fExpDate; } - const char *GetHost() const { return fHost; } - const char *GetID() const { return fID; } - Int_t GetMethod() const { return fMethod; } - const char *GetMethodName() const { return fMethodName; } - Int_t GetOffSet() const { return fOffSet; } - TList *GetSecContextCleanup() const { return fCleanup; } - const char *GetToken() const { return fToken; } - const char *GetUser() const { return fUser; } - - Bool_t IsA(const char *methodname); - Bool_t IsActive() const; - - void Print(Option_t *option = "F") const override; - - void SetExpDate(TDatime expdate) { fExpDate= expdate; } - void SetID(const char *id) { fID= id; } - void SetOffSet(Int_t offset) { fOffSet = offset; } - void SetUser(const char *user) { fUser = user; } - - ClassDefOverride(TSecContext,0) // Class providing host specific authentication information -}; - -// -// TSecContextCleanup -// -// When the context is destroyed the remote authentication table -// should be updated; for this we need to open a socket to a remote -// service; we keep track here of port and type of socket needed by -// the remote service used in connection with this security context. -// The last used is the first in the list. -// This info is used in TAuthenticate::CleanupSecContext to trasmit -// the actual cleanup request -// -class TSecContextCleanup : public TObject { - -private: - Int_t fPort; - Int_t fServerProtocol; - Int_t fServerType; // 0 = sockd, 1 = rootd - -public: - TSecContextCleanup(Int_t port, Int_t proto, Int_t type) : - fPort(port), fServerProtocol(proto), fServerType(type) { }; - virtual ~TSecContextCleanup() { }; - - Int_t GetPort() const { return fPort; } - Int_t GetProtocol() const { return fServerProtocol; } - Int_t GetType() const { return fServerType; } - - ClassDefOverride(TSecContextCleanup,0) //Update the remote authentication table -}; - -// -// TPwdCtx -// -// To store associated passwd for UsrPwd method -// -class TPwdCtx { - -private: - TString fPasswd; - Bool_t fPwHash; - -public: - TPwdCtx(const char *pwd, Bool_t pwh): fPasswd(pwd), fPwHash(pwh) {}; - virtual ~TPwdCtx() {}; - - const char *GetPasswd() const { return fPasswd; } - Bool_t IsPwHash() const { return fPwHash; } - -}; - -} // namespace ROOT::Deprecated - -using TSecContext R__DEPRECATED(6, 42, "TSecContext is deprecated") = ROOT::Deprecated::TSecContext; -using TSecContextCleanup R__DEPRECATED(6, 42, "TPwdCtx is deprecated") = ROOT::Deprecated::TSecContextCleanup; -using TPwdCtx R__DEPRECATED(6, 42, "TPwdCtx is deprecated") = ROOT::Deprecated::TPwdCtx; - -#endif diff --git a/net/net/src/TSecContext.cxx b/net/net/src/TSecContext.cxx deleted file mode 100644 index d8c87d5b62f96..0000000000000 --- a/net/net/src/TSecContext.cxx +++ /dev/null @@ -1,337 +0,0 @@ -// @(#)root/net:$Id$ -// Author: G. Ganis 19/03/2003 - -/************************************************************************* - * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * - * All rights reserved. * - * * - * For the licensing terms see $ROOTSYS/LICENSE. * - * For the list of contributors see $ROOTSYS/README/CREDITS. * - *************************************************************************/ - -////////////////////////////////////////////////////////////////////////// -// // -// TSecContext // -// // -// Contains details about an established security context // -// Used by THostAuth // -// // -////////////////////////////////////////////////////////////////////////// - -#include "RConfigure.h" - -#include - -#include "strlcpy.h" -#include "snprintf.h" -#include "TSecContext.h" -#include "TSocket.h" -#include "TUrl.h" -#include "TROOT.h" -#include "TError.h" -#include "TVirtualMutex.h" - - -const TDatime kROOTTZERO = 788914800; - -//////////////////////////////////////////////////////////////////////////////// -/// Ctor for SecContext object. - -ROOT::Deprecated::TSecContext::TSecContext(const char *user, const char *host, Int_t meth, - Int_t offset, const char *id, - const char *token, TDatime expdate, void *ctx) - : TObject() -{ - R__ASSERT(gROOT); - - fContext = ctx; - fCleanup = new TList; - fExpDate = expdate; - if (offset > -1) { - if (fExpDate < TDatime()) { - // This means expdate was not initialized - // We set it to default, ie 1 day from now - fExpDate.Set(TDatime().GetDate() + 1, TDatime().GetTime()); - } - } - fHost = host; - fID = id; - fMethod = meth; - fMethodName = ""; - fOffSet = offset; - fToken = token; - fUser = user; - - // Keep official list updated with active TSecContexts - if (fOffSet > -1) { - R__LOCKGUARD(gROOTMutex); - ROOT::Deprecated::Internal::GetListOfSecContexts(*gROOT)->Add(this); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Ctor for SecContext object. -/// User and host from url = `user@host` . - -ROOT::Deprecated::TSecContext::TSecContext(const char *url, Int_t meth, Int_t offset, - const char *token, const char *id, - TDatime expdate, void *ctx) - : TObject() -{ - R__ASSERT(gROOT); - - fContext = ctx; - fCleanup = new TList; - fExpDate = expdate; - if (offset > -1) { - if (fExpDate < TDatime()) { - // This means expdate was not initialized - // We set it to default, ie 1 day from now - fExpDate.Set(TDatime().GetDate() + 1, TDatime().GetTime()); - } - } - fHost = TUrl(url).GetHost(); - fID = id; - fMethod = meth; - fMethodName = ""; - fOffSet = offset; - fToken = token; - fUser = TUrl(url).GetUser(); - - // Keep official list updated with active TSecContexts - if (fOffSet > -1) { - R__LOCKGUARD(gROOTMutex); - ROOT::Deprecated::Internal::GetListOfSecContexts(*gROOT)->Add(this); - } -} - -//////////////////////////////////////////////////////////////////////////////// -///copy constructor - -ROOT::Deprecated::TSecContext::TSecContext(const TSecContext& sc) : - TObject(sc), - fContext(sc.fContext), - fCleanup(sc.fCleanup), - fExpDate(sc.fExpDate), - fHost(sc.fHost), - fID(sc.fID), - fMethod(sc.fMethod), - fMethodName(sc.fMethodName), - fOffSet(sc.fOffSet), - fToken(sc.fToken), - fUser(sc.fUser) -{ -} - -//////////////////////////////////////////////////////////////////////////////// -///assignement operator - -ROOT::Deprecated::TSecContext& ROOT::Deprecated::TSecContext::operator=(const TSecContext& sc) -{ - if(this!=&sc) { - TObject::operator=(sc); - fContext=sc.fContext; - fCleanup=sc.fCleanup; - fExpDate=sc.fExpDate; - fHost=sc.fHost; - fID=sc.fID; - fMethod=sc.fMethod; - fMethodName=sc.fMethodName; - fOffSet=sc.fOffSet; - fToken=sc.fToken; - fUser=sc.fUser; - } - return *this; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Dtor: delete (deActivate, local/remote cleanup, list removal) -/// all what is still active - -ROOT::Deprecated::TSecContext::~TSecContext() -{ - Cleanup(); -} -//////////////////////////////////////////////////////////////////////////////// -/// Cleanup what is still active - -void ROOT::Deprecated::TSecContext::Cleanup() -{ - if (IsActive()) { - CleanupSecContext(kTRUE); - DeActivate("R"); - // All have been remotely Deactivated - TIter nxtl(ROOT::Deprecated::Internal::GetListOfSecContexts(*gROOT)); - TSecContext *nscl; - while ((nscl = (TSecContext *)nxtl())) { - if (nscl != this && !strcmp(nscl->GetHost(), fHost.Data())) { - // Need to set ofs=-1 to avoid sending another - // cleanup request - nscl->DeActivate(""); - } - } - } - - // Delete the cleanup list - if (fCleanup) { - fCleanup->Delete(); - delete fCleanup; - fCleanup = 0; - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Set OffSet to -1 and expiring Date to default -/// Remove from the list -/// If Opt contains "C" or "c", ask for remote cleanup -/// If Opt contains "R" or "r", remove from the list -/// Default Opt="CR" - -void ROOT::Deprecated::TSecContext::DeActivate(Option_t *Opt) -{ - // Ask remote cleanup of this context - Bool_t clean = (strstr(Opt,"C") || strstr(Opt,"c")); - if (clean && fOffSet > -1) - CleanupSecContext(kFALSE); - - Bool_t remove = (strstr(Opt,"R") || strstr(Opt,"r")); - if (remove && fOffSet > -1){ - R__LOCKGUARD(gROOTMutex); - // Remove from the global list - ROOT::Deprecated::Internal::GetListOfSecContexts(*gROOT)->Remove(this); - } - - // Set inactive - fOffSet = -1; - fExpDate = kROOTTZERO; -} - -//////////////////////////////////////////////////////////////////////////////// -/// Create a new TSecContextCleanup -/// Internally is added to the list - -void ROOT::Deprecated::TSecContext::AddForCleanup(Int_t port, Int_t proto, Int_t type) -{ - auto *tscc = new ROOT::Deprecated::TSecContextCleanup(port, proto, type); - fCleanup->Add(tscc); - -} - -//////////////////////////////////////////////////////////////////////////////// -/// Checks if this security context is for method named 'methname' -/// Case sensitive. - -Bool_t ROOT::Deprecated::TSecContext::IsA(const char *methname) -{ - return Bool_t(!strcmp(methname, GetMethodName())); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Check remote OffSet and expiring Date - -Bool_t ROOT::Deprecated::TSecContext::IsActive() const -{ - if (fOffSet > -1 && fExpDate > TDatime()) - return kTRUE; - // Invalid - return kFALSE; -} - -//////////////////////////////////////////////////////////////////////////////// -/// If opt is "F" (default) print object content. -/// If opt is "" print in special form for calls within THostAuth -/// with cardinality "" -/// If opt is "S" prints short in-line form for calls within TFTP and similar - -void ROOT::Deprecated::TSecContext::Print(Option_t *opt) const -{ - char aOrd[16] = {0}; - char aSpc[16] = {0}; - - // Check if option is numeric - Int_t ord = -1, i = 0; - for (; i < (Int_t)strlen(opt); i++) { - if (opt[i] < 48 || opt[i] > 57) { - ord = -2; - break; - } - } - // If numeric get the cardinality and prepare the strings - if (ord == -1) - ord = atoi(opt); - - // If asked to print ordinal number, preapre the string - if (ord > -1) { - snprintf(aOrd, sizeof(aOrd), "%d)", ord); - // and take care of alignment - Int_t len=strlen(aOrd); - while (len--) - strlcat(aSpc, " ", sizeof(aSpc)); - } - - if (!strncasecmp(opt,"F",1)) { - Info("Print", - "+------------------------------------------------------+"); - Info("Print", - "+ Host:%s Method:%d (%s) User:'%s'", - GetHost(), fMethod, GetMethodName(), - fUser.Data()); - Info("Print", - "+ OffSet:%d, id:%s", fOffSet, fID.Data()); - if (fOffSet > -1) - Info("Print", - "+ Expiration time: %s",fExpDate.AsString()); - Info("Print", - "+------------------------------------------------------+"); - } else if (!strncasecmp(opt,"S",1)) { - if (fOffSet > -1) { - Printf("Security context: Method: %d (%s) expiring on %s", - fMethod, GetMethodName(), - fExpDate.AsString()); - } else { - Printf("Security context: Method: %d (%s) not reusable", - fMethod, GetMethodName()); - } - } else { - // special printing form for THostAuth - Info("PrintEstblshed","+ %s h:%s met:%d (%s) us:'%s'", - aOrd, GetHost(), fMethod, GetMethodName(), - fUser.Data()); - Info("PrintEstblshed","+ %s offset:%d id:%s", aSpc, fOffSet, fID.Data()); - if (fOffSet > -1) - Info("PrintEstblshed","+ %s expiring: %s",aSpc,fExpDate.AsString()); - } -} - -//////////////////////////////////////////////////////////////////////////////// -/// Returns short string with relevant information about this -/// security context - -const char *ROOT::Deprecated::TSecContext::AsString(TString &out) -{ - if (fOffSet > -1) { - char expdate[32]; - out = Form("Method: %d (%s) expiring on %s", - fMethod, GetMethodName(), fExpDate.AsString(expdate)); - } else { - if (fOffSet == -1) - out = Form("Method: %d (%s) not reusable", fMethod, GetMethodName()); - else if (fOffSet == -3) - out = Form("Method: %d (%s) authorized by /etc/hosts.equiv or $HOME/.rhosts", - fMethod, GetMethodName()); - else if (fOffSet == -4) - out = Form("No authentication required remotely"); - } - return out.Data(); -} - -//////////////////////////////////////////////////////////////////////////////// -/// Ask remote client to cleanup security context 'ctx' -/// If 'all', all sec context with the same host as ctx -/// are cleaned. - -Bool_t ROOT::Deprecated::TSecContext::CleanupSecContext(Bool_t) -{ - AbstractMethod("CleanupSecContext"); - return kFALSE; -}