XRootD
XrdSecProtocolgsi.cc
Go to the documentation of this file.
1 /******************************************************************************/
2 /* */
3 /* X r d S e c P r o t o c o l g s i . c c */
4 /* */
5 /* (c) 2005 G. Ganis / CERN */
6 /* */
7 /* This file is part of the XRootD software suite. */
8 /* */
9 /* XRootD is free software: you can redistribute it and/or modify it under */
10 /* the terms of the GNU Lesser General Public License as published by the */
11 /* Free Software Foundation, either version 3 of the License, or (at your */
12 /* option) any later version. */
13 /* */
14 /* XRootD is distributed in the hope that it will be useful, but WITHOUT */
15 /* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
16 /* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public */
17 /* License for more details. */
18 /* */
19 /* You should have received a copy of the GNU Lesser General Public License */
20 /* along with XRootD in a file called COPYING.LESSER (LGPL license) and file */
21 /* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */
22 /* */
23 /* The copyright holder's institutional names and contributor's names may not */
24 /* be used to endorse or promote products derived from this software without */
25 /* specific prior written permission of the institution or contributor. */
26 /* */
27 /******************************************************************************/
28 
29 #include <unistd.h>
30 #include <cctype>
31 #include <cerrno>
32 #include <cstdlib>
33 #include <strings.h>
34 #include <cstdio>
35 #include <sys/param.h>
36 #include <pwd.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <fcntl.h>
40 #include <dirent.h>
41 #include <iostream>
42 
43 #include "XrdVersion.hh"
44 
45 #include "XrdNet/XrdNetAddr.hh"
47 #include "XrdSys/XrdSysHeaders.hh"
48 #include "XrdSys/XrdSysLogger.hh"
49 #include "XrdSys/XrdSysError.hh"
51 #include "XrdOuc/XrdOucStream.hh"
52 #include "XrdOuc/XrdOucEnv.hh"
53 
54 #include "XrdSut/XrdSutAux.hh"
55 
59 
62 
63 /******************************************************************************/
64 /* T r a c i n g I n i t O p t i o n s */
65 /******************************************************************************/
66 #ifndef NODEBUG
67 //#define POPTS(t,y) {if (t) {t->Beg(epname); std::cerr <<y; t->End();}}
68 #define POPTS(t,y) {if (t) {std::cerr <<"Secgsi" <<y <<'\n' << std::flush;}}
69 #else
70 #define POPTS(t,y)
71 #endif
72 
73 /******************************************************************************/
74 /* S t a t i c D a t a */
75 /******************************************************************************/
76 
77 static String Prefix = "xrd";
80 
81 static const char *gsiClientSteps[] = {
82  "kXGC_none",
83  "kXGC_certreq",
84  "kXGC_cert",
85  "kXGC_sigpxy",
86  "kXGC_reserved"
87 };
88 
89 static const char *gsiServerSteps[] = {
90  "kXGS_none",
91  "kXGS_init",
92  "kXGS_cert",
93  "kXGS_pxyreq",
94  "kXGS_reserved"
95 };
96 
97 static const char *gGSErrStr[] = {
98  "ErrParseBuffer", // 10000
99  "ErrDecodeBuffer", // 10001
100  "ErrLoadCrypto", // 10002
101  "ErrBadProtocol", // 10003
102  "ErrCreateBucket", // 10004
103  "ErrDuplicateBucket", // 10005
104  "ErrCreateBuffer", // 10006
105  "ErrSerialBuffer", // 10007
106  "ErrGenCipher", // 10008
107  "ErrExportPuK", // 10009
108  "ErrEncRndmTag", // 10010
109  "ErrBadRndmTag", // 10011
110  "ErrNoRndmTag", // 10012
111  "ErrNoCipher", // 10013
112  "ErrNoCreds", // 10014
113  "ErrBadOpt", // 10015
114  "ErrMarshal", // 10016
115  "ErrUnmarshal", // 10017
116  "ErrSaveCreds", // 10018
117  "ErrNoBuffer", // 10019
118  "ErrRefCipher", // 10020
119  "ErrNoPublic", // 10021
120  "ErrAddBucket", // 10022
121  "ErrFinCipher", // 10023
122  "ErrInit", // 10024
123  "ErrBadCreds", // 10025
124  "ErrError" // 10026
125 };
126 
127 // One day in secs
128 static const int kOneDay = 86400;
129 // Default proxy location template
130 static const char *gUsrPxyDef = "/tmp/x509up_u";
131 // Tag for pad support
132 static const char *gNoPadTag = "nopad";
133 // static const char *gPadTag = "&pad";
134 
135 
136 /******************************************************************************/
137 /* S t a t i c C l a s s D a t a */
138 /******************************************************************************/
139 
140 XrdSysMutex XrdSecProtocolgsi::gsiContext;
141 String XrdSecProtocolgsi::CAdir = "/etc/grid-security/certificates/";
142 String XrdSecProtocolgsi::CRLdir = "/etc/grid-security/certificates/";
143 String XrdSecProtocolgsi::DefCRLext= ".r0";
144 String XrdSecProtocolgsi::GMAPFile = "/etc/grid-security/grid-mapfile";
145 String XrdSecProtocolgsi::SrvCert = "/etc/grid-security/xrd/xrdcert.pem";
146 String XrdSecProtocolgsi::SrvKey = "/etc/grid-security/xrd/xrdkey.pem";
147 String XrdSecProtocolgsi::UsrProxy;
148 String XrdSecProtocolgsi::UsrCert = "/.globus/usercert.pem";
149 String XrdSecProtocolgsi::UsrKey = "/.globus/userkey.pem";
150 String XrdSecProtocolgsi::PxyValid = "12:00";
151 int XrdSecProtocolgsi::DepLength= 0;
152 int XrdSecProtocolgsi::DefBits = XrdCryptoDefRSABits;
153 int XrdSecProtocolgsi::CACheck = caVerifyss;
154 int XrdSecProtocolgsi::CRLCheck = crlTry; // 1
155 int XrdSecProtocolgsi::CRLDownload = 0;
156 int XrdSecProtocolgsi::CRLRefresh = 86400;
157 int XrdSecProtocolgsi::GMAPOpt = 1;
158 bool XrdSecProtocolgsi::GMAPuseDNname = 0;
159 String XrdSecProtocolgsi::DefCrypto= "ssl";
160 String XrdSecProtocolgsi::DefCipher= "aes-128-cbc:bf-cbc:des-ede3-cbc";
161 String XrdSecProtocolgsi::DefMD = "sha256";
162 String XrdSecProtocolgsi::DefError = "invalid credentials ";
163 int XrdSecProtocolgsi::PxyReqOpts = 0;
164 int XrdSecProtocolgsi::AuthzPxyWhat = -1;
165 int XrdSecProtocolgsi::AuthzPxyWhere = -1;
166 int XrdSecProtocolgsi::AuthzAlways = 1;
167 XrdSecgsiGMAP_t XrdSecProtocolgsi::GMAPFun = 0;
168 XrdSecgsiAuthz_t XrdSecProtocolgsi::AuthzFun = 0;
169 XrdSecgsiAuthzKey_t XrdSecProtocolgsi::AuthzKey = 0;
170 int XrdSecProtocolgsi::AuthzCertFmt = -1;
171 int XrdSecProtocolgsi::GMAPCacheTimeOut = -1;
172 int XrdSecProtocolgsi::AuthzCacheTimeOut = 43200; // 12h, default
173 String XrdSecProtocolgsi::SrvAllowedNames;
174 int XrdSecProtocolgsi::VOMSAttrOpt = vatIgnore; // Was '1' or extract
175 XrdSecgsiAuthz_t XrdSecProtocolgsi::VOMSFun = 0;
176 int XrdSecProtocolgsi::VOMSCertFmt = -1;
177 int XrdSecProtocolgsi::MonInfoOpt = 0;
178 bool XrdSecProtocolgsi::HashCompatibility = 1;
179 bool XrdSecProtocolgsi::TrustDNS = false;
180 bool XrdSecProtocolgsi::ShowDN = false;
181 //
182 // Crypto related info
183 int XrdSecProtocolgsi::ncrypt = 0; // Number of factories
184 XrdCryptoFactory *XrdSecProtocolgsi::cryptF[XrdCryptoMax] = {0}; // their hooks
185 int XrdSecProtocolgsi::cryptID[XrdCryptoMax] = {0}; // their IDs
186 String XrdSecProtocolgsi::cryptName[XrdCryptoMax] = {0}; // their names
187 XrdCryptoCipher *XrdSecProtocolgsi::refcip[XrdCryptoMax] = {0}; // ref for session ciphers
188 //
189 // Caches
190 XrdSutCache XrdSecProtocolgsi::cacheCA; // Server certificates info cache (default size 144)
191 XrdSutCache XrdSecProtocolgsi::cacheCert(8,13); // Server certificates info cache (Fibonacci-based sizes)
192 XrdSutCache XrdSecProtocolgsi::cachePxy(8,13); // Client proxies cache (Fibonacci-based sizes)
193 XrdSutCache XrdSecProtocolgsi::cacheGMAPFun; // Entries mapped by GMAPFun (default size 144)
194 XrdSutCache XrdSecProtocolgsi::cacheAuthzFun; // Entities filled by AuthzFun (default size 144)
195 //
196 // Services
197 XrdOucGMap *XrdSecProtocolgsi::servGMap = 0; // Grid map service
198 //
199 // CA and CRL stacks
200 GSIStack<XrdCryptoX509Chain> XrdSecProtocolgsi::stackCA; // Stack of CA in use
201 std::unique_ptr<GSIStack<XrdCryptoX509Crl>> XrdSecProtocolgsi::stackCRL( new GSIStack<XrdCryptoX509Crl>() ); // Stack of CRL in use
202 //
203 // GMAP control vars
204 time_t XrdSecProtocolgsi::lastGMAPCheck = -1; // Time of last check
205 XrdSysMutex XrdSecProtocolgsi::mutexGMAP; // Mutex to control GMAP reloads
206 //
207 // Running options / settings
208 int XrdSecProtocolgsi::Debug = 0; // [CS] Debug level
209 bool XrdSecProtocolgsi::Server = 1; // [CS] If server mode
210 int XrdSecProtocolgsi::TimeSkew = 300; // [CS] Allowed skew in secs for time stamps
211 //
212 // Debug an tracing
213 XrdSysError XrdSecProtocolgsi::eDest(0, "secgsi_");
214 XrdSysLogger XrdSecProtocolgsi::Logger;
215 XrdOucTrace *XrdSecProtocolgsi::GSITrace = 0;
216 
218 
219 /******************************************************************************/
220 /* S t a t i c F u n c t i o n s */
221 /******************************************************************************/
222 //_____________________________________________________________________________
223 static const char *ClientStepStr(int kclt)
224 {
225  // Return string with client step
226  static const char *ukn = "Unknown";
227 
228  kclt = (kclt < 0) ? 0 : kclt;
229  kclt = (kclt > kXGC_reserved) ? 0 : kclt;
230  kclt = (kclt >= kXGC_certreq) ? (kclt - kXGC_certreq + 1) : kclt;
231 
232  if (kclt < 0 || kclt > (kXGC_reserved - kXGC_certreq + 1))
233  return ukn;
234  else
235  return gsiClientSteps[kclt];
236 }
237 
238 //_____________________________________________________________________________
239 static const char *ServerStepStr(int ksrv)
240 {
241  // Return string with server step
242  static const char *ukn = "Unknown";
243 
244  ksrv = (ksrv < 0) ? 0 : ksrv;
245  ksrv = (ksrv > kXGS_reserved) ? 0 : ksrv;
246  ksrv = (ksrv >= kXGS_init) ? (ksrv - kXGS_init + 1) : ksrv;
247 
248  if (ksrv < 0 || ksrv > (kXGS_reserved - kXGS_init + 1))
249  return ukn;
250  else
251  return gsiServerSteps[ksrv];
252 }
253 
254 
255 /******************************************************************************/
256 /* D u m p o f H a n d s h a k e v a r i a b l e s */
257 /******************************************************************************/
258 
259 //_____________________________________________________________________________
261 {
262  // Dump content
263  EPNAME("HSVars::Dump");
264 
265  PRINT("----------------------------------------------------------------");
266  PRINT("protocol instance: "<<p);
267  PRINT("this: "<<this);
268  PRINT(" ");
269  PRINT("Time stamp: "<<TimeStamp);
270  PRINT("Crypto mod: "<<CryptoMod);
271  PRINT("Remote version: "<<RemVers);
272  PRINT("Ref cipher: "<<Rcip);
273  PRINT("Cipher padding: "<<HasPad);
274  PRINT("Bucket for exp cert: "<<Cbck);
275  PRINT("Handshake ID: "<<ID);
276  PRINT("Cache reference: "<<Cref);
277  PRINT("Relevant file entry: "<<Pent);
278  PRINT("Chain pointer: "<<Chain);
279  PRINT("CRL pointer: "<<Crl);
280  PRINT("Proxy chain: "<<PxyChain);
281  PRINT("Rndm tag checked: "<<RtagOK);
282  PRINT("Last step: "<<LastStep);
283  PRINT("Options: "<<Options);
284  PRINT("----------------------------------------------------------------");
285 }
286 
287 /******************************************************************************/
288 /* P r o t o c o l I n i t i a l i z a t i o n M e t h o d s */
289 /******************************************************************************/
290 
291 
292 //_____________________________________________________________________________
294  XrdNetAddrInfo &endPoint,
295  const char *parms) : XrdSecProtocol("gsi")
296 {
297  // Default constructor
298  EPNAME("XrdSecProtocolgsi");
299 
300  if (QTRACE(Authen)) { PRINT("constructing: "<<this); }
301 
302  // Create instance of the handshake vars
303  if ((hs = new gsiHSVars())) {
304  // Update time stamp
305  hs->TimeStamp = time(0);
306  // Local handshake variables
307  hs->Tty = (isatty(0) == 0 || isatty(1) == 0) ? 0 : 1;
308  } else {
309  PRINT("could not create handshake vars object");
310  }
311 
312  // Set host name and address
313  // The hostname is critical for the GSI protocol; it must match the potential
314  // names on the remote EEC. We default to the hostname requested by the user to
315  // the client (or proxy). However, as we may have been redirected to an IP
316  // address instead of an actual hostname, we must fallback to a reverse DNS lookup.
317  // As of time of testing (June 2018), EOS will redirect to an IP address to handle
318  // metadata commands and rely on the reverse DNS lookup for GSI security to function.
319  // Hence, this fallback likely needs to be kept for some time.
320  //
321  // We provide servers a switch and clients an environment variable to override all
322  // usage of DNS (processed on XrdSecProtocolgsiInit).
323  // Default is to fallback to DNS lookups in limited
324  // cases for backward compatibility.
325  expectedHost = NULL;
326  if (TrustDNS) {
327  if (!hname || !XrdNetAddrInfo::isHostName(hname)) {
328  Entity.host = strdup(endPoint.Name(""));
329  } else {
330  // At this point, hname still may possibly be a non-qualified domain name.
331  // If there is a '.' character, then we assume it is a qualified domain name --
332  // otherwise, we use DNS.
333  //
334  // NOTE: We can definitively test whether this is a qualified domain name by
335  // simply appending a '.' to `hname` and performing a lookup. However, this
336  // causes DNS to be used by every lookup - meaning we rely on the security
337  // of DNS for all cases; we want to avoid this.
338  if (strchr(hname, '.')) {
339  // We have a valid hostname; proceed.
340  Entity.host = strdup(hname);
341  } else {
342  XrdNetAddr xrd_addr;
343  char canonname[256];
344  if (!xrd_addr.Set(hname) || (xrd_addr.Format(canonname, 256, XrdNetAddrInfo::fmtName, XrdNetAddrInfo::noPort) <= 0)) {
345  Entity.host = strdup(hname);
346  } else {
347  Entity.host = strdup(canonname);
348  }
349  }
350  }
351  } else {
352  // We have been told via environment variable to not trust DNS; use the exact
353  // hostname provided by the user.
354 // char dnBuff[256];
355 // getdomainname(dnBuff, sizeof(dnBuff));
356  Entity.host = strdup(hname);
357  expectedHost = strdup(hname);
358  }
359  epAddr = endPoint;
360  Entity.addrInfo = &epAddr;
361 
362  // Init session variables
363  sessionCF = 0;
364  sessionKey = 0;
365  bucketKey = 0;
366  sessionMD = 0;
367  sessionKsig = 0;
368  sessionKver = 0;
369  sessionKver = 0;
370  proxyChain = 0;
371  useIV = false;
372 
373  //
374  // Notify, if required
375  DEBUG("constructing: host: "<< Entity.host);
376  DEBUG("p: "<<XrdSecPROTOIDENT<<", plen: "<<XrdSecPROTOIDLEN);
377  //
378  // basic settings
379  options = opts;
380  srvMode = 0;
381 
382  //
383  // Mode specific initializations
384  if (Server) {
385  srvMode = 1;
386  DEBUG("mode: server");
387  } else {
388  DEBUG("mode: client");
389  //
390  // Decode received buffer
391  if (parms) {
392  XrdOucString p("&P=gsi,");
393  p += parms;
394  hs->Parms = new XrdSutBuffer(p.c_str(), p.length());
395  }
396  }
397 
398  // We are done
399  String vers = Version;
400  vers.insert('.',vers.length()-2);
401  vers.insert('.',vers.length()-5);
402  DEBUG("object created: v"<<vers.c_str());
403 }
404 
405 //_____________________________________________________________________________
407 {
408  // Static method to the configure the static part of the protocol
409  // Called once by XrdSecProtocolgsiInit
410  EPNAME("Init");
411  char *Failure = 0, *Parms = 0;
412 
413  //
414  // Debug an tracing
415  Debug = (opt.debug > -1) ? opt.debug : Debug;
416 
417  // We must have the tracing object at this point
418  // (initialized in XrdSecProtocolgsiInit)
419  if (!gsiTrace) {
420  ErrF(erp,kGSErrInit,"tracing object (gsiTrace) not initialized! cannot continue");
421  return Failure;
422  }
423  // Set debug mask ... also for auxilliary libs
424  int trace = 0, traceSut = 0, traceCrypto = 0;
425  if (Debug >= 3) {
426  trace = cryptoTRACE_Dump;
427  traceSut = sutTRACE_Dump;
428  traceCrypto = cryptoTRACE_Dump;
429  GSITrace->What = TRACE_ALL;
430  } else if (Debug >= 2) {
431  trace = cryptoTRACE_Debug;
432  traceSut = sutTRACE_Debug;
433  traceCrypto = cryptoTRACE_Debug;
434  GSITrace->What = TRACE_Debug;
435  GSITrace->What |= TRACE_Authen;
436  } else if (Debug >= 1) {
437  trace = cryptoTRACE_Debug;
438  traceSut = sutTRACE_Notify;
439  traceCrypto = cryptoTRACE_Notify;
440  GSITrace->What = TRACE_Debug;
441  }
442 
443  // ... also for auxilliary libs
444  XrdSutSetTrace(traceSut);
445  XrdCryptoSetTrace(traceCrypto);
446 
447  // Name hashing algorithm compatibility
448  if (opt.hashcomp == 0) HashCompatibility = 0;
449 
450  //
451  // Operation mode
452  Server = (opt.mode == 's');
453 
454  //
455  // CA verification level
456  //
457  // 0 do not verify
458  // 1 verify if self-signed; warn if not
459  // 2 verify in all cases; fail if not possible
460  //
461  if (opt.ca >= caNoVerify && opt.ca <= caVerify)
462  CACheck = opt.ca;
463  DEBUG("option CACheck: "<<getOptName(caVerOpts,CACheck));
464 
465  //
466  // Check existence of CA directory
467  struct stat st;
468  if (opt.certdir) {
469  DEBUG("testing CA dir(s): "<<opt.certdir);
470  String CAtmp;
471  String tmp = opt.certdir;
472  String dp;
473  int from = 0;
474  while ((from = tmp.tokenize(dp, from, ',')) != -1) {
475  if (dp.length() > 0) {
476  if (XrdSutExpand(dp) == 0) {
477  if (stat(dp.c_str(),&st) == -1) {
478  if (errno == ENOENT) {
479  ErrF(erp,kGSErrError,"CA directory non existing",dp.c_str());
480  PRINT(erp->getErrText());
481  } else {
482  ErrF(erp,kGSErrError,"cannot stat CA directory",dp.c_str());
483  PRINT(erp->getErrText());
484  }
485  } else {
486  if (!(dp.endswith('/'))) dp += '/';
487  if (!(CAtmp.endswith(','))) CAtmp += ',';
488  CAtmp += dp;
489  }
490  } else {
491  PRINT("Warning: could not expand: "<<dp);
492  }
493  }
494  }
495  if (CAtmp.length() > 0)
496  CAdir = CAtmp;
497  }
498  DEBUG("using CA dir(s): "<<CAdir);
499 
500  //
501  // CRL check level
502  //
503  // 0 do not care
504  // 1 use if available
505  // 2 require
506  // 3 require not expired
507  // 12 require; try download if missing
508  // 13 require not expired; try download if missing
509  //
510  const char *cocrl[] = { "do-not-care", "use-if-available", "require", "require-not-expired" };
511  const char *codwld[] = { "no", "yes"};
512  if (opt.crl >= crlUpdate) {
513  CRLDownload = 1;
514  opt.crl %= 10;
515  }
516  if (opt.crl >= crlIgnore && opt.crl <= crlRequire)
517  CRLCheck = opt.crl;
518  DEBUG("option CRLCheck: "<<CRLCheck<<" ('"<<cocrl[CRLCheck]<<"'; download? "<<
519  codwld[CRLDownload]<<")");
520 
521  //
522  // Check existence of CRL directory
523  if (opt.crldir) {
524 
525  DEBUG("testing CRL dir(s): "<<opt.crldir);
526  String CRLtmp;
527  String tmp = opt.crldir;
528  String dp;
529  int from = 0;
530  while ((from = tmp.tokenize(dp, from, ',')) != -1) {
531  if (dp.length() > 0) {
532  if (XrdSutExpand(dp) == 0) {
533  if (stat(dp.c_str(),&st) == -1) {
534  if (errno == ENOENT) {
535  ErrF(erp,kGSErrError,"CRL directory non existing:",dp.c_str());
536  PRINT(erp->getErrText());
537  } else {
538  ErrF(erp,kGSErrError,"cannot stat CRL directory:",dp.c_str());
539  PRINT(erp->getErrText());
540  }
541  } else {
542  if (!(dp.endswith('/'))) dp += '/';
543  if (!(CRLtmp.endswith(','))) CRLtmp += ',';
544  CRLtmp += dp;
545  }
546  } else {
547  PRINT("Warning: could not expand: "<<dp);
548  }
549  }
550  }
551  if (CRLtmp.length() > 0)
552  CRLdir = CRLtmp;
553 
554  } else {
555  // Use CAdir
556  CRLdir = CAdir;
557  }
558  if (CRLCheck > 0)
559  DEBUG("using CRL dir(s): "<<CRLdir);
560 
561  //
562  // Default extension for CRL files
563  if (opt.crlext)
564  DefCRLext = opt.crlext;
565 
566  //
567  // Refresh or expiration time for CRLs
568  if (opt.crlrefresh)
569  CRLRefresh = opt.crlrefresh;
570  DEBUG("CRL information refreshed every "<<CRLRefresh<<" secs");
571 
572  //
573  // Honour trust / unstrust DNS settings (switch or env)
574  TrustDNS = opt.trustdns;
575  DEBUG("trust DNS option: "<<TrustDNS);
576 
577  //
578  // Enable/disable displaying the DN
579  ShowDN = opt.showDN;
580  DEBUG("show DN option: "<<ShowDN);
581 
582  //
583  // Server specific options
584  if (Server) {
585  //
586  // List of supported / wanted crypto modules
587  if (opt.clist)
588  DefCrypto = opt.clist;
589  //
590  // List of crypto modules
591  String cryptlist;
592  String crypts(DefCrypto,0,-1,64);
593  //
594  // Load crypto modules
595  XrdSutPFEntry ent;
596  XrdCryptoFactory *cf = 0;
597  if (crypts.length()) {
598  String ncpt = "";
599  int from = 0;
600  while ((from = crypts.tokenize(ncpt, from, '|')) != -1) {
601  if (ncpt.length() > 0 && ncpt[0] != '-') {
602  // Try loading
603  if ((cf = XrdCryptoFactory::GetCryptoFactory(ncpt.c_str()))) {
604  // Add it to the list
605  cryptF[ncrypt] = cf;
606  cryptID[ncrypt] = cf->ID();
607  cryptName[ncrypt].insert(cf->Name(),0,strlen(cf->Name())+1);
608  cf->SetTrace(trace);
609  cf->Notify();
610  // Ref cipher
611  if (!(refcip[ncrypt] = cf->Cipher(0,0,0))) {
612  PRINT("ref cipher for module "<<ncpt<<
613  " cannot be instantiated : disable");
614  from -= ncpt.length();
615  } else {
616  ncrypt++;
617  if (ncrypt >= XrdCryptoMax) {
618  PRINT("max number of crypto modules ("
619  << XrdCryptoMax <<") reached ");
620  break;
621  }
622  if (cryptlist.length()) cryptlist += ":";
623  cryptlist += ncpt;
624  if (!cf->HasPaddingSupport()) cryptlist += gNoPadTag;
625  }
626  } else {
627  PRINT("cannot instantiate crypto factory "<<ncpt<<
628  ": disable");
629  from -= ncpt.length();
630  }
631  }
632  }
633  }
634  //
635  // We need at least one valid crypto module
636  if (ncrypt <= 0) {
637  ErrF(erp,kGSErrInit,"could not find any valid crypto module");
638  PRINT(erp->getErrText());
639  return Failure;
640  }
641  //
642  // List of supported / wanted ciphers
643  if (opt.cipher)
644  DefCipher = opt.cipher;
645  // make sure we support all of them
646  String cip = "";
647  int from = 0;
648  while ((from = DefCipher.tokenize(cip, from, ':')) != -1) {
649  if (cip.length() > 0) {
650  int i = 0;
651  for (; i < ncrypt; i++) {
652  if (!(cryptF[i]->SupportedCipher(cip.c_str()))) {
653  // Not supported: drop from the list
654  DEBUG("cipher type not supported ("<<cip<<") - disabling");
655  from -= cip.length();
656  DefCipher.erase(cip);
657  }
658  }
659  }
660  }
661 
662  //
663  // List of supported / wanted Message Digest
664  if (opt.md)
665  DefMD = opt.md;
666  // make sure we support all of them
667  String md = "";
668  from = 0;
669  while ((from = DefMD.tokenize(md, from, ':')) != -1) {
670  if (md.length() > 0) {
671  int i = 0;
672  for (; i < ncrypt; i++) {
673  if (!(cryptF[i]->SupportedMsgDigest(md.c_str()))) {
674  // Not supported: drop from the list
675  PRINT("MD type not supported ("<<md<<") - disabling");
676  from -= md.length();
677  DefMD.erase(md);
678  }
679  }
680  }
681  }
682 
683  //
684  // Load server certificate and key
685  if (opt.cert) {
686  String TmpCert = opt.cert;
687  if (XrdSutExpand(TmpCert) == 0) {
688  SrvCert = TmpCert;
689  } else {
690  PRINT("Could not expand: "<<opt.cert<<": use default");
691  }
692  }
693  if (opt.key) {
694  String TmpKey = opt.key;
695  if (XrdSutExpand(TmpKey) == 0) {
696  SrvKey = TmpKey;
697  } else {
698  PRINT("Could not expand: "<<opt.key<<": use default");
699  }
700  }
701  //
702  // Check if we can read the certificate key
703  if (access(SrvKey.c_str(), R_OK)) {
704  PRINT("WARNING: process has no permission to read the certificate key file: "<<SrvKey);
705  }
706  int i = 0;
707  String certcalist = ""; // list of CA for server certificates
708  XrdSutCERef ceref;
709  for (; i<ncrypt; i++) {
710  if (!GetSrvCertEnt(ceref, cryptF[i], time(0), certcalist)) {
711  PRINT("problems loading srv cert");
712  ceref.UnLock();
713  continue;
714  }
715  }
716  // Rehash cache
717  ceref.UnLock();
718  //
719  // We must have got at least one valid certificate
720  if (cacheCert.Num() <= 0) {
721  ErrF(erp,kGSErrError,"no valid server certificate found");
722  PRINT(erp->getErrText());
723  return Failure;
724  }
725 
726  DEBUG("CA list: "<<certcalist);
727 
728  //
729  // GRID map check option
730  //
731  // 0 do not use (DN hash will be used as identifier)
732  // 1 use if available; otherwise as 0
733  // 2 require
734  // 10 do not use (DN name will be used as identifier)
735  // 11 use if available; otherwise as 10
736  const char *cogmap[] = { "do-not-use", "use-if-available", "require" };
737  const char *codnnm[] = { "DN hash", "DN name"};
738  if (opt.ogmap >= 10) {
739  GMAPuseDNname = 1;
740  opt.ogmap %= 10;
741  }
742  if (opt.ogmap >= 0 && opt.ogmap <= 2)
743  GMAPOpt = opt.ogmap;
744  DEBUG("user mapping file option: "<<cogmap[GMAPOpt]);
745  if (GMAPOpt < 2)
746  DEBUG("default option for entity name if no mapping available: "<<codnnm[(int)GMAPuseDNname]);
747 
748  //
749  // Check existence of GRID map file
750  if (opt.gridmap) {
751  String GMAPTmp = opt.gridmap;
752  if (XrdSutExpand(GMAPTmp) == 0) {
753  GMAPFile = GMAPTmp;
754  } else {
755  PRINT("Could not expand: "<<opt.gridmap<<": use default");
756  }
757  }
758  bool hasgmap = 0;
759  if (GMAPOpt > 0) {
760  // Initialize the GMap service
761  //
762  String pars;
763  if (Debug) pars += "dbg|";
764  if (opt.gmapto > 0) { pars += "to="; pars += (int)opt.gmapto; }
765  if (!(servGMap = XrdOucgetGMap(&eDest, GMAPFile.c_str(), pars.c_str()))) {
766  if (GMAPOpt > 1) {
767  ErrF(erp,kGSErrError,"error loading grid map file",GMAPFile.c_str());
768  PRINT(erp->getErrText());
769  return Failure;
770  } else {
771  NOTIFY("Grid map file: "<<GMAPFile<<" cannot be 'access'ed: do not use");
772  }
773  } else {
774  DEBUG("using grid map file: "<<GMAPFile);
775  hasgmap = 1;
776  }
777  }
778  //
779  // Load function be used to map DN to usernames, if specified
780  bool hasgmapfun = 0;
781  if (opt.gmapfun && GMAPOpt > 0) {
782  if (!(GMAPFun = LoadGMAPFun((const char *) opt.gmapfun,
783  (const char *) opt.gmapfunparms))) {
784  ErrF(erp, kGSErrError, "GMAP plug-in could not be loaded", opt.gmapfun);
785  PRINT(erp->getErrText());
786  return Failure;
787  } else {
788  hasgmapfun = 1;
789  }
790  }
791  //
792  // Disable GMAP if neither a grid mapfile nor a GMAP function are available
793  if (!hasgmap && !hasgmapfun) {
794  if (GMAPOpt > 1) {
795  ErrF(erp,kGSErrError,"User mapping required, but neither a grid mapfile"
796  " nor a mapping function are available");
797  PRINT(erp->getErrText());
798  return Failure;
799  }
800  GMAPOpt = 0;
801  }
802  //
803  // Authentication function
804  bool hasauthzfun = 0;
805  AuthzAlways = opt.authzcall;
806  if (opt.authzfun) {
807  if (!(AuthzFun = LoadAuthzFun((const char *) opt.authzfun,
808  (const char *) opt.authzfunparms, AuthzCertFmt))) {
809  ErrF(erp, kGSErrError, "Authz plug-in could not be loaded", opt.authzfun);
810  PRINT(erp->getErrText());
811  return Failure;
812  } else {
813  hasauthzfun = 1;
814  // Notify certificate format
815  if (AuthzCertFmt >= 0 && AuthzCertFmt <= 1) {
816  const char *ccfmt[] = { "raw", "PEM base64" };
817  DEBUG("authzfun: proxy certificate format: "<<ccfmt[AuthzCertFmt]);
818  } else {
819  NOTIFY("authzfun: proxy certificate format: unknown (code: "<<AuthzCertFmt<<")");
820  }
821  // Expiration of Authz related cache entries
822  if (opt.authzto > 0) {
823  AuthzCacheTimeOut = opt.authzto;
824  DEBUG("grid-map cache entries expire after "<<AuthzCacheTimeOut<<" secs");
825  }
826  }
827  }
828  //
829  // Expiration of GRIDMAP related cache entries
830  if (GMAPOpt > 0 && !hasauthzfun && opt.gmapto > 0) {
831  GMAPCacheTimeOut = opt.gmapto;
832  DEBUG("grid-map cache entries expire after "<<GMAPCacheTimeOut<<" secs");
833  }
834 
835  //
836  // Request for proxy export for authorization
837  // authzpxy = opt_what*10 + opt_where
838  // opt_what = 0 full chain
839  // 1 last proxy only
840  // opt_where = 1 Entity.creds
841  // 2 Entity.endorsements
842  if (opt.authzpxy) {
843  AuthzPxyWhat = opt.authzpxy / 10;
844  AuthzPxyWhere = opt.authzpxy % 10;
845  // Some notification
846  const char *capxy_what = (AuthzPxyWhat == 1) ? "'last proxy only'"
847  : "'full proxy chain'";
848  const char *capxy_where = (AuthzPxyWhere == 1) ? "XrdSecEntity.creds"
849  : "XrdSecEntity.endorsements";
850  DEBUG("Export proxy for authorization in '"<<capxy_where<<"': "<<capxy_what);
851  if (hasauthzfun) {
852  // Warn user about possible overwriting of Entity.creds or Entity.endorsements
853  PRINT("WARNING: proxy export for authz enabled: be aware that any setting of '"<<capxy_what<<
854  "' done by '"<<opt.authzfun<<"' will get overwritten with "<<capxy_what);
855  }
856  }
857 
858  //
859  // Handle delegated proxies options
860  if (opt.dlgpxy == -1) {
861  // Will not accept any delegated proxies
862  DEBUG("Will not accept delegated proxies");
863  } else {
864  // Ask the client to sign a delegated proxy; client may decide to forward its proxy
865  if (opt.dlgpxy == dlgReqSign)
866  PxyReqOpts |= kOptsSrvReq;
867 
868  // Exporting options (default none: delegated proxy kept in memory, in proxyChain)
869  if (opt.exppxy) {
870  if (!strcmp(opt.exppxy, "=creds")) {
871  // register the delegated proxy in Entity.creds (in HEX format)
872  PxyReqOpts |= kOptsPxCred;
873  DEBUG("Delegated proxy saved in Entity.creds ");
874  } else {
875  String TmpProxy = gUsrPxyDef;
876  if (strcmp(opt.exppxy, "=default"))
877  TmpProxy = opt.exppxy;
878  if (XrdSutExpand(TmpProxy) == 0) {
879  UsrProxy = TmpProxy;
880  } else {
881  UsrProxy = gUsrPxyDef;
882  UsrProxy += "u<uid>";
883  }
884  PxyReqOpts |= kOptsPxFile;
885  DEBUG("File template for delegated proxy: "<<UsrProxy);
886  }
887  }
888  DEBUG("Delegated proxies options: "<<PxyReqOpts);
889  }
890 
891  //
892  // VOMS attributes switch
893  // vomsat = 0 do not look for
894  // 1 extract if any (fill 'vorg', 'role'; the full string in 'endorsements');
895  // 2 require (fill 'vorg', 'role'; the full string in 'endorsements');
896  VOMSAttrOpt = (opt.vomsat <= vatRequire && opt.vomsat >= vatIgnore)
897  ? opt.vomsat : VOMSAttrOpt;
898 
899  //
900  // Alternative VOMS extraction function
901  if (opt.vomsfun) {
902  if (!(VOMSFun = LoadVOMSFun((const char *) opt.vomsfun,
903  (const char *) opt.vomsfunparms, VOMSCertFmt))) {
904  ErrF(erp, kGSErrError, "VOMS plug-in loading failed", opt.vomsfun);
905  PRINT(erp->getErrText());
906  return Failure;
907  } else {
908  // Notify certificate format
909  if (VOMSCertFmt >= 0 && VOMSCertFmt <= 1) {
910  const char *ccfmt[] = { "raw", "PEM base64" };
911  DEBUG("vomsfun: proxy certificate format: "<<ccfmt[VOMSCertFmt]);
912  } else {
913  char fbuff[64];
914  snprintf(fbuff, sizeof(fbuff), "%d", VOMSCertFmt);
915  ErrF(erp, kGSErrError, "VOMS plug-in returned invalid cert "
916  "format", fbuff);
917  PRINT(erp->getErrText());
918  return Failure;
919  }
920  }
921  } else opt.authzcall = AuthzAlways = 1;
922  DEBUG("VOMS attributes options: "<<getOptName(vomsatOpts, VOMSAttrOpt));
923 
924  //
925  // Default moninfo option
926  // 0 nothing
927  // 1 DN
928  MonInfoOpt = opt.moninfo;
929  const char *cmoninfo = (MonInfoOpt == 1) ? "DN" : "none";
930  DEBUG("Monitor information options: "<<cmoninfo);
931 
932  // Make sure we have a calist as the client can't do anything without it.
933  // If the cryptlist is empty the client will use the default one.
934  //
935  if (certcalist.length() == 0)
936  {ErrF(erp,kGSErrInit,"unable to generate ca cert hash list!");
937  PRINT(erp->getErrText());
938  return Failure;
939  }
940 
941  //
942  // Parms in the form:
943  // &P=gsi,v:<version>,c:<cryptomod>,ca:<list_of_srv_cert_ca>
944  Parms = new char[cryptlist.length()+3+12+certcalist.length()+5];
945  if (Parms) {
946  sprintf(Parms,"v:%d,c:%s,ca:%s",
947  Version,cryptlist.c_str(),certcalist.c_str());
948  } else {
949  ErrF(erp,kGSErrInit,"no system resources for 'Parms'");
950  PRINT(erp->getErrText());
951  return Failure;
952  }
953 
954  // Some notification
955  DEBUG("available crypto modules: "<<cryptlist);
956  DEBUG("issuer CAs of server certs (hashes): "<<certcalist);
957  }
958 
959  //
960  // Client specific options
961  if (!Server) {
962  // use default dir $(HOME)/.<prefix>
963  struct passwd *pw = getpwuid(getuid());
964  if (!pw) {
965  NOTIFY("WARNING: cannot get user information (uid:"<<getuid()<<")");
966  }
967  //
968  // Define user proxy file
969  UsrProxy = gUsrPxyDef;
970  if (opt.proxy) {
971  String TmpProxy = opt.proxy;
972  if (XrdSutExpand(TmpProxy) == 0) {
973  UsrProxy = TmpProxy;
974  } else {
975  PRINT("Could not expand: "<<opt.proxy<<": use default");
976  }
977  } else {
978  if (pw)
979  UsrProxy += (int)(pw->pw_uid);
980  }
981  // Define user certificate file
982  if (opt.cert) {
983  String TmpCert = opt.cert;
984  if (XrdSutExpand(TmpCert) == 0) {
985  UsrCert = TmpCert;
986  } else {
987  PRINT("Could not expand: "<<opt.cert<<": use default");
988  }
989  } else {
990  if (pw)
991  UsrCert.insert(XrdSutHome(),0);
992  }
993  // Define user private key file
994  if (opt.key) {
995  String TmpKey = opt.key;
996  if (XrdSutExpand(TmpKey) == 0) {
997  UsrKey = TmpKey;
998  } else {
999  PRINT("Could not expand: "<<opt.key<<": use default");
1000  }
1001  } else {
1002  if (pw)
1003  UsrKey.insert(XrdSutHome(),0);
1004  }
1005  // Define proxy validity at renewal
1006  if (opt.valid)
1007  PxyValid = opt.valid;
1008  // Set depth of signature path
1009  if (opt.deplen != DepLength)
1010  DepLength = opt.deplen;
1011  // Set number of bits for proxy key
1012  if (opt.bits > DefBits)
1013  DefBits = opt.bits;
1014  //
1015  // Delegate proxy options
1016  if (opt.dlgpxy > dlgIgnore) {
1017  PxyReqOpts |= kOptsSigReq;
1018  if (opt.dlgpxy == dlgSendpxy) {
1019  PxyReqOpts |= kOptsFwdPxy;
1020  } else {
1021  PxyReqOpts |= kOptsDlgPxy;
1022  }
1023  }
1024  //
1025  // No proxy options
1026  if (opt.createpxy) {
1027  PxyReqOpts |= kOptsCreatePxy;
1028  }
1029  //
1030  // Define valid CNs for the server certificates; default is null, which means that
1031  // the server CN must be in the form "*/<hostname>"
1032  if (opt.srvnames)
1033  SrvAllowedNames = opt.srvnames;
1034  //
1035  // Notify
1036  TRACE(Authen, "using certificate file: "<<UsrCert);
1037  TRACE(Authen, "using private key file: "<<UsrKey);
1038  TRACE(Authen, "proxy: file: "<<UsrProxy);
1039  TRACE(Authen, "proxy: validity: "<<PxyValid);
1040  TRACE(Authen, "proxy: depth of signature path: "<<DepLength);
1041  TRACE(Authen, "proxy: bits in key: "<<DefBits);
1042  TRACE(Authen, "server cert: allowed names: "<<SrvAllowedNames);
1043  if (!(PxyReqOpts & kOptsCreatePxy)) {
1044  TRACE(Authen, "allowing for pure cert/key authentication (no proxy) ");
1045  }
1046 
1047  // We are done
1048  Parms = (char *)"";
1049  }
1050 
1051  // We are done
1052  return Parms;
1053 }
1054 
1055 /******************************************************************************/
1056 /* D e l e t e */
1057 /******************************************************************************/
1059 {
1060  // Deletes the protocol
1061  SafeFree(Entity.name);
1062  SafeFree(Entity.host);
1063  SafeFree(Entity.vorg);
1064  SafeFree(Entity.role);
1065  SafeFree(Entity.grps);
1066  SafeFree(Entity.caps);
1068  if (Entity.creds && Entity.credslen > 0) {
1070  } else {
1071  Entity.creds = 0;
1072  }
1073  Entity.credslen = 0;
1075  // Cleanup the handshake variables, if still there
1076  SafeDelete(hs);
1077  // Cleanup any other instance specific to this protocol
1078  SafeDelete(sessionKey); // Session Key (result of the handshake)
1079  SafeDelete(bucketKey); // Bucket with the key in export form
1080  SafeDelete(sessionMD); // Message Digest instance
1081  SafeDelete(sessionKsig); // RSA key to sign
1082  SafeDelete(sessionKver); // RSA key to verify
1083  if (proxyChain) proxyChain->Cleanup();
1084  SafeDelete(proxyChain); // Chain with delegated proxies
1085  SafeFree(expectedHost);
1086 
1087  delete this;
1088 }
1089 
1090 
1091 /******************************************************************************/
1092 /* E n c r y p t i o n R e l a t e d M e t h o d s */
1093 /******************************************************************************/
1094 
1095 //_____________________________________________________________________________
1096 int XrdSecProtocolgsi::Encrypt(const char *inbuf, // Data to be encrypted
1097  int inlen, // Length of data in inbuff
1098  XrdSecBuffer **outbuf) // Returns encrypted data
1099 {
1100  // Encrypt data in inbuff and place it in outbuff.
1101  //
1102  // Returns: < 0 Failed, the return value is -errno of the reason. Typically,
1103  // -EINVAL - one or more arguments are invalid.
1104  // -ENOTSUP - encryption not supported by the protocol
1105  // -EOVERFLOW - outbuff is too small to hold result
1106  // -ENOENT - Context not initialized
1107  // = 0 Success, outbuff contains a pointer to the encrypted data.
1108  //
1109  EPNAME("Encrypt");
1110 
1111  // We must have a key
1112  if (!sessionKey)
1113  return -ENOENT;
1114 
1115  // And something to encrypt
1116  if (!inbuf || inlen <= 0 || !outbuf)
1117  return -EINVAL;
1118 
1119  // Regenerate IV
1120  int liv = 0;
1121  char *iv = 0;
1122  if (useIV) {
1123  iv = sessionKey->RefreshIV(liv); // no need to call sessionKeySetIV as
1124  // RefreshIV will set the internal value
1125  }
1126 
1127  // Get output buffer
1128  char *buf = (char *)malloc(sessionKey->EncOutLength(inlen) + liv);
1129  if (!buf)
1130  return -ENOMEM;
1131  // IV at beginning
1132  if (liv > 0 && iv)
1133  memcpy(buf, iv, liv);
1134 
1135  // Encrypt
1136  int len = sessionKey->Encrypt(inbuf, inlen, buf + liv) + liv; // the size of initialization vector which is being appended at
1137  // the beginning of the output buffer has to be taken into account
1138  if (len <= 0) {
1139  SafeFree(buf);
1140  return -EINVAL;
1141  }
1142 
1143  // Create and fill output buffer
1144  *outbuf = new XrdSecBuffer(buf, len);
1145 
1146  // We are done
1147  DEBUG("encrypted buffer has "<<len<<" bytes");
1148  return 0;
1149 }
1150 
1151 //_____________________________________________________________________________
1152 int XrdSecProtocolgsi::Decrypt(const char *inbuf, // Data to be decrypted
1153  int inlen, // Length of data in inbuff
1154  XrdSecBuffer **outbuf) // Returns decrypted data
1155 {
1156  // Decrypt data in inbuff and place it in outbuff.
1157  //
1158  // Returns: < 0 Failed,the return value is -errno (see Encrypt).
1159  // = 0 Success, outbuff contains a pointer to the encrypted data.
1160  EPNAME("Decrypt");
1161 
1162  // We must have a key
1163  if (!sessionKey)
1164  return -ENOENT;
1165 
1166  // And something to decrypt
1167  if (!inbuf || inlen <= 0 || !outbuf)
1168  return -EINVAL;
1169 
1170  // Size
1171  int liv = (useIV) ? sessionKey->MaxIVLength() : 0;
1172  int sz = inlen - liv;
1173  // Get output buffer
1174  char *buf = (char *)malloc(sessionKey->DecOutLength(sz) + liv);
1175  if (!buf)
1176  return -ENOMEM;
1177 
1178  // Get and set IV
1179  if (useIV) {
1180  char *iv = new char[liv];
1181  memcpy(iv, inbuf, liv);
1182  sessionKey->SetIV(liv, iv);
1183  delete[] iv;
1184  }
1185 
1186  // Decrypt
1187  int len = sessionKey->Decrypt(inbuf + liv, sz, buf);
1188  if (len <= 0) {
1189  SafeFree(buf);
1190  return -EINVAL;
1191  }
1192 
1193  // Create and fill output buffer
1194  *outbuf = new XrdSecBuffer(buf, len);
1195 
1196  // We are done
1197  DEBUG("decrypted buffer has "<<len<<" bytes");
1198  return 0;
1199 }
1200 
1201 //_____________________________________________________________________________
1202 int XrdSecProtocolgsi::Sign(const char *inbuf, // Data to be signed
1203  int inlen, // Length of data to be signed
1204  XrdSecBuffer **outbuf) // Buffer for the signature
1205 {
1206  // Sign data in inbuff and place the signature in outbuf.
1207  //
1208  // Returns: < 0 Failed, returned value is -errno (see Encrypt).
1209  // = 0 Success, the return value is the length of the signature
1210  // placed in outbuf.
1211  //
1212  EPNAME("Sign");
1213 
1214  // We must have a PKI and a digest
1215  if (!sessionKsig || !sessionMD)
1216  return -ENOENT;
1217 
1218  // And something to sign
1219  if (!inbuf || inlen <= 0 || !outbuf)
1220  return -EINVAL;
1221 
1222  // Reset digest
1223  sessionMD->Reset(0);
1224 
1225  // Calculate digest
1226  sessionMD->Update(inbuf, inlen);
1227  sessionMD->Final();
1228 
1229  // Output length
1230  int lmax = sessionKsig->GetOutlen(sessionMD->Length());
1231  char *buf = (char *)malloc(lmax);
1232  if (!buf)
1233  return -ENOMEM;
1234 
1235  // Sign
1236  int len = sessionKsig->EncryptPrivate(sessionMD->Buffer(),
1237  sessionMD->Length(),
1238  buf, lmax);
1239  if (len <= 0) {
1240  SafeFree(buf);
1241  return -EINVAL;
1242  }
1243 
1244  // Create and fill output buffer
1245  *outbuf = new XrdSecBuffer(buf, len);
1246 
1247  // We are done
1248  DEBUG("signature has "<<len<<" bytes");
1249  return 0;
1250 }
1251 
1252 //_____________________________________________________________________________
1253 int XrdSecProtocolgsi::Verify(const char *inbuf, // Data to be verified
1254  int inlen, // Length of data in inbuf
1255  const char *sigbuf, // Buffer with signature
1256  int siglen) // Length of signature
1257 {
1258  // Verify a signature
1259  //
1260  // Returns: < 0 Failed, returned value is -errno (see Encrypt).
1261  // = 0 Signature matches the value in inbuff.
1262  // > 0 Failed to verify, signature does not match inbuff data.
1263  //
1264  EPNAME("Verify");
1265 
1266  // We must have a PKI and a digest
1267  if (!sessionKver || !sessionMD)
1268  return -ENOENT;
1269 
1270  // And something to verify
1271  if (!inbuf || inlen <= 0 || !sigbuf || siglen <= 0)
1272  return -EINVAL;
1273 
1274  // Reset digest
1275  sessionMD->Reset(0);
1276 
1277  // Calculate digest
1278  sessionMD->Update(inbuf, inlen);
1279  sessionMD->Final();
1280 
1281  // Output length
1282  int lmax = sessionKver->GetOutlen(siglen);
1283  char *buf = new char[lmax];
1284  if (!buf)
1285  return -ENOMEM;
1286 
1287  // Decrypt signature
1288  int len = sessionKver->DecryptPublic(sigbuf, siglen, buf, lmax);
1289  if (len <= 0) {
1290  delete[] buf;
1291  return -EINVAL;
1292  }
1293 
1294  // Verify signature
1295  bool bad = 1;
1296  if (len == sessionMD->Length()) {
1297  if (!strncmp(buf, sessionMD->Buffer(), len)) {
1298  // Signature matches
1299  bad = 0;
1300  DEBUG("signature successfully verified");
1301  }
1302  }
1303 
1304  // Cleanup
1305  if (buf) delete[] buf;
1306 
1307  // We are done
1308  return ((bad) ? 1 : 0);
1309 }
1310 
1311 //_____________________________________________________________________________
1312 int XrdSecProtocolgsi::getKey(char *kbuf, int klen)
1313 {
1314  // Get the current encryption key
1315  //
1316  // Returns: < 0 Failed, returned value if -errno (see Encrypt)
1317  // >= 0 The size of the encyption key. The supplied buffer of length
1318  // size hold the key. If the buffer address is 0, only the
1319  // size of the key is returned.
1320  //
1321  EPNAME("getKey");
1322 
1323  // Check if we have to serialize the key
1324  if (!bucketKey) {
1325 
1326  // We must have a key for that
1327  if (!sessionKey)
1328  // Invalid call
1329  return -ENOENT;
1330  // Create bucket
1331  bucketKey = sessionKey->AsBucket();
1332  }
1333 
1334  // Prepare output now, if we have any
1335  if (bucketKey) {
1336  // If are asked only the size, we are done
1337  if (kbuf == 0)
1338  return bucketKey->size;
1339 
1340  // Check the size of the buffer
1341  if (klen < bucketKey->size)
1342  // Too small
1343  return -EOVERFLOW;
1344 
1345  // Copy the buffer
1346  memcpy(kbuf, bucketKey->buffer, bucketKey->size);
1347 
1348  // We are done
1349  DEBUG("session key exported");
1350  return bucketKey->size;
1351  }
1352 
1353  // Key exists but we could export it in bucket format
1354  return -ENOMEM;
1355 }
1356 
1357 //_____________________________________________________________________________
1358 int XrdSecProtocolgsi::setKey(char *kbuf, int klen)
1359 {
1360  // Set the current encryption key
1361  //
1362  // Returns: < 0 Failed, returned value if -errno (see Encrypt)
1363  // 0 The new key has been set.
1364  //
1365  EPNAME("setKey");
1366 
1367  // Make sur that we can initialize the new key
1368  if (!kbuf || klen <= 0)
1369  // Invalid inputs
1370  return -EINVAL;
1371 
1372  if (!sessionCF)
1373  // Invalid context
1374  return -ENOENT;
1375 
1376  // Put the buffer key into a bucket
1377  XrdSutBucket *bck = new XrdSutBucket();
1378  if (!bck)
1379  // Cannot get buffer: out-of-resources?
1380  return -ENOMEM;
1381  // Set key buffer
1382  bck->SetBuf(kbuf, klen);
1383 
1384  // Init a new cipher from the bucket
1385  XrdCryptoCipher *newKey = sessionCF->Cipher(bck);
1386  if (!newKey) {
1387  SafeDelete(bck);
1388  return -ENOMEM;
1389  }
1390 
1391  // Delete current key
1392  SafeDelete(sessionKey);
1393 
1394  // Set the new key
1395  sessionKey = newKey;
1396 
1397  // Cleanup
1398  SafeDelete(bck);
1399 
1400  // Ok
1401  DEBUG("session key update");
1402  return 0;
1403 }
1404 
1405 /******************************************************************************/
1406 /* C l i e n t O r i e n t e d F u n c t i o n s */
1407 /******************************************************************************/
1408 /******************************************************************************/
1409 /* g e t C r e d e n t i a l s */
1410 /******************************************************************************/
1411 
1413  XrdOucErrInfo *ei)
1414 {
1415  // Query client for the password; remote username and host
1416  // are specified in 'parm'. File '.rootnetrc' is checked.
1417  EPNAME("getCredentials");
1418 
1419  // If we are a server the only reason to be here is to get the forwarded
1420  // or saved client credentials
1421  if (srvMode) {
1422  XrdSecCredentials *creds = 0;
1423  if (proxyChain) {
1424  // Export the proxy chain into a bucket
1425  XrdCryptoX509ExportChain_t ExportChain = sessionCF->X509ExportChain();
1426  if (ExportChain) {
1427  XrdSutBucket *bck = (*ExportChain)(proxyChain, 1);
1428  if (bck) {
1429  // We need to duplicate it because XrdSecCredentials uses
1430  // {malloc, free} instead of {new, delete}
1431  char *nbuf = (char *) malloc(bck->size);
1432  if (nbuf) {
1433  memcpy(nbuf, bck->buffer, bck->size);
1434  // Import the buffer in a XrdSecCredentials object
1435  creds = new XrdSecCredentials(nbuf, bck->size);
1436  }
1437  delete bck;
1438  }
1439  }
1440  }
1441  return creds;
1442  }
1443 
1444  // Handshake vars container must be initialized at this point
1445  if (!hs)
1446  return ErrC(ei,0,0,0,kGSErrError,
1447  "handshake var container missing","getCredentials");
1448  //
1449  // Nothing to do if buffer is empty
1450  if ((!parm && !hs->Parms) || (parm && (!(parm->buffer) || parm->size <= 0))) {
1451  if (hs->Iter == 0)
1452  return ErrC(ei,0,0,0,kGSErrNoBuffer,"missing parameters","getCredentials");
1453  else
1454  return (XrdSecCredentials *)0;
1455  }
1456 
1457  // We support passing the user {proxy, cert, key} paths via Url parameter
1458  char *upp = (ei && ei->getEnv()) ? ei->getEnv()->Get("xrd.gsiusrpxy") : 0;
1459  if (upp) urlUsrProxy = upp;
1460  upp = (ei && ei->getEnv()) ? ei->getEnv()->Get("xrd.gsiusrcrt") : 0;
1461  if (upp) urlUsrCert = upp;
1462  upp = (ei && ei->getEnv()) ? ei->getEnv()->Get("xrd.gsiusrkey") : 0;
1463  if (upp) urlUsrKey = upp;
1464 
1465  // Count interations
1466  (hs->Iter)++;
1467 
1468  // Update time stamp
1469  hs->TimeStamp = time(0);
1470 
1471  // Local vars
1472  int step = 0;
1473  int nextstep = 0;
1474  const char *stepstr = 0;
1475  char *bpub = 0;
1476  int lpub = 0;
1477  String CryptoMod = "";
1478  String Host = "";
1479  String RemID = "";
1480  String Emsg;
1481  String specID = "";
1482  String issuerHash = "";
1483  // Buffer / Bucket related
1484  XrdSutBuffer *bpar = 0; // Global buffer
1485  XrdSutBuffer *bmai = 0; // Main buffer
1486  XrdSutBucket *bck = 0; // Generic bucket
1487 
1488  //
1489  // Decode received buffer
1490  bpar = hs->Parms;
1491  if (!bpar && !(bpar = new XrdSutBuffer((const char *)parm->buffer,parm->size)))
1492  return ErrC(ei,0,0,0,kGSErrDecodeBuffer,"global",stepstr);
1493  // Ownership has been transferred
1494  hs->Parms = 0;
1495  //
1496  // Check protocol ID name
1497  if (strcmp(bpar->GetProtocol(),XrdSecPROTOIDENT))
1498  return ErrC(ei,bpar,bmai,0,kGSErrBadProtocol,stepstr);
1499  //
1500  // The step indicates what we are supposed to do
1501  if (!(step = bpar->GetStep())) {
1502  // The first, fake, step
1503  step = kXGS_init;
1504  bpar->SetStep(step);
1505  }
1506  stepstr = ServerStepStr(step);
1507  // Dump, if requested
1508  XrdOucString bmsg;
1509  if (QTRACE(Dump)) {
1510  bmsg.form("IN: bpar: %s", stepstr);
1511  bpar->Dump(bmsg.c_str());
1512  }
1513  //
1514  // Parse input buffer
1515  if (ParseClientInput(bpar, &bmai, Emsg) == -1) {
1516  DEBUG(Emsg<<" CF: "<<sessionCF);
1517  return ErrC(ei,bpar,bmai,0,kGSErrParseBuffer,Emsg.c_str(),stepstr);
1518  }
1519  // Dump, if requested
1520  if (QTRACE(Dump)) {
1521  if (bmai) {
1522  bmsg.form("IN: bmai: %s", stepstr);
1523  bmai->Dump(bmsg.c_str());
1524  }
1525  }
1526  //
1527  // Version
1528  DEBUG("version run by server: "<< hs->RemVers);
1529  //
1530  // Check random challenge
1531  if (!CheckRtag(bmai, Emsg))
1532  return ErrC(ei,bpar,bmai,0,kGSErrBadRndmTag,Emsg.c_str(),stepstr);
1533  //
1534  // Login name if any
1535  String user(Entity.name);
1536  if (user.length() <= 0) user = getenv("XrdSecUSER");
1537  //
1538  // Now action depens on the step
1539  nextstep = kXGC_none;
1540 
1541  XrdCryptoX509 *c = 0;
1542 
1543  switch (step) {
1544 
1545  case kXGS_init:
1546  //
1547  // Add bucket with cryptomod to the global list
1548  // (This must be always visible from now on)
1549  CryptoMod = hs->CryptoMod;
1550  if (hs->RemVers >= XrdSecgsiVersDHsigned && !(hs->HasPad)) CryptoMod += gNoPadTag;
1551  if (bpar->AddBucket(CryptoMod,kXRS_cryptomod) != 0)
1552  return ErrC(ei,bpar,bmai,0,
1554  //
1555  // Add bucket with our version to the main list
1556  if (bpar->MarshalBucket(kXRS_version,(kXR_int32)(Version)) != 0)
1557  return ErrC(ei,bpar,bmai,0, kGSErrCreateBucket,
1558  XrdSutBuckStr(kXRS_version),"global",stepstr);
1559  //
1560  // Add our issuer hash
1561  c = hs->PxyChain->Begin();
1562  if (c->type == XrdCryptoX509::kCA) {
1563  issuerHash = c->SubjectHash();
1564  if (HashCompatibility && c->SubjectHash(1)) {
1565  issuerHash += "|"; issuerHash += c->SubjectHash(1); }
1566  } else {
1567  issuerHash = c->IssuerHash();
1568  if (HashCompatibility && c->IssuerHash(1)
1569  && strcmp(c->IssuerHash(1),c->IssuerHash())) {
1570  issuerHash += "|"; issuerHash += c->IssuerHash(1); }
1571  }
1572  while ((c = hs->PxyChain->Next()) != 0) {
1573  if (c->type != XrdCryptoX509::kCA)
1574  break;
1575  issuerHash = c->SubjectHash();
1576  if (HashCompatibility && c->SubjectHash(1)
1577  && strcmp(c->IssuerHash(1),c->IssuerHash())) {
1578  issuerHash += "|"; issuerHash += c->SubjectHash(1); }
1579  }
1580 
1581  DEBUG("Client issuer hash: " << issuerHash);
1582  if (bpar->AddBucket(issuerHash,kXRS_issuer_hash) != 0)
1583  return ErrC(ei,bpar,bmai,0, kGSErrCreateBucket,
1584  XrdSutBuckStr(kXRS_issuer_hash),stepstr);
1585  //
1586  // Add bucket with our delegate proxy options
1587  if (hs->RemVers >= 10100) {
1588  if (bpar->MarshalBucket(kXRS_clnt_opts,(kXR_int32)(hs->Options)) != 0)
1589  return ErrC(ei,bpar,bmai,0, kGSErrCreateBucket,
1590  XrdSutBuckStr(kXRS_clnt_opts),"global",stepstr);
1591  }
1592 
1593  //
1594  nextstep = kXGC_certreq;
1595  break;
1596 
1597  case kXGS_cert:
1598  //
1599  // We must have a session cipher at this point
1600  if (!(sessionKey))
1601  return ErrC(ei,bpar,bmai,0,
1602  kGSErrNoCipher,"session cipher",stepstr);
1603 
1604  //
1605  // Extract buffer with public info for the cipher agreement
1606  if (!(bpub = sessionKey->Public(lpub)))
1607  return ErrC(ei,bpar,bmai,0,
1608  kGSErrNoPublic,"session",stepstr);
1609 
1610  //
1611  // If server supports decoding of signed DH, do sign them
1612  if (hs->RemVers >= XrdSecgsiVersDHsigned) {
1613  bck = new XrdSutBucket(bpub,lpub,kXRS_cipher);
1614  if (sessionKsig) {
1615  // Encrypt client DH public parameters with client private key
1616  if (sessionKsig->EncryptPrivate(*bck) <= 0)
1617  return ErrC(ei,bpar,bmai,0, kGSErrExportPuK,
1618  "encrypting client DH public parameters",stepstr);
1619  } else {
1620  return ErrC(ei,bpar,bmai,0, kGSErrExportPuK,
1621  "client signing key undefined!",stepstr);
1622  }
1623  //
1624  // Add it to the global list
1625  if (bpar->AddBucket(bck) != 0)
1626  return ErrC(ei,bpar,bmai,0, kGSErrAddBucket, "main",stepstr);
1627  //
1628  // Export client public key
1629  XrdOucString cpub;
1630  if (sessionKsig->ExportPublic(cpub) < 0)
1631  return ErrC(ei,bpar,bmai,0, kGSErrExportPuK,
1632  "exporting client public key",stepstr);
1633  // Add it to the global list
1634  if (bpar->UpdateBucket(cpub.c_str(),cpub.length(),kXRS_puk) != 0)
1635  return ErrC(ei,bpar,bmai,0, kGSErrAddBucket,
1636  XrdSutBuckStr(kXRS_puk),"global",stepstr);
1637  } else {
1638  //
1639  // Add it to the global list
1640  if (bpar->UpdateBucket(bpub,lpub,kXRS_puk) != 0)
1641  return ErrC(ei,bpar,bmai,0, kGSErrAddBucket,
1642  XrdSutBuckStr(kXRS_puk),"global",stepstr);
1643  delete[] bpub; // bpub is being duplicated inside of 'UpdateBucket'
1644  }
1645 
1646  //
1647  // Add the proxy certificate
1648  bmai->AddBucket(hs->Cbck);
1649  //
1650  // Add login name if any, needed while chosing where to export the proxies
1651  if (user.length() > 0) {
1652  if (bmai->AddBucket(user, kXRS_user) != 0)
1653  return ErrC(ei,bpar,bmai,0, kGSErrCreateBucket,
1654  XrdSutBuckStr(kXRS_user),stepstr);
1655  }
1656  //
1657  nextstep = kXGC_cert;
1658  break;
1659 
1660  case kXGS_pxyreq:
1661  //
1662  // If something went wrong, send explanation
1663  if (Emsg.length() > 0) {
1664  if (bmai->AddBucket(Emsg,kXRS_message) != 0)
1665  return ErrC(ei,bpar,bmai,0, kGSErrCreateBucket,
1666  XrdSutBuckStr(kXRS_message),stepstr);
1667  }
1668  //
1669  // Add login name if any, needed while chosing where to export the proxies
1670  if (user.length() > 0) {
1671  if (bmai->AddBucket(user, kXRS_user) != 0)
1672  return ErrC(ei,bpar,bmai,0, kGSErrCreateBucket,
1673  XrdSutBuckStr(kXRS_user),stepstr);
1674  }
1675  //
1676  // The relevant buckets should already be in the buffers
1677  nextstep = kXGC_sigpxy;
1678  break;
1679 
1680  default:
1681  return ErrC(ei,bpar,bmai,0, kGSErrBadOpt,stepstr);
1682  }
1683 
1684  //
1685  // Serialize and encrypt
1686  if (AddSerialized('c', nextstep, hs->ID,
1687  bpar, bmai, kXRS_main, sessionKey) != 0) {
1688  return ErrC(ei,bpar,bmai,0,
1689  kGSErrSerialBuffer,"main",stepstr);
1690  }
1691  //
1692  // Serialize the global buffer
1693  char *bser = 0;
1694  int nser = bpar->Serialized(&bser,'f');
1695 
1696  if (QTRACE(Authen)) {
1697  bmsg.form("OUT: bpar: %s", ClientStepStr(bpar->GetStep()));
1698  bpar->Dump(bmsg.c_str());
1699  bmsg.form("OUT: bmai: %s", ClientStepStr(bpar->GetStep()));
1700  bmai->Dump(bmsg.c_str());
1701  }
1702  //
1703  // We may release the buffers now
1704  REL2(bpar,bmai);
1705  //
1706  // Return serialized buffer
1707  if (nser > 0) {
1708  DEBUG("returned " << nser <<" bytes of credentials");
1709  return new XrdSecCredentials(bser, nser);
1710  } else {
1711  NOTIFY("problems with final serialization");
1712  return (XrdSecCredentials *)0;
1713  }
1714 }
1715 
1716 /******************************************************************************/
1717 /* S e r v e r O r i e n t e d M e t h o d s */
1718 /******************************************************************************/
1719 
1720 //_____________________________________________________________________________
1721 static bool AuthzFunCheck(XrdSutCacheEntry *e, void *a) {
1722 
1723  int st_ref = (*((XrdSutCacheArg_t *)a)).arg1;
1724  time_t ts_ref = (time_t)(*((XrdSutCacheArg_t *)a)).arg2;
1725  long to_ref = (*((XrdSutCacheArg_t *)a)).arg3;
1726  int st_exp = (*((XrdSutCacheArg_t *)a)).arg4;
1727 
1728  if (e && (e->status == st_ref)) {
1729  // Check expiration, if required
1730  bool expired = 0;
1731  if (to_ref > 0 && (ts_ref - e->mtime) > to_ref) expired = 1;
1732  int notafter = *((int *) e->buf2.buf);
1733  if (to_ref > notafter) expired = 1;
1734 
1735  if (expired) {
1736  // Invalidate the entry, if the case
1737  e->status = st_exp;
1738  } else {
1739  return true;
1740  }
1741  }
1742  return false;
1743 }
1744 
1745 /******************************************************************************/
1746 /* A u t h e n t i c a t e */
1747 /******************************************************************************/
1748 
1750  XrdSecParameters **parms,
1751  XrdOucErrInfo *ei)
1752 {
1753  //
1754  // Check if we have any credentials or if no credentials really needed.
1755  // In either case, use host name as client name
1756  EPNAME("Authenticate");
1757 
1758  //
1759  // If cred buffer is two small or empty assume host protocol
1760  if (cred->size <= (int)XrdSecPROTOIDLEN || !cred->buffer) {
1761  strncpy(Entity.prot, "host", sizeof(Entity.prot));
1762  return 0;
1763  }
1764 
1765  // Handshake vars conatiner must be initialized at this point
1766  if (!hs)
1767  return ErrS(Entity.tident,ei,0,0,0,kGSErrError,
1768  "handshake var container missing",
1769  "protocol initialization problems");
1770 
1771  // Update time stamp
1772  hs->TimeStamp = time(0);
1773 
1774  //
1775  // ID of this handshaking
1776  if (hs->ID.length() <= 0)
1777  hs->ID = Entity.tident;
1778  DEBUG("handshaking ID: " << hs->ID);
1779 
1780  // Local vars
1781  int kS_rc = kgST_more;
1782  int step = 0;
1783  int nextstep = 0;
1784  char *bpub = 0;
1785  int lpub = 0;
1786  bool vomsFailed = false;
1787  const char *stepstr = 0;
1788  String Message;
1789  String CryptList;
1790  String Ciphers;
1791  String Host;
1792  String SrvPuKExp;
1793  String Salt;
1794  String RndmTag;
1795  String ClntMsg(256);
1796  // Buffer related
1797  XrdSutBuffer *bpar = 0; // Global buffer
1798  XrdSutBuffer *bmai = 0; // Main buffer
1799  XrdSutBucket *bck = 0; // Generic bucket
1800  // Proxy export related
1801  XrdOucString spxy;
1802  XrdSutBucket *bpxy = 0;
1803 
1804  //
1805  // Decode received buffer
1806  if (!(bpar = new XrdSutBuffer((const char *)cred->buffer,cred->size)))
1807  return ErrS(hs->ID,ei,0,0,0,kGSErrDecodeBuffer,"global",stepstr);
1808  //
1809  // Check protocol ID name
1810  if (strcmp(bpar->GetProtocol(),XrdSecPROTOIDENT))
1811  return ErrS(hs->ID,ei,bpar,bmai,0,kGSErrBadProtocol,stepstr);
1812  //
1813  // The step indicates what we are supposed to do
1814  step = bpar->GetStep();
1815  stepstr = ClientStepStr(step);
1816  // Dump, if requested
1817  XrdOucString bmsg;
1818  if (QTRACE(Dump)) {
1819  bmsg.form("IN: bpar: %s", stepstr);
1820  bpar->Dump(bmsg.c_str());
1821  }
1822  //
1823  // Parse input buffer
1824  if (ParseServerInput(bpar, &bmai, ClntMsg) == -1) {
1825  DEBUG(ClntMsg);
1826  return ErrS(hs->ID,ei,bpar,bmai,0,kGSErrParseBuffer,ClntMsg.c_str(),stepstr);
1827  }
1828  //
1829  // Version
1830  DEBUG("version run by client: "<< hs->RemVers);
1831  DEBUG("options req by client: "<< hs->Options);
1832  //
1833  // Dump, if requested
1834  if (QTRACE(Dump)) {
1835  if (bmai) {
1836  bmsg.form("IN: bmai: %s", stepstr);
1837  bmai->Dump(bmsg.c_str());
1838  }
1839  }
1840  //
1841  // Check random challenge
1842  if (!CheckRtag(bmai, ClntMsg))
1843  return ErrS(hs->ID,ei,bpar,bmai,0,kGSErrBadRndmTag,stepstr,ClntMsg.c_str());
1844 
1845  // Extract the VOMS attrbutes, if required
1846  XrdCryptoX509ExportChain_t X509ExportChain = (sessionCF) ? sessionCF->X509ExportChain() : 0;
1847  if (!X509ExportChain) {
1848  // Error
1849  return ErrS(hs->ID,ei,0,0,0,kGSErrError,
1850  "crypto factory function for chain export not found");
1851  }
1852 
1853  //
1854  // Now action depens on the step
1855  switch (step) {
1856 
1857  case kXGC_certreq:
1858  //
1859  // Client required us to send our certificate and cipher DH public parameters:
1860  // add first this last one.
1861  // Extract buffer with public info for the cipher agreement
1862  if (!(bpub = hs->Rcip->Public(lpub)))
1863  return ErrS(hs->ID,ei,bpar,bmai,0, kGSErrNoPublic,
1864  "session",stepstr);
1865 
1866  // If client supports decoding of signed DH, do sign them
1867  if (hs->RemVers >= XrdSecgsiVersDHsigned) {
1868  bck = new XrdSutBucket(bpub,lpub,kXRS_cipher);
1869  if (sessionKsig) {
1870  //
1871  // Encrypt server DH public parameters with server key
1872  if (sessionKsig->EncryptPrivate(*bck) <= 0)
1873  return ErrS(hs->ID,ei,bpar,bmai,0, kGSErrExportPuK,
1874  "encrypting server DH public parameters",stepstr);
1875  } else {
1876  return ErrS(hs->ID,ei,bpar,bmai,0, kGSErrExportPuK,
1877  "server signing key undefined!",stepstr);
1878  }
1879  } else {
1880  // Previous naming
1881  bck = new XrdSutBucket(bpub,lpub,kXRS_puk);
1882  }
1883 
1884  //
1885  // Add it to the global list
1886  if (bpar->AddBucket(bck) != 0)
1887  return ErrS(hs->ID,ei,bpar,bmai,0, kGSErrAddBucket,
1888  "main",stepstr);
1889 
1890  //
1891  // Add bucket with list of supported ciphers
1892  if (bpar->AddBucket(DefCipher,kXRS_cipher_alg) != 0)
1893  return ErrS(hs->ID,ei,bpar,bmai,0,
1895  //
1896  // Add bucket with list of supported MDs
1897  if (bpar->AddBucket(DefMD,kXRS_md_alg) != 0)
1898  return ErrS(hs->ID,ei,bpar,bmai,0,
1900  //
1901  // Add the server certificate
1902  bpar->AddBucket(hs->Cbck);
1903 
1904  // We are done for the moment
1905  nextstep = kXGS_cert;
1906  break;
1907 
1908  case kXGC_cert:
1909  //
1910  // Client sent its own credentials: their are checked in
1911  // ParseServerInput, so if we are here they are OK
1912  kS_rc = kgST_ok;
1913  nextstep = kXGS_none;
1914 
1915  if (GMAPOpt > 0) {
1916  // Get name from gridmap
1917  String name;
1918  QueryGMAP(hs->Chain, hs->TimeStamp, name);
1919  DEBUG("username(s) associated with this DN: "<<name);
1920  if (name.length() <= 0) {
1921  // Grid map lookup failure
1922  if (GMAPOpt == 2) {
1923  // It was required, so we fail
1924  kS_rc = kgST_error;
1925  PRINT("ERROR: user mapping required, but lookup failed - failure");
1926  break;
1927  } else {
1928  NOTIFY("WARNING: user mapping lookup failed - use DN or DN-hash as name");
1929  }
1930  } else {
1931  //
1932  // Extract user login name, if any
1933  XrdSutBucket *bck = 0;
1934  String user;
1935  if ((bck = bmai->GetBucket(kXRS_user))) {
1936  bck->ToString(user);
1937  bmai->Deactivate(kXRS_user);
1938  }
1939  DEBUG("target user: "<<user);
1940  if (user.length() > 0) {
1941  // Check if the wanted username is authorized
1942  String u;
1943  int from = 0;
1944  bool ok = 0;
1945  while ((from = name.tokenize(u, from, ',')) != -1) {
1946  if (user == u) { ok = 1; break; }
1947  }
1948  if (ok) {
1949  name = u;
1950  DEBUG("DN mapping: requested user is authorized: name is '"<<name<<"'");
1951  } else {
1952  // The requested username is not in the list; we warn and default to the first
1953  // found (to be Globus compliant)
1954  if (name.find(',') != STR_NPOS) name.erase(name.find(','));
1955  PRINT("WARNING: user mapping lookup ok, but the requested user is not"
1956  " authorized ("<<user<<"). Instead, mapped as " << name << ".");
1957  }
1958  } else {
1959  // No username requested: we default to the first found (to be Globus compliant)
1960  if (name.find(',') != STR_NPOS) name.erase(name.find(','));
1961  DEBUG("user mapping lookup successful: name is '"<<name<<"'");
1962  }
1963  Entity.name = strdup(name.c_str());
1964  Entity.eaAPI->Add("gridmap.name", "1", true);
1965  }
1966  }
1967  // If not set, use DN
1968  if (!Entity.name || (strlen(Entity.name) <= 0)) {
1969  // No grid map: set the hash of the client DN as name
1970  if (!GMAPuseDNname && hs->Chain->EEChash()) {
1971  Entity.name = strdup(hs->Chain->EEChash());
1972  } else if (GMAPuseDNname && hs->Chain->EECname()) {
1973  Entity.name = strdup(hs->Chain->EECname());
1974  } else {
1975  PRINT("WARNING: DN missing: corruption? ");
1976  }
1977  }
1978 
1979  // Add the DN as default moninfo if requested (the authz plugin may change this)
1980  if (MonInfoOpt > 0 || ShowDN) {
1981  const char *theDN = hs->Chain->EECname();
1982  if (theDN) {
1983  if (ShowDN && !GMAPuseDNname) {
1984  PRINT(Entity.name<<" Subject DN='"<<theDN<<"'");
1985  }
1986  if (MonInfoOpt > 0) Entity.moninfo = strdup(theDN);
1987  }
1988  }
1989 
1990  if (VOMSAttrOpt > vatIgnore && VOMSFun) {
1991  // Fill the information needed by the external function
1992  if (VOMSCertFmt == 1) {
1993  // PEM base64
1994  bpxy = (*X509ExportChain)(hs->Chain, true);
1995  bpxy->ToString(spxy);
1996  delete bpxy;
1997  Entity.creds = strdup(spxy.c_str());
1998  Entity.credslen = spxy.length();
1999  } else {
2000  // Raw (opaque) format, to be used with XrdCrypto
2001  Entity.creds = (char *) hs->Chain;
2002  Entity.credslen = 0;
2003  }
2004  if ((*VOMSFun)(Entity) != 0) {
2005  vomsFailed = true;
2006  if (VOMSAttrOpt == vatRequire) {
2007  // Error
2008  kS_rc = kgST_error;
2009  PRINT("ERROR: the VOMS extraction plug-in reported "
2010  "authentication failure");
2011  break;
2012  }
2013  }
2014  NOTIFY("VOMS: Entity.vorg: "<< (Entity.vorg ? Entity.vorg : "<none>"));
2015  NOTIFY("VOMS: Entity.grps: "<< (Entity.grps ? Entity.grps : "<none>"));
2016  NOTIFY("VOMS: Entity.role: "<< (Entity.role ? Entity.role : "<none>"));
2017  NOTIFY("VOMS: Entity.endorsements: "<< (Entity.endorsements ? Entity.endorsements : "<none>"));
2018  }
2019 
2020  // Here prepare/extract the information for authorization
2021  spxy = "";
2022  bpxy = 0;
2023  if (AuthzFun && AuthzKey && (AuthzAlways || vomsFailed)) {
2024  // Fill the information needed by the external function
2025  if (AuthzCertFmt == 1) {
2026  // May have been already done
2027  if (!Entity.creds || (Entity.creds && Entity.credslen == 0)) {
2028  // PEM base64
2029  bpxy = (*X509ExportChain)(hs->Chain, true);
2030  bpxy->ToString(spxy);
2031  Entity.creds = strdup(spxy.c_str());
2032  Entity.credslen = spxy.length();
2033  // If not empty Entity.creds is a pointer to hs->Chain and
2034  // we need not to free it
2035  }
2036  } else {
2037  // May have been already done
2038  if (Entity.creds && Entity.credslen > 0) {
2039  // Entity.creds is in PEM form, we need to free it
2040  free(Entity.creds);
2041  // Raw (opaque) format, to be used with XrdCrypto
2042  Entity.creds = (char *) hs->Chain;
2043  Entity.credslen = 0;
2044  }
2045  }
2046  // Get the key
2047  char *key = 0;
2048  int lkey = 0;
2049  if ((lkey = (*AuthzKey)(Entity, &key)) < 0) {
2050  // Fatal error
2051  kS_rc = kgST_error;
2052  PRINT("ERROR: unable to get the key associated to this user");
2053  break;
2054  }
2055  const char *dn = (const char *)key;
2056  time_t now = hs->TimeStamp;
2057  // We may have it in the cache
2058  XrdSutCERef ceref;
2059  bool rdlock = false;
2060  XrdSutCacheArg_t arg = {kCE_ok, now, AuthzCacheTimeOut, kCE_disabled};
2061  XrdSutCacheEntry *cent = cacheAuthzFun.Get(dn, rdlock, AuthzFunCheck, (void *) &arg);
2062  if (!cent) {
2063  // Fatal error
2064  kS_rc = kgST_error;
2065  PRINT("ERROR: unable to get cache entry for dn: "<<dn);
2066  break;
2067  }
2068  ceref.Set(&(cent->rwmtx));
2069  if (!rdlock) {
2070  if (cent->buf1.buf)
2071  FreeEntity((XrdSecEntity *) cent->buf1.buf);
2072  SafeDelete(cent->buf1.buf);
2073  SafeDelete(cent->buf2.buf);
2074  }
2075  if (cent->status != kCE_ok) {
2076  int authzrc = 0;
2077  if ((authzrc = (*AuthzFun)(Entity)) != 0) {
2078  // Error
2079  kS_rc = kgST_error;
2080  PRINT("ERROR: the authz plug-in reported failure");
2081  SafeDelete(key);
2082  ceref.UnLock();
2083  break;
2084  } else {
2085  cent->status = kCE_ok;
2086  // Save a copy of the relevant Entity fields
2087  XrdSecEntity *se = new XrdSecEntity();
2088  int slen = 0;
2089  CopyEntity(&Entity, se, &slen);
2090  FreeEntity((XrdSecEntity *) cent->buf1.buf);
2091  SafeDelete(cent->buf1.buf);
2092  cent->buf1.buf = (char *) se;
2093  cent->buf1.len = slen;
2094  // Proxy expiration time
2095  int notafter = hs->Chain->End() ? hs->Chain->End()->NotAfter() : -1;
2096  cent->buf2.buf = (char *) new int(notafter);
2097  cent->buf2.len = sizeof(int);
2098  // Fill up the rest
2099  cent->cnt = 0;
2100  cent->mtime = now; // creation time
2101  // Notify
2102  DEBUG("Saved Entity to cacheAuthzFun ("<<slen<<" bytes)");
2103  }
2104  } else {
2105  // Fetch a copy of the saved entity
2106  int slen = 0;
2107  FreeEntity(&Entity);
2108  CopyEntity((XrdSecEntity *) cent->buf1.buf, &Entity, &slen);
2109  // Notify
2110  DEBUG("Got Entity from cacheAuthzFun ("<<slen<<" bytes)");
2111  }
2112  // Release lock
2113  ceref.UnLock();
2114  // Cleanup
2115  SafeDelArray(key);
2116  }
2117 
2118  // Export proxy for authorization, if required
2119  if (AuthzPxyWhat >= azFull) {
2120  if (bpxy && AuthzPxyWhat == azLast) {
2121  SafeDelete(bpxy); spxy = "";
2123  Entity.credslen = 0;
2124  }
2125  if (!bpxy) {
2126  if (AuthzPxyWhat == 1 && hs->Chain->End()) {
2127  bpxy = hs->Chain->End()->Export();
2128  } else {
2129  bpxy = (*X509ExportChain)(hs->Chain, true);
2130  }
2131  bpxy->ToString(spxy);
2132  }
2133  if (AuthzPxyWhere == azCred) {
2134  Entity.creds = strdup(spxy.c_str());
2135  Entity.credslen = spxy.length();
2136  } else {
2137  // This should be deprecated
2138  Entity.endorsements = strdup(spxy.c_str());
2139  }
2140  delete bpxy;
2141  NOTIFY("Entity.endorsements: "<<(void *)Entity.endorsements);
2142  NOTIFY("Entity.creds: "<<(void *)Entity.creds);
2143  NOTIFY("Entity.credslen: "<<Entity.credslen);
2144 
2145  } else if (bpxy) {
2146  // Cleanup
2147  SafeDelete(bpxy); spxy = "";
2148  }
2149 
2150  if (hs->RemVers >= 10100) {
2151  if (hs->PxyChain) {
2152  // The client is going to send over info for delegation
2153  kS_rc = kgST_more;
2154  nextstep = kXGS_pxyreq;
2155  }
2156  }
2157 
2158  break;
2159 
2160  case kXGC_sigpxy:
2161  //
2162  // Nothing to do after this
2163  kS_rc = kgST_ok;
2164  nextstep = kXGS_none;
2165  //
2166  // If something went wrong, print explanation
2167  if (ClntMsg.length() > 0) {
2168  PRINT(ClntMsg);
2169  }
2170  break;
2171 
2172  default:
2173  return ErrS(hs->ID,ei,bpar,bmai,0, kGSErrBadOpt, stepstr);
2174  }
2175 
2176  if (kS_rc == kgST_more) {
2177  //
2178  // Add message to client
2179  if (ClntMsg.length() > 0)
2180  if (bmai->AddBucket(ClntMsg,kXRS_message) != 0) {
2181  NOTIFY("problems adding bucket with message for client");
2182  }
2183  //
2184  // Serialize, encrypt and add to the global list
2185  if (AddSerialized('s', nextstep, hs->ID,
2186  bpar, bmai, kXRS_main, sessionKey) != 0) {
2187  return ErrS(hs->ID,ei,bpar,bmai,0, kGSErrSerialBuffer,
2188  "main / session cipher",stepstr);
2189  }
2190  //
2191  // Serialize the global buffer
2192  char *bser = 0;
2193  int nser = bpar->Serialized(&bser,'f');
2194  //
2195  // Dump, if requested
2196  if (QTRACE(Authen)) {
2197  bmsg.form("OUT: bpar: %s", ServerStepStr(bpar->GetStep()));
2198  bpar->Dump(bmsg.c_str());
2199  bmsg.form("OUT: bmai: %s", ServerStepStr(bpar->GetStep()));
2200  bmai->Dump(bmsg.c_str());
2201  }
2202  //
2203  // Create buffer for client
2204  *parms = new XrdSecParameters(bser,nser);
2205 
2206  } else {
2207  //
2208  // Cleanup handshake vars
2209  SafeDelete(hs);
2210  }
2211  //
2212  // We may release the buffers now
2213  REL2(bpar,bmai);
2214  //
2215  // All done
2216  return kS_rc;
2217 }
2218 
2219 /******************************************************************************/
2220 /* C o p y E n t i ty */
2221 /******************************************************************************/
2222 
2223 void XrdSecProtocolgsi::CopyEntity(XrdSecEntity *in, XrdSecEntity *out, int *lout)
2224 {
2225  // Copy relevant fields of 'in' into 'out'; return length of 'out'
2226 
2227  if (!in || !out) return;
2228 
2229  int slen = sizeof(XrdSecEntity);
2230  if (in->name) { out->name = strdup(in->name); slen += strlen(in->name); }
2231  if (in->host) { out->host = strdup(in->host); slen += strlen(in->host); }
2232  if (in->vorg) { out->vorg = strdup(in->vorg); slen += strlen(in->vorg); }
2233  if (in->role) { out->role = strdup(in->role); slen += strlen(in->role); }
2234  if (in->grps) { out->grps = strdup(in->grps); slen += strlen(in->grps); }
2235  if (in->creds && in->credslen > 0) {
2236  out->creds = strdup(in->creds); slen += in->credslen;
2237  out->credslen = in->credslen; }
2238  if (in->endorsements) { out->endorsements = strdup(in->endorsements);
2239  slen += strlen(in->endorsements); }
2240  if (in->moninfo) { out->moninfo = strdup(in->moninfo);
2241  slen += strlen(in->moninfo); }
2242 
2243  // Save length, if required
2244  if (lout) *lout = slen;
2245 
2246  // Done
2247  return;
2248 }
2249 
2250 /******************************************************************************/
2251 /* F r e e E n t i ty */
2252 /******************************************************************************/
2253 
2254 void XrdSecProtocolgsi::FreeEntity(XrdSecEntity *in)
2255 {
2256  // Free relevant fields of 'in';
2257 
2258  if (!in) return;
2259 
2260  if (in->name) SafeFree(in->name);
2261  if (in->host) SafeFree(in->host);
2262  if (in->vorg) SafeFree(in->vorg);
2263  if (in->role) SafeFree(in->role);
2264  if (in->grps) SafeFree(in->grps);
2265  if (in->creds && in->credslen > 0) { SafeFree(in->creds); in->credslen = 0; }
2266  if (in->endorsements) SafeFree(in->endorsements);
2267  if (in->moninfo) SafeFree(in->moninfo);
2268 
2269  // Done
2270  return;
2271 }
2272 
2273 /******************************************************************************/
2274 /* E n a b l e T r a c i n g */
2275 /******************************************************************************/
2276 
2278 {
2279  // Initiate error logging and tracing
2280 
2281  eDest.logger(&Logger);
2282  GSITrace = new XrdOucTrace(&eDest);
2283  return GSITrace;
2284 }
2285 
2286 /******************************************************************************/
2287 /* g s i O p t i o n s :: P r i n t */
2288 /******************************************************************************/
2289 
2291 {
2292  // Dump summary of GSI init options
2293 // EPNAME("InitOpts");
2294 
2295  // For clients print only if really required (for servers we notified it
2296  // always once for all)
2297  if ((mode == 'c') && debug <= 0) return;
2298 
2299  POPTS(t, " -------------------------------------------------------------------");
2300  POPTS(t, " Mode: "<< ((mode == 'c') ? "client" : "server"));
2301  POPTS(t, " Debug: "<< debug);
2302  POPTS(t, " CA dir: " << (certdir ? certdir : XrdSecProtocolgsi::CAdir));
2303  POPTS(t, " CA verification level: "<< getOptName(caVerOpts, ca));
2304  POPTS(t, " CRL dir: " << (crldir ? crldir : XrdSecProtocolgsi::CRLdir ));
2305  POPTS(t, " CRL extension: " << (crlext ? crlext : XrdSecProtocolgsi::DefCRLext));
2306  POPTS(t, " CRL check level: "<< getOptName(crlOpts,crl));
2307  if (crl > 0) POPTS(t, " CRL refresh time: "<< crlrefresh);
2308  if (mode == 'c') {
2309  POPTS(t, " Certificate: " << (cert ? cert : XrdSecProtocolgsi::UsrCert));
2310  POPTS(t, " Key: " << (key ? key : XrdSecProtocolgsi::UsrKey));
2311  POPTS(t, " Proxy file: " << XrdSecProtocolgsi::UsrProxy);
2312  POPTS(t, " Proxy validity: " << (valid ? valid : XrdSecProtocolgsi::PxyValid));
2313  POPTS(t, " Proxy dep length: " << deplen);
2314  POPTS(t, " Proxy bits: " << bits);
2315  POPTS(t, " Proxy sign option: "<< sigpxy);
2316  POPTS(t, " Proxy delegation option: "<< dlgpxy);
2317  if (createpxy) POPTS(t, " Pure Cert/Key authentication allowed");
2318  POPTS(t, " Allowed server names: "<< (srvnames ? srvnames : "[*/]<target host name>[/*]"));
2319  } else {
2320  POPTS(t, " Certificate: " << (cert ? cert : XrdSecProtocolgsi::SrvCert));
2321  POPTS(t, " Key: " << (key ? key : XrdSecProtocolgsi::SrvKey));
2322  POPTS(t, " Proxy delegation option: "<< getOptName(sDlgOpts,dlgpxy));
2323  if (exppxy)
2324  POPTS(t, " Template for exported proxy: "<< (exppxy ? exppxy : gUsrPxyDef));
2325  POPTS(t, " GRIDmap file: " << (gridmap ? gridmap : XrdSecProtocolgsi::GMAPFile));
2326  POPTS(t, " GRIDmap option: "<< getOptName(gmoOpts,ogmap));
2327  POPTS(t, " GRIDmap cache entries expiration (secs): "<< gmapto);
2328  if (gmapfun) {
2329  POPTS(t, " DN mapping function: " << gmapfun);
2330  if (gmapfunparms) POPTS(t, " DN mapping function parms: " << gmapfunparms);
2331  } else {
2332  if (gmapfunparms) POPTS(t, " DN mapping function parms: ignored (no mapping function defined)");
2333  }
2334  if (authzfun) {
2335  POPTS(t, " Authz function: " << authzfun);
2336  if (authzfunparms) POPTS(t, " Authz function parms: " << authzfunparms);
2337  POPTS(t, " Authz call: " <<getOptName(azCallOpts,authzcall));
2338  POPTS(t, " Authz cache entries expiration (secs): " << authzto);
2339  } else {
2340  if (authzfunparms) POPTS(t, " Authz function parms: ignored (no authz function defined)");
2341  }
2342  if (authzpxy)
2343  POPTS(t, " Client proxy availability in XrdSecEntity.endorsement: "<< getOptName(azPxyOpts,authzpxy));
2344  POPTS(t, " VOMS option: "<< getOptName(vomsatOpts,vomsat));
2345  if (vomsfun) {
2346  POPTS(t, " VOMS extraction function: " << vomsfun);
2347  if (vomsfunparms) POPTS(t, " VOMS extraction function parms: " << vomsfunparms);
2348  } else {
2349  if (vomsfunparms) POPTS(t, " VOMS extraction function parms: ignored (no VOMS extraction function defined)");
2350  }
2351  POPTS(t, " MonInfo option: "<< moninfo);
2352  if (!hashcomp)
2353  POPTS(t, " Name hashing algorithm compatibility OFF");
2354  POPTS(t, " Show DN option: "<<showDN);
2355  }
2356  // Crypto options
2357  POPTS(t, " Crypto modules: "<< (clist ? clist : XrdSecProtocolgsi::DefCrypto));
2358  POPTS(t, " Ciphers: "<< (cipher ? cipher : XrdSecProtocolgsi::DefCipher));
2359  POPTS(t, " MDigests: "<< (md ? md : XrdSecProtocolgsi::DefMD));
2360  if (trustdns) {
2361  POPTS(t, " Trusting DNS for hostname checking");
2362  } else {
2363  POPTS(t, " Untrusting DNS for hostname checking");
2364  }
2365  POPTS(t, " -------------------------------------------------------------------");
2366 }
2367 
2368 /******************************************************************************/
2369 /* X r d S e c P r o t o c o l g s i I n i t */
2370 /******************************************************************************/
2371 
2372 extern "C"
2373 {
2374 char *XrdSecProtocolgsiInit(const char mode,
2375  const char *parms, XrdOucErrInfo *erp)
2376 {
2377  // One-time protocol initialization, filling the static flags and options
2378  // of the protocol.
2379  // For clients (mode == 'c') we use values in envs.
2380  // For servers (mode == 's') the command line options are passed through
2381  // parms.
2382  EPNAME("ProtocolgsiInit");
2383 
2384  gsiOptions opts;
2385  char *rc = (char *)"";
2386  char *cenv = 0;
2387 
2388  // Initiate error logging and tracing
2390 
2391  //
2392  // Clients first
2393  if (mode == 'c') {
2394  //
2395  // Decode envs:
2396  // "XrdSecDEBUG" debug flag ("0","1","2","3")
2397  // "XrdSecGSICADIR" full path to an alternative path
2398  // containing the CA info
2399  // [/etc/grid-security/certificates]
2400  // "XrdSecGSICRLDIR" full path to an alternative path
2401  // containing the CRL info
2402  // [/etc/grid-security/certificates]
2403  // "XrdSecGSICRLEXT" default extension of CRL files [.r0]
2404  // "XrdSecGSIUSERCERT" full path to an alternative file
2405  // containing the user certificate
2406  // [$HOME/.globus/usercert.pem]
2407  // "XrdSecGSIUSERKEY" full path to an alternative file
2408  // containing the user key
2409  // [$HOME/.globus/userkey.pem]
2410  // "XrdSecGSIUSERPROXY" full path to an alternative file
2411  // containing the user proxy
2412  // [/tmp/x509up_u<uid>]
2413  // "XrdSecGSIPROXYVALID" validity of proxies in the
2414  // grid-proxy-init format
2415  // ["12:00", i.e. 12 hours]
2416  // "XrdSecGSIPROXYDEPLEN" depth of signature path for proxies;
2417  // use -1 for unlimited [0]
2418  // "XrdSecGSIPROXYKEYBITS" bits in PKI for proxies [default: XrdCryptoDefRSABits]
2419  // "XrdSecGSICACHECK" CA check level [1]:
2420  // 0 do not verify;
2421  // 1 verify if self-signed, warn if not;
2422  // 2 verify in all cases, fail if not possible
2423  // "XrdSecGSICRLCHECK" CRL check level [2]:
2424  // 0 don't care;
2425  // 1 use if available;
2426  // 2 require,
2427  // 3 require non-expired CRL
2428  // "XrdSecGSIDELEGPROXY" Forwarding of credentials option:
2429  // 0 deny; 1 sign request created
2430  // by server; 2 forward local proxy
2431  // (include private key) [1]
2432  // "XrdSecGSICREATEPROXY" Controls use of proxy [1]:
2433  // 1 auto-generate proxy from the cert/key pair if no one is not found
2434  // 0 a proxy is used if present; else, the cert/key pair is used if present.
2435  // "XrdSecGSISRVNAMES" Server names allowed: if the server CN
2436  // does not match any of these, or it is
2437  // explicitely denied by these, or it is
2438  // not in the form "*/<hostname>", the
2439  // handshake fails.
2440  // "XrdSecGSIUSEDEFAULTHASH" If this variable is set only the default
2441  // name hashing algorithm is used
2442 
2443  //
2444  opts.mode = mode;
2445  // debug
2446  cenv = getenv("XrdSecDEBUG");
2447  if (cenv)
2448  {if (cenv[0] >= 49 && cenv[0] <= 51) opts.debug = atoi(cenv);
2449  else {PRINT("unsupported debug value from env XrdSecDEBUG: "<<cenv<<" - setting to 1");
2450  opts.debug = 1;
2451  }
2452  }
2453 
2454  // directory with CA certificates
2455  cenv = (getenv("XrdSecGSICADIR") ? getenv("XrdSecGSICADIR")
2456  : getenv("X509_CERT_DIR"));
2457  if (cenv)
2458  opts.certdir = strdup(cenv);
2459 
2460  // directory with CRL info
2461  cenv = (getenv("XrdSecGSICRLDIR") ? getenv("XrdSecGSICRLDIR")
2462  : getenv("X509_CERT_DIR"));
2463  if (cenv)
2464  opts.crldir = strdup(cenv);
2465 
2466  // Default extension CRL files
2467  cenv = getenv("XrdSecGSICRLEXT");
2468  if (cenv)
2469  opts.crlext = strdup(cenv);
2470 
2471  // CRL refresh or expiration time
2472  cenv = getenv("XrdSecGSICRLRefresh");
2473  if (cenv)
2474  opts.crlrefresh = atoi(cenv);
2475 
2476  // file with user cert
2477  cenv = (getenv("XrdSecGSIUSERCERT") ? getenv("XrdSecGSIUSERCERT")
2478  : getenv("X509_USER_CERT"));
2479  if (cenv)
2480  opts.cert = strdup(cenv);
2481 
2482  // file with user key
2483  cenv = (getenv("XrdSecGSIUSERKEY") ? getenv("XrdSecGSIUSERKEY")
2484  : getenv("X509_USER_KEY"));
2485  if (cenv)
2486  opts.key = strdup(cenv);
2487 
2488  // file with user proxy
2489  cenv = (getenv("XrdSecGSIUSERPROXY") ? getenv("XrdSecGSIUSERPROXY")
2490  : getenv("X509_USER_PROXY"));
2491  if (cenv)
2492  opts.proxy = strdup(cenv);
2493 
2494  // file with user proxy
2495  cenv = getenv("XrdSecGSIPROXYVALID");
2496  if (cenv)
2497  opts.valid = strdup(cenv);
2498 
2499  // Depth of signature path for proxies
2500  cenv = getenv("XrdSecGSIPROXYDEPLEN");
2501  if (cenv)
2502  opts.deplen = atoi(cenv);
2503 
2504  // Key Bit length
2505  cenv = getenv("XrdSecGSIPROXYKEYBITS");
2506  if (cenv)
2507  opts.bits = atoi(cenv);
2508 
2509  // CA verification level
2510  cenv = getenv("XrdSecGSICACHECK");
2511  if (cenv)
2512  opts.ca = atoi(cenv);
2513 
2514  // CRL check level
2515  cenv = getenv("XrdSecGSICRLCHECK");
2516  if (cenv)
2517  opts.crl = atoi(cenv);
2518 
2519  // Delegate proxy
2520  cenv = getenv("XrdSecGSIDELEGPROXY");
2521  if (cenv)
2522  opts.dlgpxy = atoi(cenv);
2523 
2524  // No proxy
2525  cenv = getenv("XrdSecGSICREATEPROXY");
2526  if (cenv)
2527  opts.createpxy = atoi(cenv);
2528 
2529  // Allowed server name formats
2530  cenv = getenv("XrdSecGSISRVNAMES");
2531  if (cenv)
2532  opts.srvnames = strdup(cenv);
2533 
2534  // Name hashing algorithm
2535  cenv = getenv("XrdSecGSIUSEDEFAULTHASH");
2536  if (cenv)
2537  opts.hashcomp = 0;
2538 
2539  // DNS trusting control
2540  if ((cenv = getenv("XrdSecGSITRUSTDNS")))
2541  opts.trustdns = (!strcmp(cenv, "0")) ? false : true;
2542 
2543  //
2544  // Setup the object with the chosen options
2545  rc = XrdSecProtocolgsi::Init(opts,erp);
2546 
2547  // Notify init options, if required or in case of init errors
2548  if (!rc) opts.debug = 1;
2549  opts.Print(gsiTrace);
2550 
2551  // Some cleanup
2552  SafeFree(opts.certdir);
2553  SafeFree(opts.crldir);
2554  SafeFree(opts.crlext);
2555  SafeFree(opts.cert);
2556  SafeFree(opts.key);
2557  SafeFree(opts.proxy);
2558  SafeFree(opts.valid);
2559  SafeFree(opts.srvnames);
2560 
2561  // We are done
2562  return rc;
2563  }
2564 
2565  // Take into account xrootd debug flag
2566  cenv = getenv("XRDDEBUG");
2567  if (cenv && !strcmp(cenv,"1")) opts.debug = 1;
2568 
2569  //
2570  // Server initialization
2571  if (parms) {
2572  //
2573  // Duplicate the parms
2574  char parmbuff[1024];
2575  strlcpy(parmbuff, parms, sizeof(parmbuff));
2576  //
2577  // The tokenizer
2578  XrdOucTokenizer inParms(parmbuff);
2579  //
2580  // Decode parms:
2581  // for servers:
2582  // [-d:<debug_level>]
2583  // [-c:[-]ssl[:[-]<CryptoModuleName]]
2584  // [-certdir:<dir_with_CA_info>]
2585  // [-crldir:<dir_with_CRL_info>]
2586  // [-crlext:<default_extension_CRL_files>]
2587  // [-cert:<path_to_server_certificate>]
2588  // [-key:<path_to_server_key>]
2589  // [-cipher:<list_of_supported_ciphers>]
2590  // [-md:<list_of_supported_digests>]
2591  // [-ca:<crl_verification_level>]
2592  // [-crl:<crl_check_level>]
2593  // [-crlrefresh:<crl_refresh_time>]
2594  // [-gridmap:<grid_map_file>]
2595  // [-gmapfun:<grid_map_function>]
2596  // [-gmapfunparms:<grid_map_function_init_parameters>]
2597  // [-authzcall:<authz_callopt>]
2598  // [-authzfun:<authz_function>]
2599  // [-authzfunparms:<authz_function_init_parameters>]
2600  // [-authzto:<authz_cache_entry_validity_in_secs>]
2601  // [-gmapto:<grid_map_cache_entry_validity_in_secs>]
2602  // [-gmapopt:<grid_map_check_option>]
2603  // [-dlgpxy:<proxy_req_option>]
2604  // [-exppxy:<filetemplate>]
2605  // [-authzpxy]
2606  // [-vomsat:<voms_option>]
2607  // [-vomsfun:<voms_function>]
2608  // [-vomsfunparms:<voms_function_init_parameters>]
2609  // [-defaulthash]
2610  // [-trustdns:<0|1>]
2611  //
2612  int debug = -1;
2613  String clist = "";
2614  String certdir = "";
2615  String crldir = "";
2616  String crlext = "";
2617  String cert = "";
2618  String key = "";
2619  String cipher = "";
2620  String md = "";
2621  String gridmap = "";
2622  String gmapfun = "";
2623  String gmapfunparms = "";
2624  String authzfun = "";
2625  String authzfunparms = "";
2626  String vomsfun = "";
2627  String vomsfunparms = "";
2628  String exppxy = "";
2629  int ca = 1;
2630  int crl = 1;
2631  int crlrefresh = 86400;
2632  int ogmap = 1;
2633  int gmapto = 600;
2634  int authzto = -1;
2635  int authzcall = 1;
2636  int dlgpxy = dlgIgnore;
2637  int authzpxy = 0;
2638  int vomsat = vatIgnore; // Was 1 or extract
2639  int moninfo = 0;
2640  int hashcomp = 1;
2641  int trustdns = false;
2642  int showDN = false;
2643  char *op = 0;
2644  while (inParms.GetLine()) {
2645  while ((op = inParms.GetToken())) {
2646  if (!strncmp(op, "-d:",3)) {
2647  debug = atoi(op+3);
2648  } else if (!strncmp(op, "-c:",3)) {
2649  clist = (const char *)(op+3);
2650  } else if (!strncmp(op, "-certdir:",9)) {
2651  certdir = (const char *)(op+9);
2652  } else if (!strncmp(op, "-crldir:",8)) {
2653  crldir = (const char *)(op+8);
2654  } else if (!strncmp(op, "-crlext:",8)) {
2655  crlext = (const char *)(op+8);
2656  } else if (!strncmp(op, "-cert:",6)) {
2657  cert = (const char *)(op+6);
2658  } else if (!strncmp(op, "-key:",5)) {
2659  key = (const char *)(op+5);
2660  } else if (!strncmp(op, "-cipher:",8)) {
2661  cipher = (const char *)(op+8);
2662  } else if (!strncmp(op, "-md:",4)) {
2663  md = (const char *)(op+4);
2664  } else if (!strncmp(op, "-ca:",4)) {
2665  ca = getOptVal(caVerOpts, op+4);
2666  ca = atoi(op+4);
2667  } else if (!strncmp(op, "-crl:",5)) {
2668  crl = getOptVal(crlOpts, op+5);
2669  } else if (!strncmp(op, "-crlrefresh:",12)) {
2670  crlrefresh = atoi(op+12);
2671  } else if (!strncmp(op, "-gmapopt:",9)) {
2672  ogmap = getOptVal(gmoOpts, op+9);
2673  } else if (!strncmp(op, "-gridmap:",9)) {
2674  gridmap = (const char *)(op+9);
2675  } else if (!strncmp(op, "-gmapfun:",9)) {
2676  gmapfun = (const char *)(op+9);
2677  } else if (!strncmp(op, "-gmapfunparms:",14)) {
2678  gmapfunparms = (const char *)(op+14);
2679  } else if (!strncmp(op, "-authzcall:",11)) {
2680  authzcall = getOptVal(azCallOpts, op+11);
2681  } else if (!strncmp(op, "-authzfun:",10)) {
2682  authzfun = (const char *)(op+10);
2683  } else if (!strncmp(op, "-authzfunparms:",15)) {
2684  authzfunparms = (const char *)(op+15);
2685  } else if (!strncmp(op, "-authzto:",9)) {
2686  authzto = atoi(op+9);
2687  } else if (!strncmp(op, "-gmapto:",8)) {
2688  gmapto = atoi(op+8);
2689  } else if (!strncmp(op, "-dlgpxy:",8)) {
2690  opts.dlgpxy = getOptVal(sDlgOpts, op+8);
2691  } else if (!strncmp(op, "-exppxy:",8)) {
2692  exppxy = (const char *)(op+8);
2693  } else if (!strncmp(op, "-authzpxy:",10)) {
2694  opts.authzpxy = getOptVal(azPxyOpts, op+10);
2695  } else if (!strncmp(op, "-authzpxy",9)) {
2696  authzpxy = 11;
2697  } else if (!strncmp(op, "-vomsat:",8)) {
2698  vomsat = getOptVal(vomsatOpts, op+8);
2699  if (vomsat != vatIgnore && vomsfun.length() == 0)
2700  vomsfun = "default";
2701  } else if (!strncmp(op, "-vomsfun:",9)) {
2702  vomsfun = (const char *)(op+9);
2703  } else if (!strncmp(op, "-vomsfunparms:",14)) {
2704  vomsfunparms = (const char *)(op+14);
2705  } else if (!strcmp(op, "-moninfo")) {
2706  moninfo = 1;
2707  } else if (!strncmp(op, "-moninfo:",9)) {
2708  moninfo = atoi(op+9);
2709  } else if (!strcmp(op, "-defaulthash")) {
2710  hashcomp = 0;
2711  } else if (!strncmp(op, "-trustdns:",10)) {
2712  trustdns = getOptVal(tdnsOpts, op+10);
2713  } else if (!strncmp(op, "-showdn:",8)) {
2714  showDN = getOptVal(tdnsOpts, op+8);
2715  } else {
2716  PRINT("ignoring unknown switch: "<<op);
2717  }
2718  }
2719  }
2720 
2721  // If vomsfun is 'default' substitute the default plugin. The go on to
2722  // resolve conflicts between vomsfun and vomsat options. So, if vomsfun
2723  // was specified but vomsat is set to 'ignore' then we set vomsat to be
2724  // 'required'.
2725  //
2726  if (vomsfun.length() > 0)
2727  {if (vomsat == vatIgnore) vomsat = vatExtract;
2728  if (vomsfun == "default") vomsfun = LIB_XRDVOMS;
2729  } else authzcall = azAlways;
2730 
2731  //
2732  // Build the option object
2733  opts.debug = (debug > -1) ? debug : opts.debug;
2734  opts.mode = 's';
2735  opts.ca = ca;
2736  opts.crl = crl;
2737  opts.crlrefresh = crlrefresh;
2738  opts.ogmap = ogmap;
2739  opts.gmapto = gmapto;
2740  opts.authzcall = authzcall;
2741  opts.authzto = authzto;
2742  opts.dlgpxy = (dlgpxy >= dlgIgnore && dlgpxy <= dlgReqSign) ? dlgpxy : 0;
2743  opts.authzpxy = authzpxy;
2744  opts.vomsat = vomsat;
2745  opts.moninfo = moninfo;
2746  opts.hashcomp = hashcomp;
2747  opts.trustdns = (trustdns <= 0) ? false : true;
2748  opts.showDN = (showDN > 0) ? true : false;
2749  if (clist.length() > 0)
2750  opts.clist = (char *)clist.c_str();
2751  if (certdir.length() > 0)
2752  opts.certdir = (char *)certdir.c_str();
2753  if (crldir.length() > 0)
2754  opts.crldir = (char *)crldir.c_str();
2755  if (crlext.length() > 0)
2756  opts.crlext = (char *)crlext.c_str();
2757  if (cert.length() > 0)
2758  opts.cert = (char *)cert.c_str();
2759  if (key.length() > 0)
2760  opts.key = (char *)key.c_str();
2761  if (cipher.length() > 0)
2762  opts.cipher = (char *)cipher.c_str();
2763  if (md.length() > 0)
2764  opts.md = (char *)md.c_str();
2765  if (gridmap.length() > 0)
2766  opts.gridmap = (char *)gridmap.c_str();
2767  if (gmapfun.length() > 0)
2768  opts.gmapfun = (char *)gmapfun.c_str();
2769  if (gmapfunparms.length() > 0)
2770  opts.gmapfunparms = (char *)gmapfunparms.c_str();
2771  if (authzfun.length() > 0)
2772  opts.authzfun = (char *)authzfun.c_str();
2773  if (authzfunparms.length() > 0)
2774  opts.authzfunparms = (char *)authzfunparms.c_str();
2775  if (exppxy.length() > 0)
2776  opts.exppxy = (char *)exppxy.c_str();
2777  if (vomsfun.length() > 0)
2778  opts.vomsfun = (char *)vomsfun.c_str();
2779  if (vomsfunparms.length() > 0)
2780  opts.vomsfunparms = (char *)vomsfunparms.c_str();
2781 
2782  // Notify init options, if required
2783  opts.Print(gsiTrace);
2784 
2785  //
2786  // Setup the plug-in with the chosen options
2787  return XrdSecProtocolgsi::Init(opts,erp);
2788  }
2789 
2790  // Notify init options, if required
2791  opts.Print(gsiTrace);
2792  //
2793  // Setup the plug-in with the defaults
2794  return XrdSecProtocolgsi::Init(opts,erp);
2795 }}
2796 
2797 
2798 /******************************************************************************/
2799 /* X r d S e c P r o t o c o l g s i O b j e c t */
2800 /******************************************************************************/
2801 
2803 
2804 namespace
2805 {XrdVersionInfo *gsiVersion = &XrdVERSIONINFOVAR(XrdSecProtocolgsiObject);}
2806 
2807 extern "C"
2808 {
2810  const char *hostname,
2811  XrdNetAddrInfo &endPoint,
2812  const char *parms,
2813  XrdOucErrInfo *erp)
2814 {
2815  XrdSecProtocolgsi *prot;
2816  int options = XrdSecNOIPCHK;
2817 
2818  //
2819  // Get a new protocol object
2820  if (!(prot = new XrdSecProtocolgsi(options, hostname, endPoint, parms))) {
2821  const char *msg = "Secgsi: Insufficient memory for protocol.";
2822  if (erp)
2823  erp->setErrInfo(ENOMEM, msg);
2824  else
2825  std::cerr <<msg <<std::endl;
2826  return (XrdSecProtocol *)0;
2827  }
2828  //
2829  // We are done
2830  if (!erp)
2831  std::cerr << "protocol object instantiated" << std::endl;
2832  return prot;
2833 }}
2834 
2835 
2836 /******************************************************************************/
2837 /* P r i v a t e M e t h o d s */
2838 /******************************************************************************/
2839 
2840 //_________________________________________________________________________
2841 int XrdSecProtocolgsi::AddSerialized(char opt, kXR_int32 step, String ID,
2842  XrdSutBuffer *bls, XrdSutBuffer *buf,
2843  kXR_int32 type,
2844  XrdCryptoCipher *cip)
2845 {
2846  // Serialize buf, and add it encrypted to bls as bucket type
2847  // Cipher cip is used if defined; else PuK rsa .
2848  // If both are undefined the buffer is just serialized and added.
2849  EPNAME("AddSerialized");
2850 
2851  if (!bls || !buf || (opt != 0 && opt != 'c' && opt != 's')) {
2852  PRINT("invalid inputs ("
2853  <<bls<<","<<buf<<","<<opt<<")"
2854  <<" - type: "<<XrdSutBuckStr(type));
2855  return -1;
2856  }
2857 
2858  //
2859  // Add step to indicate the counterpart what we send
2860  if (step > 0) {
2861  bls->SetStep(step);
2862  buf->SetStep(step);
2863  hs->LastStep = step;
2864  }
2865 
2866  //
2867  // If a random tag has been sent and we have a session cipher,
2868  // we sign it
2869  XrdSutBucket *brt = buf->GetBucket(kXRS_rtag);
2870  if (brt && sessionKsig) {
2871  //
2872  // Encrypt random tag with session cipher
2873  if (sessionKsig->EncryptPrivate(*brt) <= 0) {
2874  PRINT("error encrypting random tag");
2875  return -1;
2876  }
2877  //
2878  // Update type
2879  brt->type = kXRS_signed_rtag;
2880  }
2881  //
2882  // Add an random challenge: if a next exchange is required this will
2883  // allow to prove authenticity of counter part
2884  //
2885  // Generate new random tag and create a bucket
2886  if (!(opt == 'c' && step == kXGC_sigpxy)) {
2887  String RndmTag;
2888  XrdSutRndm::GetRndmTag(RndmTag);
2889  //
2890  // Get bucket
2891  brt = 0;
2892  if (!(brt = new XrdSutBucket(RndmTag,kXRS_rtag))) {
2893  PRINT("error creating random tag bucket");
2894  return -1;
2895  }
2896  buf->AddBucket(brt);
2897  }
2898  //
2899  // Get cache entry
2900  if (!hs->Cref) {
2901  PRINT("cache entry not found: protocol error");
2902  return -1;
2903  }
2904  //
2905  // Add random tag to the cache and update timestamp
2906  hs->Cref->buf1.SetBuf(brt->buffer,brt->size);
2907  hs->Cref->mtime = (kXR_int32)hs->TimeStamp;
2908  //
2909  // Now serialize the buffer ...
2910  char *bser = 0;
2911  int nser = buf->Serialized(&bser);
2912  //
2913  // Update bucket with this content
2914  XrdSutBucket *bck = 0;;
2915  if (!(bck = bls->GetBucket(type))) {
2916  // or create new bucket, if not existing
2917  if (!(bck = new XrdSutBucket(bser,nser,type))) {
2918  PRINT("error creating bucket "
2919  <<" - type: "<<XrdSutBuckStr(type));
2920  return -1;
2921  }
2922  //
2923  // Add the bucket to the list
2924  bls->AddBucket(bck);
2925  } else {
2926  bck->Update(bser,nser);
2927  }
2928  //
2929  // Encrypted the bucket
2930  if (cip) {
2931  if (cip->Encrypt(*bck, useIV) == 0) {
2932  PRINT("error encrypting bucket - cipher "
2933  <<" - type: "<<XrdSutBuckStr(type));
2934  return -1;
2935  }
2936  }
2937  // We are done
2938  return 0;
2939 }
2940 
2941 //_________________________________________________________________________
2942 int XrdSecProtocolgsi::ParseClientInput(XrdSutBuffer *br, XrdSutBuffer **bm,
2943  String &cmsg)
2944 {
2945  // Parse received buffer b,
2946  // Result used to fill the handshake local variables
2947  EPNAME("ParseClientInput");
2948 
2949  // Space for pointer to main buffer must be already allocated
2950  if (!br || !bm) {
2951  PRINT("invalid inputs ("<<br<<","<<bm<<")");
2952  cmsg = "invalid inputs";
2953  return -1;
2954  }
2955 
2956  //
2957  // Get the step
2958  int step = br->GetStep();
2959 
2960  // Do the right action
2961  switch (step) {
2962  case kXGS_init:
2963  // Process message
2964  if (ClientDoInit(br, bm, cmsg) != 0)
2965  return -1;
2966  break;
2967  case kXGS_cert:
2968  // Process message
2969  if (ClientDoCert(br, bm, cmsg) != 0)
2970  return -1;
2971  break;
2972  case kXGS_pxyreq:
2973  // Process message
2974  if (ClientDoPxyreq(br, bm, cmsg) != 0)
2975  return -1;
2976  break;
2977  default:
2978  cmsg = "protocol error: unknown action: "; cmsg += step;
2979  return -1;
2980  break;
2981  }
2982 
2983  // We are done
2984  return 0;
2985 }
2986 
2987 //_________________________________________________________________________
2988 int XrdSecProtocolgsi::ClientDoInit(XrdSutBuffer *br, XrdSutBuffer **bm,
2989  String &emsg)
2990 {
2991  // Client side: process a kXGS_init message.
2992  // Return 0 on success, -1 on error. If the case, a message is returned
2993  // in cmsg.
2994  EPNAME("ClientDoInit");
2995 
2996  //
2997  // Create the main buffer as a copy of the buffer received
2998  if (!((*bm) = new XrdSutBuffer(br->GetProtocol(),br->GetOptions()))) {
2999  emsg = "error instantiating main buffer";
3000  return -1;
3001  }
3002  //
3003  // Extract server version from options
3004  String opts = br->GetOptions();
3005  int ii = opts.find("v:");
3006  if (ii >= 0) {
3007  String sver(opts,ii+2);
3008  sver.erase(sver.find(','));
3009  hs->RemVers = atoi(sver.c_str());
3010  } else {
3011  hs->RemVers = Version;
3012  emsg = "server version information not found in options:"
3013  " assume same as local";
3014  }
3015  // Set use IV depending on the remote version
3016  useIV = false;
3017  if (hs->RemVers >= XrdSecgsiVersDHsigned) {
3018  // Supports setting a unique IV in enc/dec operations
3019  useIV = true;
3020  }
3021  //
3022  // Create cache
3023  if (!(hs->Cref = new XrdSutPFEntry("c"))) {
3024  emsg = "error creating cache";
3025  return -1;
3026  }
3027  //
3028  // Save server version in cache
3029  hs->Cref->status = hs->RemVers;
3030  //
3031  // Set options
3032  hs->Options = PxyReqOpts;
3033  //
3034  // Extract list of crypto modules
3035  String clist;
3036  ii = opts.find("c:");
3037  if (ii >= 0) {
3038  clist.assign(opts, ii+2);
3039  clist.erase(clist.find(','));
3040  } else {
3041  NOTIFY("Crypto list missing: protocol error? (use defaults)");
3042  clist = DefCrypto;
3043  }
3044  // Parse the list loading the first we can
3045  if (ParseCrypto(clist) != 0) {
3046  emsg = "cannot find / load crypto requested modules :";
3047  emsg += clist;
3048  return -1;
3049  }
3050  //
3051  // Extract server certificate CA hashes
3052  String srvca;
3053  ii = opts.find("ca:");
3054  if (ii >= 0) {
3055  srvca.assign(opts, ii+3);
3056  srvca.erase(srvca.find(','));
3057  }
3058  // Parse the list loading the first we can
3059  if (ParseCAlist(srvca) != 0) {
3060  emsg = "unknown CA: cannot verify server certificate";
3061  hs->Chain = 0;
3062  return -1;
3063  }
3064 
3065  //
3066  // Extract no proxy option, if any
3067  bool createpxy = (PxyReqOpts & kOptsCreatePxy) ? 1 : 0;
3068  if (hs->RemVers < XrdSecgsiVersCertKey && !createpxy) {
3069  // Server does not accept pure cert files
3070  createpxy = 1;
3071  DEBUG("Server does not accept pure cert/key authentication: version < "<< (int)XrdSecgsiVersCertKey);
3072  }
3073 
3074  String clientcert = UsrCert, clientkey = UsrKey, clientproxy = UsrProxy;
3075  if (urlUsrCert.length()>0) clientcert = urlUsrCert;
3076  if (urlUsrKey.length()>0) clientkey = urlUsrKey;
3077  if (urlUsrProxy.length()>0) clientproxy = urlUsrProxy;
3078 
3079  //
3080  // Resolve place-holders in cert, key and proxy file paths, if any
3081  if (XrdSutResolve(clientcert, Entity.host, Entity.vorg, Entity.grps, Entity.name) != 0) {
3082  PRINT("Problems resolving templates in "<<clientcert);
3083  return -1;
3084  }
3085  if (XrdSutResolve(clientkey, Entity.host, Entity.vorg, Entity.grps, Entity.name) != 0) {
3086  PRINT("Problems resolving templates in "<<clientkey);
3087  return -1;
3088  }
3089  //
3090  // In the standard case we need to resolve also the proxy file path
3091  // Get the proxy path
3092  if (XrdSutResolve(clientproxy, Entity.host, Entity.vorg, Entity.grps, Entity.name) != 0) {
3093  PRINT("Problems resolving templates in "<<clientproxy);
3094  return -1;
3095  }
3096  //
3097  // Load / Attach-to user proxies
3098  ProxyIn_t pi = {clientcert.c_str(), clientkey.c_str(), CAdir.c_str(),
3099  clientproxy.c_str(), PxyValid.c_str(),
3100  DepLength, DefBits, createpxy};
3101  ProxyOut_t po = {hs->PxyChain, sessionKsig, hs->Cbck };
3102  if (QueryProxy(1, &cachePxy, clientproxy.c_str(),
3103  sessionCF, hs->TimeStamp, &pi, &po) != 0) {
3104  emsg = "error getting user proxies";
3105  hs->Chain = 0;
3106  return -1;
3107  }
3108 
3109  if (!po.cbck) {
3110  emsg = "failed to initialize user proxies";
3111  hs->Chain = 0;
3112  return -1;
3113  }
3114 
3115  // Save the result
3116  hs->PxyChain = po.chain;
3117  hs->Cbck = new XrdSutBucket(*((XrdSutBucket *)(po.cbck)));
3118  if (!po.ksig || !(sessionKsig = sessionCF->RSA(*(po.ksig)))) {
3119  emsg = "could not get a copy of the signing key:";
3120  hs->Chain = 0;
3121  return -1;
3122  }
3123  //
3124  // And we are done;
3125  return 0;
3126 }
3127 
3128 //_________________________________________________________________________
3129 int XrdSecProtocolgsi::ClientDoCert(XrdSutBuffer *br, XrdSutBuffer **bm,
3130  String &emsg)
3131 {
3132  // Client side: process a kXGS_cert message.
3133  // Return 0 on success, -1 on error. If the case, a message is returned
3134  // in cmsg.
3135  EPNAME("ClientDoCert");
3136  XrdSutBucket *bck = 0;
3137 
3138  //
3139  // make sure the cache is still there
3140  if (!hs->Cref) {
3141  emsg = "cache entry not found";
3142  hs->Chain = 0;
3143  return -1;
3144  }
3145  //
3146  // make sure is not too old
3147  int reftime = hs->TimeStamp - TimeSkew;
3148  if (hs->Cref->mtime < reftime) {
3149  emsg = "cache entry expired";
3150  // Remove: should not be checked a second time
3151  SafeDelete(hs->Cref);
3152  hs->Chain = 0;
3153  return -1;
3154  }
3155  //
3156  // Get from cache version run by server
3157  hs->RemVers = hs->Cref->status;
3158 
3159  //
3160  // Extract list of cipher algorithms supported by the server
3161  String cip = "";
3162  if ((bck = br->GetBucket(kXRS_cipher_alg))) {
3163  String ciplist;
3164  bck->ToString(ciplist);
3165  // Parse the list
3166  int from = 0;
3167  while ((from = ciplist.tokenize(cip, from, ':')) != -1) {
3168  if (cip.length() > 0)
3169  if (sessionCF->SupportedCipher(cip.c_str()))
3170  break;
3171  cip = "";
3172  }
3173  // Must have a common cipher algorithm
3174  if (cip.length() <= 0) {
3175  emsg = "no common cipher algorithm";
3176  hs->Chain = 0;
3177  return -1;
3178  }
3179  } else {
3180  NOTIFY("WARNING: list of ciphers supported by server missing"
3181  " - using default");
3182  }
3183 
3184  //
3185  // Extract server certificate
3186  if (!(bck = br->GetBucket(kXRS_x509))) {
3187  emsg = "server certificate missing";
3188  hs->Chain = 0;
3189  return -1;
3190  }
3191 
3192  //
3193  // Finalize chain: get a copy of it (we do not touch the reference)
3194  hs->Chain = new X509Chain(hs->Chain);
3195  if (!(hs->Chain)) {
3196  emsg = "cannot duplicate reference chain";
3197  return -1;
3198  }
3199  // The new chain must be deleted at destruction
3200  hs->Options |= kOptsDelChn;
3201 
3202  // Get hook to parsing function
3203  XrdCryptoX509ParseBucket_t ParseBucket = sessionCF->X509ParseBucket();
3204  if (!ParseBucket) {
3205  emsg = "cannot attach to ParseBucket function!";
3206  return -1;
3207  }
3208  // Parse bucket
3209  int nci = (*ParseBucket)(bck, hs->Chain);
3210  if (nci != 1) {
3211  emsg += nci;
3212  emsg += " vs 1 expected)";
3213  return -1;
3214  }
3215  //
3216  // Verify the chain
3217  x509ChainVerifyOpt_t vopt = {0,static_cast<int>(hs->TimeStamp),-1,hs->Crl};
3219  if (!(hs->Chain->Verify(ecode, &vopt))) {
3220  emsg = "certificate chain verification failed: ";
3221  emsg += hs->Chain->LastError();
3222  return -1;
3223  }
3224  //
3225  // Verify server identity using RFC2818 method
3226  //
3227 
3228  // First we check the SAN. If the check succeeds then we are all done.
3229  // Otherwise, if there is no SAN extension or if trustDNS is in effect,
3230  // we check if the common name matches.
3231  //
3232  DEBUG("Checking cert is for host " <<Entity.host);
3233 
3234  bool hasSAN, usedDNS = false;
3235  const char *wantHost = (Entity.host ? Entity.host : "");
3236 
3237  if (!hs->Chain->End()->MatchesSAN(Entity.host, hasSAN))
3238  {if (hasSAN && !TrustDNS)
3239  {emsg = "Unable to verify server hostname '"; emsg += wantHost;
3240  emsg+= "' using SAN extension; common name fallback disallowed.";
3241  return -1;
3242  }
3243  // If the common name check fails, TrustDNS allows fallback
3244  if (!ServerCertNameOK(hs->Chain->End()->Subject(),Entity.host,emsg))
3245  {if (!TrustDNS || Entity.addrInfo == 0 || expectedHost)
3246  {emsg = "Unable to verify server hostname '"; emsg += wantHost;
3247  emsg+= "' using common name; DNS fallback prohibited.";
3248  return -1;
3249  }
3250  // Use DNS to resolve possible alias name
3251  const char *name = Entity.addrInfo->Name();
3252  if (name == NULL)
3253  {emsg = "Unable to verify server hostname '"; emsg += wantHost;
3254  emsg+= "'; DNS fallback translation failed.";
3255  return -1;
3256  }
3257  DEBUG("TrustDNS: checking if cert is for host " <<name);
3258  usedDNS = true;
3259  bool hostOK = ServerCertNameOK(hs->Chain->End()->Subject(),name,emsg)
3260  || (hasSAN && hs->Chain->End()->MatchesSAN(name,hasSAN));
3261  if (!hostOK) return -1;
3262  }
3263  }
3264 
3265  // If we used the DNS then we must prohibit proxy delegation of any kind
3266  //
3267  // In the case of delegation, give client a chance to use XrdSecGSISRVNAMES
3268  // to limit where it is being redirected to. If the new destination does not
3269  // match XrdSecGSISRVNAMES, refuse to delegate.
3270  //
3271  if (usedDNS ||
3272  (SrvAllowedNames.length() > 0 &&
3273  !ServerCertNameOK(hs->Chain->End()->Subject(), NULL, emsg)))
3274  {if (hs->Options & (kOptsFwdPxy | kOptsSigReq))
3275  {hs->Options &= ~(kOptsFwdPxy | kOptsSigReq);
3276  std::cerr <<"secgsi: proxy delegation forbidden when trusting DNS "
3277  "to resolve '" <<wantHost <<"'!\n" <<std::flush;
3278  }
3279  }
3280 
3281  //
3282  // Extract the server key
3283  sessionKver = sessionCF->RSA(*(hs->Chain->End()->PKI()));
3284  if (!sessionKver || !sessionKver->IsValid()) {
3285  emsg = "server certificate contains an invalid key";
3286  return -1;
3287  }
3288  // Move next part to here, after sessionKver set, in order to
3289  // verify the signature of DH parameters
3290 
3291  //
3292  // If client supports decoding of signed DH, do sign them
3293  if (hs->RemVers >= XrdSecgsiVersDHsigned) {
3294 
3295  // Extract server public part for session cipher
3296  if (!(bck = br->GetBucket(kXRS_cipher))) {
3297  emsg = "server public part for session cipher missing";
3298  hs->Chain = 0;
3299  return -1;
3300  }
3301 
3302  // Encrypt server DH public parameters with server key
3303  if (sessionKver->DecryptPublic(*bck) <= 0) {
3304  emsg = "decrypting server DH public parameters";
3305  return -1;
3306  }
3307  } else {
3308 
3309  // Extract server public part for session cipher
3310  if (!(bck = br->GetBucket(kXRS_puk))) {
3311  emsg = "server public part for session cipher missing";
3312  hs->Chain = 0;
3313  return -1;
3314  }
3315 
3316  // If the server doesn't provide signed DH parameter, disable proxy delegation
3317  if (hs->Options & (kOptsFwdPxy | kOptsSigReq)) {
3318  hs->Options &= ~(kOptsFwdPxy | kOptsSigReq);
3319  PRINT("no signed DH parameters from " << Entity.host
3320  << ". Will not delegate x509 proxy to it");
3321  }
3322  }
3323 
3324  //
3325  // Initialize session cipher
3326  SafeDelete(sessionKey);
3327  if (!(sessionKey =
3328  sessionCF->Cipher(hs->HasPad, 0,bck->buffer,bck->size,cip.c_str())) || !(sessionKey->IsValid())) {
3329  PRINT("could not instantiate session cipher "
3330  "using cipher public info from server");
3331  emsg = "could not instantiate session cipher ";
3332  return -1;
3333  }
3334 
3335  //
3336  // Communicate the cipher name to server
3337  if (hs->RemVers >= XrdSecgsiVersDHsigned) {
3338  // Including the length of the IV if supported
3339  String cipiv;
3340  String::form(cipiv, "%s#%d", cip.c_str(), sessionKey->MaxIVLength());
3341  br->UpdateBucket(cipiv, kXRS_cipher_alg);
3342  } else {
3343  br->UpdateBucket(cip, kXRS_cipher_alg);
3344  }
3345 
3346  // Deactivate what not needed any longer
3347  if (hs->RemVers >= XrdSecgsiVersDHsigned) {
3348  br->Deactivate(kXRS_cipher);
3349  } else {
3350  br->Deactivate(kXRS_puk);
3351  }
3352  br->Deactivate(kXRS_x509);
3353 
3354  //
3355  // Extract list of MD algorithms supported by the server
3356  String md = "";
3357  if ((bck = br->GetBucket(kXRS_md_alg))) {
3358  String mdlist;
3359  bck->ToString(mdlist);
3360  // Parse the list
3361  int from = 0;
3362  while ((from = mdlist.tokenize(md, from, ':')) != -1) {
3363  if (md.length() > 0)
3364  if (sessionCF->SupportedMsgDigest(md.c_str()))
3365  break;
3366  md = "";
3367  }
3368  } else {
3369  NOTIFY("WARNING: list of digests supported by server missing"
3370  " - using default");
3371  md = "sha256";
3372  }
3373  if (!(sessionMD = sessionCF->MsgDigest(md.c_str()))) {
3374  emsg = "could not instantiate digest object";
3375  return -1;
3376  }
3377  // Communicate choice to server
3378  br->UpdateBucket(md, kXRS_md_alg);
3379 
3380  //
3381  // Extract the main buffer (it contains the random challenge
3382  // and will contain our credentials encrypted)
3383  XrdSutBucket *bckm = 0;
3384  if (!(bckm = br->GetBucket(kXRS_main))) {
3385  emsg = "main buffer missing";
3386  return -1;
3387  }
3388 
3389  //
3390  // Deserialize main buffer
3391  if (!((*bm) = new XrdSutBuffer(bckm->buffer,bckm->size))) {
3392  emsg = "error deserializing main buffer";
3393  return -1;
3394  }
3395 
3396  //
3397  // And we are done;
3398  return 0;
3399 }
3400 
3401 //_________________________________________________________________________
3402 int XrdSecProtocolgsi::ClientDoPxyreq(XrdSutBuffer *br, XrdSutBuffer **bm,
3403  String &emsg)
3404 {
3405  // Client side: process a kXGS_pxyreq message.
3406  // Return 0 on success, -1 on error. If the case, a message is returned
3407  // in cmsg.
3408  XrdSutBucket *bck = 0;
3409 
3410  //
3411  // Extract the main buffer (it contains the random challenge
3412  // and will contain our credentials encrypted)
3413  XrdSutBucket *bckm = 0;
3414  if (!(bckm = br->GetBucket(kXRS_main))) {
3415  emsg = "main buffer missing";
3416  return -1;
3417  }
3418  //
3419  // Decrypt the main buffer with the session cipher, if available
3420  if (sessionKey) {
3421  if (!(sessionKey->Decrypt(*bckm, useIV))) {
3422  emsg = "error with session cipher";
3423  return -1;
3424  }
3425  }
3426 
3427  //
3428  // Deserialize main buffer
3429  if (!((*bm) = new XrdSutBuffer(bckm->buffer,bckm->size))) {
3430  emsg = "error deserializing main buffer";
3431  return -1;
3432  }
3433 
3434  //
3435  // Check if we are ready to proces this
3436  if ((hs->Options & kOptsFwdPxy)) {
3437  // We have to send the private key of our proxy
3438  XrdCryptoX509 *pxy = 0;
3439  XrdCryptoRSA *kpxy = 0;
3440  if (!(hs->PxyChain) ||
3441  !(pxy = hs->PxyChain->End()) || !(kpxy = pxy->PKI())) {
3442  emsg = "local proxy info missing or corrupted";
3443  return 0;
3444  }
3445  // Send back the signed request as bucket
3446  String pri;
3447  if (kpxy->ExportPrivate(pri) != 0) {
3448  emsg = "problems exporting private key";
3449  return 0;
3450  }
3451  // Add it to the main list
3452  if ((*bm)->AddBucket(pri, kXRS_x509) != 0) {
3453  emsg = "problem adding bucket with private key to main buffer";
3454  return 0;
3455  }
3456  } else {
3457  // Proxy request: check if we are allowed to sign it
3458  if (!(hs->Options & kOptsSigReq)) {
3459  emsg = "Not allowed to sign proxy requests";
3460  return 0;
3461  }
3462  // Get the request
3463  if (!(bck = (*bm)->GetBucket(kXRS_x509_req))) {
3464  emsg = "bucket with proxy request missing";
3465  return 0;
3466  }
3467  XrdCryptoX509Req *req = sessionCF->X509Req(bck);
3468  if (!req) {
3469  emsg = "could not resolve proxy request";
3470  return 0;
3471  }
3472  req->SetVersion(hs->RemVers);
3473  // Get our proxy and its private key
3474  XrdCryptoX509 *pxy = 0;
3475  XrdCryptoRSA *kpxy = 0;
3476  if (!(hs->PxyChain) ||
3477  !(pxy = hs->PxyChain->End()) || !(kpxy = pxy->PKI())) {
3478  emsg = "local proxy info missing or corrupted";
3479  return 0;
3480  }
3481  // Sign the request
3482  XrdCryptoX509SignProxyReq_t X509SignProxyReq = (sessionCF) ? sessionCF->X509SignProxyReq() : 0;
3483  if (!X509SignProxyReq) {
3484  emsg = "problems getting method to sign request";
3485  return 0;
3486  }
3487  XrdCryptoX509 *npxy = 0;
3488  if ((*X509SignProxyReq)(pxy, kpxy, req, &npxy) != 0) {
3489  emsg = "problems signing the request";
3490  return 0;
3491  }
3492  delete req;
3493  (*bm)->Deactivate(kXRS_x509_req);
3494 
3495  // Send back the signed request as bucket
3496  if ((bck = npxy->Export())) {
3497  // Add it to the main list
3498  if ((*bm)->AddBucket(bck) != 0) {
3499  emsg = "problem adding signed request to main buffer";
3500  return 0;
3501  }
3502  }
3503  delete npxy; // has been allocated in *X509SignProxyReq
3504  }
3505 
3506  //
3507  // And we are done;
3508  return 0;
3509 
3510 }
3511 
3512 //_________________________________________________________________________
3513 int XrdSecProtocolgsi::ParseServerInput(XrdSutBuffer *br, XrdSutBuffer **bm,
3514  String &cmsg)
3515 {
3516  // Parse received buffer b, extracting and decrypting the main
3517  // buffer *bm and extracting the session
3518  // cipher, random tag buckets and user name, if any.
3519  // Results used to fill the local handshake variables
3520  EPNAME("ParseServerInput");
3521 
3522  // Space for pointer to main buffer must be already allocated
3523  if (!br || !bm) {
3524  PRINT("invalid inputs ("<<br<<","<<bm<<")");
3525  cmsg = "invalid inputs";
3526  return -1;
3527  }
3528 
3529  //
3530  // Get the step
3531  int step = br->GetStep();
3532 
3533  // Do the right action
3534  switch (step) {
3535  case kXGC_certreq:
3536  // Process message
3537  if (ServerDoCertreq(br, bm, cmsg) != 0)
3538  return -1;
3539  break;
3540  case kXGC_cert:
3541  // Process message
3542  if (ServerDoCert(br, bm, cmsg) != 0)
3543  return -1;
3544  break;
3545  case kXGC_sigpxy:
3546  // Process message
3547  if (ServerDoSigpxy(br, bm, cmsg) != 0)
3548  return -1;
3549  break;
3550  default:
3551  cmsg = "protocol error: unknown action: "; cmsg += step;
3552  return -1;
3553  break;
3554  }
3555 
3556  //
3557  // We are done
3558  return 0;
3559 }
3560 
3561 //_________________________________________________________________________
3562 int XrdSecProtocolgsi::ServerDoCertreq(XrdSutBuffer *br, XrdSutBuffer **bm,
3563  String &cmsg)
3564 {
3565  // Server side: process a kXGC_certreq message.
3566  // Return 0 on success, -1 on error. If the case, a message is returned
3567  // in cmsg.
3568  XrdSutCERef ceref;
3569  XrdSutBucket *bck = 0;
3570  XrdSutBucket *bckm = 0;
3571 
3572  //
3573  // Get version run by client, if there
3574  if (br->UnmarshalBucket(kXRS_version,hs->RemVers) != 0) {
3575  hs->RemVers = Version;
3576  cmsg = "client version information not found in options:"
3577  " assume same as local";
3578  } else {
3579  br->Deactivate(kXRS_version);
3580  }
3581  // Reset use IV; will be set in next round depending on the remote version
3582  useIV = false;
3583 
3584  //
3585  // Extract the main buffer
3586  if (!(bckm = br->GetBucket(kXRS_main))) {
3587  cmsg = "main buffer missing";
3588  return -1;
3589  }
3590  //
3591  // Extract bucket with crypto module
3592  if (!(bck = br->GetBucket(kXRS_cryptomod))) {
3593  cmsg = "crypto module specification missing";
3594  return -1;
3595  }
3596  String cmod;
3597  bck->ToString(cmod);
3598  // Parse the list loading the first we can
3599  if (ParseCrypto(cmod) != 0) {
3600  cmsg = "cannot find / load crypto requested module :";
3601  cmsg += cmod;
3602  return -1;
3603  }
3604  //
3605  // Extract bucket with client issuer hash
3606  if (!(bck = br->GetBucket(kXRS_issuer_hash))) {
3607  cmsg = "client issuer hash missing";
3608  return -1;
3609  }
3610  String cahash;
3611  bck->ToString(cahash);
3612  //
3613  // Check if we know it
3614  if (ParseCAlist(cahash) != 0) {
3615  cmsg = "unknown CA: cannot verify client credentials";
3616  return -1;
3617  }
3618  // Find our certificate in cache
3619  String cadum;
3620  XrdSutCacheEntry *cent = GetSrvCertEnt(ceref, sessionCF, hs->TimeStamp, cadum);
3621  if (!cent) {
3622  cmsg = "cannot find certificate: corruption?";
3623  return -1;
3624  }
3625 
3626  // Fill some relevant handshake variables
3627  sessionKsig = sessionCF->RSA(*((XrdCryptoRSA *)(cent->buf2.buf)));
3628  hs->Cbck = new XrdSutBucket(*((XrdSutBucket *)(cent->buf3.buf)));
3629  ceref.UnLock();
3630 
3631  // Create a handshake cache
3632  if (!(hs->Cref = new XrdSutPFEntry(hs->ID.c_str()))) {
3633  cmsg = "cannot create cache entry";
3634  return -1;
3635  }
3636  //
3637  // Deserialize main buffer
3638  if (!((*bm) = new XrdSutBuffer(bckm->buffer,bckm->size))) {
3639  cmsg = "error deserializing main buffer";
3640  return -1;
3641  }
3642 
3643  // Deactivate what not need any longer
3645 
3646  //
3647  // Get options, if any
3648  if (br->UnmarshalBucket(kXRS_clnt_opts, hs->Options) == 0)
3650 
3651  // We are done
3652  return 0;
3653 }
3654 
3655 //_________________________________________________________________________
3656 int XrdSecProtocolgsi::ServerDoCert(XrdSutBuffer *br, XrdSutBuffer **bm,
3657  String &cmsg)
3658 {
3659  // Server side: process a kXGC_cert message.
3660  // Return 0 on success, -1 on error. If the case, a message is returned
3661  // in cmsg.
3662  EPNAME("ServerDoCert");
3663 
3664  XrdSutBucket *bck = 0;
3665  XrdSutBucket *bckm = 0;
3666 
3667  //
3668  // Extract the main buffer
3669  if (!(bckm = br->GetBucket(kXRS_main))) {
3670  cmsg = "main buffer missing";
3671  return -1;
3672  }
3673  //
3674  // Extract cipher algorithm chosen by the client
3675  int lenIV = 0;
3676  String cip = "";
3677  if ((bck = br->GetBucket(kXRS_cipher_alg))) {
3678  bck->ToString(cip);
3679  // Extract IV length, if any
3680  int piv = cip.find('#');
3681  if (piv >= 0) {
3682  String siv(cip, piv+1);
3683  if (siv.isdigit()) lenIV = siv.atoi();
3684  cip.erase(piv);
3685  }
3686  // Parse the list
3687  if (DefCipher.find(cip) == -1) {
3688  cmsg = "unsupported cipher chosen by the client";
3689  hs->Chain = 0;
3690  return -1;
3691  }
3692  // Deactivate the bucket
3694  } else {
3695  NOTIFY("WARNING: client choice for cipher missing"
3696  " - using default");
3697  }
3698 
3699  XrdOucString cpub;
3700  if (hs->RemVers >= XrdSecgsiVersDHsigned) {
3701  // Supports setting a unique IV in enc/dec operations
3702  useIV = true;
3703  // First get the client public key
3704  if (!(bck = br->GetBucket(kXRS_puk))) {
3705  cmsg = "bucket with client public key missing";
3706  return -1;
3707  }
3708  bck->ToString(cpub);
3709  sessionKver = sessionCF->RSA(cpub.c_str(), cpub.length());
3710  if (!sessionKver || !sessionKver->IsValid()) {
3711  cmsg = "bucket with client public key contains an invalid key";
3712  return -1;
3713  }
3714 
3715  // Get the client DH parameters
3716  if (!(bck = br->GetBucket(kXRS_cipher))) {
3717  cmsg = "bucket with client DH parameters missing";
3718  return -1;
3719  }
3720 
3721  // Decrypt client DH public parameters with client key
3722  if (sessionKver->DecryptPublic(*bck) <= 0) {
3723  cmsg = "decrypting client DH public parameters";
3724  return -1;
3725  }
3726 
3727  } else {
3728 
3729  // Get the client DH parameters
3730  if (!(bck = br->GetBucket(kXRS_puk))) {
3731  cmsg = "bucket with client DH parameters missing";
3732  return -1;
3733  }
3734 
3735  // If the client doesn't provide signed DH parameter, disable proxy delegation
3736  if ((PxyReqOpts & kOptsSrvReq) ||
3738  PRINT("no signed DH parameters from client:" << Entity.tident <<
3739  " : will not delegate x509 proxy to it");
3740  if ((PxyReqOpts & kOptsSrvReq)) PxyReqOpts &= ~kOptsSrvReq;
3741  if (hs->Options & (kOptsDlgPxy | kOptsSigReq | kOptsFwdPxy))
3743  }
3744 
3745  // Get the session cipher
3746  if (bck) {
3747  //
3748  // Cleanup
3749  SafeDelete(sessionKey);
3750  //
3751  // Prepare cipher agreement: make sure we have the reference cipher
3752  if (!hs->Rcip) {
3753  cmsg = "reference cipher missing";
3754  hs->Chain = 0;
3755  return -1;
3756  }
3757  sessionKey = hs->Rcip;
3758  //
3759  // Instantiate the session cipher
3760  if (!(sessionKey->Finalize(hs->HasPad,bck->buffer,bck->size,cip.c_str()))) {
3761  cmsg = "cannot finalize session cipher";
3762  hs->Chain = 0;
3763  return -1;
3764  }
3765 
3766  // Set IV length, if any
3767  if (lenIV > 0) sessionKey->SetIV(lenIV, (const char *)0);
3768 
3769  } else {
3770  cmsg = "bucket with DH parameters not found or invalid: cannot finalize session cipher";
3771  return -1;
3772  }
3773  //
3774  // We need it only once
3776  br->Deactivate(kXRS_puk);
3777 
3778  //
3779  // Decrypt the main buffer with the session cipher, if available
3780  if (sessionKey) {
3781  if (!(sessionKey->Decrypt(*bckm, useIV))) {
3782  cmsg = "error decrypting main buffer with session cipher";
3783  hs->Chain = 0;
3784  return -1;
3785  }
3786  }
3787  //
3788  // Deserialize main buffer
3789  if (!((*bm) = new XrdSutBuffer(bckm->buffer,bckm->size))) {
3790  cmsg = "error deserializing main buffer";
3791  hs->Chain = 0;
3792  return -1;
3793  }
3794  //
3795  // Get version run by client, if there
3796  if (hs->RemVers == -1) {
3797  if ((*bm)->UnmarshalBucket(kXRS_version,hs->RemVers) != 0) {
3798  hs->RemVers = Version;
3799  cmsg = "client version information not found in options:"
3800  " assume same as local";
3801  } else {
3802  (*bm)->Deactivate(kXRS_version);
3803  }
3804  }
3805 
3806  //
3807  // Get cache entry
3808  if (!hs->Cref) {
3809  cmsg = "session cache has gone";
3810  hs->Chain = 0;
3811  return -1;
3812  }
3813  //
3814  // make sure cache is not too old
3815  int reftime = hs->TimeStamp - TimeSkew;
3816  if (hs->Cref->mtime < reftime) {
3817  cmsg = "cache entry expired";
3818  SafeDelete(hs->Cref);
3819  hs->Chain = 0;
3820  return -1;
3821  }
3822 
3823  //
3824  // Extract the client certificate
3825  if (!(bck = (*bm)->GetBucket(kXRS_x509))) {
3826  cmsg = "client certificate missing";
3827  SafeDelete(hs->Cref);
3828  hs->Chain = 0;
3829  return -1;
3830  }
3831 
3832  //
3833  // Finalize chain: get a copy of it (we do not touch the reference)
3834  hs->Chain = new X509Chain(hs->Chain);
3835  if (!(hs->Chain)) {
3836  cmsg = "cannot duplicate reference chain";
3837  return -1;
3838  }
3839  // The new chain must be deleted at destruction
3840  hs->Options |= kOptsDelChn;
3841 
3842  // Get hook to parsing function
3843  XrdCryptoX509ParseBucket_t ParseBucket = sessionCF->X509ParseBucket();
3844  if (!ParseBucket) {
3845  cmsg = "cannot attach to ParseBucket function!";
3846  return -1;
3847  }
3848  // Parse bucket
3849  int ncimin = (hs->Options & kOptsCreatePxy) ? 2 : 1;
3850  int nci = (*ParseBucket)(bck, hs->Chain);
3851  if (nci < ncimin) {
3852  cmsg = "wrong number of certificates in received bucket (received: ";
3853  cmsg += nci;
3854  cmsg += ", expected: >= ";
3855  cmsg += ncimin;
3856  cmsg += ")";
3857  return -1;
3858  }
3859  //
3860  // Verify the chain
3861  x509ChainVerifyOpt_t vopt = {0,static_cast<int>(hs->TimeStamp),-1,hs->Crl};
3863  if (!(hs->Chain->Verify(ecode, &vopt))) {
3864  cmsg = "certificate chain verification failed: ";
3865  cmsg += hs->Chain->LastError();
3866  return -1;
3867  }
3868 
3869  //
3870  // Extract the client public key from the certificate
3871  XrdCryptoRSA *ckey = sessionCF->RSA(*(hs->Chain->End()->PKI()));
3872  if (!ckey || !ckey->IsValid()) {
3873  cmsg = "client certificate contains an invalid key";
3874  return -1;
3875  }
3876  if (hs->RemVers >= XrdSecgsiVersDHsigned) {
3877  // For new clients, make sure it is the same we got from the bucket
3878  XrdOucString cpubcert;
3879  if ((ckey->ExportPublic(cpubcert) < 0)) {
3880  cmsg = "exporting client public key";
3881  return -1;
3882  }
3883  if (cpubcert != cpub) {
3884  cmsg = "client public key does not match the one from the bucket!";
3885  return -1;
3886  }
3887  delete ckey;
3888  } else {
3889  // For old clients, set the client public key from the certificate
3890  sessionKver = ckey;
3891  }
3892 
3893  // Deactivate certificate buffer
3894  (*bm)->Deactivate(kXRS_x509);
3895 
3896  //
3897  // Check if there will be delegated proxies; these can be through
3898  // normal request+signature, or just forwarded by the client.
3899  // In both cases we need to save the proxy chain. If we need a
3900  // request, we have to prepare it and send it back to the client.
3901  // Get hook to parsing function
3902  XrdCryptoX509CreateProxyReq_t X509CreateProxyReq = sessionCF->X509CreateProxyReq();
3903  if (!X509CreateProxyReq) {
3904  cmsg = "cannot attach to X509CreateProxyReq function!";
3905  return -1;
3906  }
3907  bool needReq =
3908  ((PxyReqOpts & kOptsSrvReq) && (hs->Options & kOptsSigReq)) ||
3909  (hs->Options & kOptsDlgPxy);
3910  if (needReq || (hs->Options & kOptsFwdPxy)) {
3911  // Create a new proxy chain
3912  hs->PxyChain = new X509Chain();
3913  // The new chain must be deleted if still in the handshake info
3914  // when the info is destroyed
3915  hs->Options |= kOptsDelPxy;
3916  // Add the current proxy
3917  if ((*ParseBucket)(bck, hs->PxyChain) > 1) {
3918  // Reorder it
3919  hs->PxyChain->Reorder();
3920  if (needReq) {
3921  // Create the request
3922  XrdCryptoX509Req *rPXp = (XrdCryptoX509Req *) &(hs->RemVers);
3923  XrdCryptoRSA *krPXp = 0;
3924  if ((*X509CreateProxyReq)(hs->PxyChain->End(), &rPXp, &krPXp) == 0) {
3925  // Save key in the cache
3926  hs->Cref->buf4.len = krPXp->GetPrilen() + 1;
3927  hs->Cref->buf4.buf = new char[hs->Cref->buf4.len];
3928  if (krPXp->ExportPrivate(hs->Cref->buf4.buf, hs->Cref->buf4.len) != 0) {
3929  delete krPXp;
3930  delete rPXp;
3931  if (hs->PxyChain) hs->PxyChain->Cleanup();
3932  SafeDelete(hs->PxyChain);
3933  cmsg = "cannot export private key of the proxy request!";
3934  return -1;
3935  }
3936  // Prepare export bucket for request
3937  XrdSutBucket *bckr = rPXp->Export();
3938  // Add it to the main list
3939  if ((*bm)->AddBucket(bckr) != 0) {
3940  if (hs->PxyChain) hs->PxyChain->Cleanup();
3941  SafeDelete(hs->PxyChain);
3942  NOTIFY("WARNING: proxy req: problem adding bucket to main buffer");
3943  }
3944  delete krPXp;
3945  delete rPXp;
3946  } else {
3947  if (hs->PxyChain) hs->PxyChain->Cleanup();
3948  SafeDelete(hs->PxyChain);
3949  NOTIFY("WARNING: proxy req: problem creating request");
3950  }
3951  }
3952  } else {
3953  if (hs->PxyChain) hs->PxyChain->Cleanup();
3954  SafeDelete(hs->PxyChain);
3955  NOTIFY("WARNING: proxy req: wrong number of certificates");
3956  }
3957  }
3958 
3959  //
3960  // Extract the MD algorithm chosen by the client
3961  String md = "";
3962  if ((bck = br->GetBucket(kXRS_md_alg))) {
3963  String mdlist;
3964  bck->ToString(md);
3965  // Parse the list
3966  if (DefMD.find(md) == -1) {
3967  cmsg = "unsupported MD chosen by the client";
3968  return -1;
3969  }
3970  // Deactivate
3971  br->Deactivate(kXRS_md_alg);
3972  } else {
3973  NOTIFY("WARNING: client choice for digests missing"
3974  " - using default");
3975  md = "md5";
3976  }
3977  if (!(sessionMD = sessionCF->MsgDigest(md.c_str()))) {
3978  cmsg = "could not instantiate digest object";
3979  return -1;
3980  }
3981 
3982  // We are done
3983  return 0;
3984 }
3985 
3986 //_________________________________________________________________________
3987 int XrdSecProtocolgsi::ServerDoSigpxy(XrdSutBuffer *br, XrdSutBuffer **bm,
3988  String &cmsg)
3989 {
3990  // Server side: process a kXGC_sigpxy message.
3991  // Return 0 on success, -1 on error. If the case, a message is returned
3992  // in cmsg.
3993  EPNAME("ServerDoSigpxy");
3994 
3995  XrdSutBucket *bck = 0;
3996  XrdSutBucket *bckm = 0;
3997 
3998  //
3999  // Extract the main buffer
4000  if (!(bckm = br->GetBucket(kXRS_main))) {
4001  cmsg = "main buffer missing";
4002  return 0;
4003  }
4004  //
4005  // Decrypt the main buffer with the session cipher, if available
4006  if (sessionKey) {
4007  if (!(sessionKey->Decrypt(*bckm, useIV))) {
4008  cmsg = "error decrypting main buffer with session cipher";
4009  return 0;
4010  }
4011  }
4012  //
4013  // Deserialize main buffer
4014  if (!((*bm) = new XrdSutBuffer(bckm->buffer,bckm->size))) {
4015  cmsg = "error deserializing main buffer";
4016  return 0;
4017  }
4018 
4019  // Get the bucket
4020  if (!(bck = (*bm)->GetBucket(kXRS_x509))) {
4021  cmsg = "buffer with requested info missing";
4022  // Is there a message from the client?
4023  if ((bck = (*bm)->GetBucket(kXRS_message))) {
4024  // Yes: decode it and print it
4025  String m;
4026  bck->ToString(m);
4027  DEBUG("msg from client: "<<m);
4028  // Add it to the main message
4029  cmsg += " :"; cmsg += m;
4030  }
4031  return 0;
4032  }
4033 
4034  // Make sure we still have the chain
4035  X509Chain *pxyc = hs->PxyChain;
4036  if (!pxyc) {
4037  cmsg = "the proxy chain is gone";
4038  return 0;
4039  }
4040 
4041  // Action depend on the type of message
4042  if ((hs->Options & kOptsFwdPxy)) {
4043  // The bucket contains a private key to be added to the proxy
4044  // public key
4045  XrdCryptoRSA *kpx = pxyc->End()->PKI();
4046  if (kpx->ImportPrivate(bck->buffer, bck->size) != 0) {
4047  cmsg = "problems importing private key";
4048  return 0;
4049  }
4050  } else {
4051  // The bucket contains our request signed by the client
4052  // The full key is in the cache
4053  if (!hs->Cref) {
4054  cmsg = "session cache has gone";
4055  return 0;
4056  }
4057  // Get the signed certificate
4058  XrdCryptoX509 *npx = sessionCF->X509(bck);
4059  if (!npx) {
4060  cmsg = "could not resolve signed request";
4061  return 0;
4062  }
4063  // Set full PKI
4064  XrdCryptoRSA *const knpx = npx->PKI();
4065  if (!knpx || knpx->ImportPrivate(hs->Cref->buf4.buf, hs->Cref->buf4.len) != 0) {
4066  delete npx;
4067  cmsg = "could not import private key into signed request";
4068  return 0;
4069  }
4070  // Add the new proxy ecert to the chain
4071  pxyc->PushBack(npx);
4072  }
4073  // Save the chain in the instance
4074  proxyChain = pxyc;
4075  hs->PxyChain = 0;
4076  // Notify
4077  if (QTRACE(Authen)) { proxyChain->Dump(); }
4078 
4079  // Check if the proxy chain is to become the actual credentials
4080  //
4081  if ((PxyReqOpts & kOptsPxCred)) {
4083  (sessionCF) ? sessionCF->X509ExportChain() : 0;
4084  if (!c2mem) {
4085  cmsg = "chain exporter not found; proxy chain not exported";
4086  return 0;
4087  }
4088  XrdOucString spxy;
4089  XrdSutBucket *bpxy = (*c2mem)(proxyChain, true);
4090  bpxy->ToString(spxy);
4091  if (Entity.credslen > 0) SafeFree(Entity.creds);
4092  Entity.creds = strdup(spxy.c_str());
4093  Entity.credslen = spxy.length();
4094  DEBUG("proxy chain exported in Entity.creds (" << Entity.credslen << " bytes)");
4095  DEBUG("\n\n" << spxy.c_str() << "\n\n");
4096  delete bpxy;
4097  return 0;
4098  }
4099 
4100  //
4101  // Extract user login name, if any
4102  String user;
4103  if ((bck = (*bm)->GetBucket(kXRS_user))) {
4104  bck->ToString(user);
4105  (*bm)->Deactivate(kXRS_user);
4106  }
4107  if (user.length() <= 0) user = Entity.name;
4108 
4109  // Dump to file if required
4110  if ((PxyReqOpts & kOptsPxFile)) {
4111  if (user.length() > 0) {
4112  String pxfile = UsrProxy, name;
4113  struct passwd *pw = getpwnam(user.c_str());
4114  if (pw) {
4115  name = pw->pw_name;
4116  } else {
4117  // Get Hash of the subject
4118  XrdCryptoX509 *c = proxyChain->SearchBySubject(proxyChain->EECname());
4119  if (c) {
4120  name = c->SubjectHash();
4121  } else {
4122  cmsg = "proxy chain not dumped to file: could not find subject hash";
4123  return 0;
4124  }
4125  }
4126  if (XrdSutResolve(pxfile, Entity.host,
4127  Entity.vorg, Entity.grps, name.c_str()) != 0) {
4128  PRINT("Problems resolving templates in "<<pxfile);
4129  return 0;
4130  }
4131  // Replace <uid> placeholder
4132  if (pw && pxfile.find("<uid>") != STR_NPOS) {
4133  String suid; suid += (int) pw->pw_uid;
4134  pxfile.replace("<uid>", suid.c_str());
4135  }
4136 
4137  // Get the function
4138  XrdCryptoX509ChainToFile_t ctofile = sessionCF->X509ChainToFile();
4139  if ((*ctofile)(proxyChain,pxfile.c_str()) != 0) {
4140  cmsg = "problems dumping proxy chain to file ";
4141  cmsg += pxfile;
4142  return 0;
4143  }
4144  PRINT("proxy chain dumped to "<< pxfile);
4145  } else {
4146  cmsg = "proxy chain not dumped to file: entity name undefined";
4147  return 0;
4148  }
4149  }
4150 
4151  // We are done
4152  return 0;
4153 }
4154 
4155 //__________________________________________________________________
4156 void XrdSecProtocolgsi::ErrF(XrdOucErrInfo *einfo, kXR_int32 ecode,
4157  const char *msg1, const char *msg2,
4158  const char *msg3)
4159 {
4160  // Filling the error structure
4161  EPNAME("ErrF");
4162 
4163  char *msgv[12];
4164  int k, i = 0, sz = strlen("Secgsi");
4165 
4166  //
4167  // Code message, if any
4168  int cm = (ecode >= kGSErrParseBuffer &&
4169  ecode <= kGSErrError) ? (ecode-kGSErrParseBuffer) : -1;
4170  const char *cmsg = (cm > -1) ? gGSErrStr[cm] : 0;
4171 
4172  //
4173  // Build error message array
4174  msgv[i++] = (char *)"Secgsi"; //0
4175  if (cmsg) {msgv[i++] = (char *)": "; //1
4176  msgv[i++] = (char *)cmsg; //2
4177  sz += strlen(msgv[i-1]) + 2;
4178  }
4179  if (msg1) {msgv[i++] = (char *)": "; //3
4180  msgv[i++] = (char *)msg1; //4
4181  sz += strlen(msgv[i-1]) + 2;
4182  }
4183  if (msg2) {msgv[i++] = (char *)": "; //5
4184  msgv[i++] = (char *)msg2; //6
4185  sz += strlen(msgv[i-1]) + 2;
4186  }
4187  if (msg3) {msgv[i++] = (char *)": "; //7
4188  msgv[i++] = (char *)msg3; //8
4189  sz += strlen(msgv[i-1]) + 2;
4190  }
4191 
4192  // save it (or print it)
4193  if (einfo) {
4194  einfo->setErrInfo(ecode, (const char **)msgv, i);
4195  }
4196  if (QTRACE(Debug)) {
4197  char *bout = new char[sz+10];
4198  if (bout) {
4199  bout[0] = 0;
4200  for (k = 0; k < i; k++)
4201  strcat(bout, msgv[k]);
4202  DEBUG(bout);
4203  } else {
4204  for (k = 0; k < i; k++)
4205  DEBUG(msgv[k]);
4206  }
4207  }
4208 }
4209 
4210 //__________________________________________________________________
4211 XrdSecCredentials *XrdSecProtocolgsi::ErrC(XrdOucErrInfo *einfo,
4212  XrdSutBuffer *b1,
4213  XrdSutBuffer *b2,
4214  XrdSutBuffer *b3,
4215  kXR_int32 ecode,
4216  const char *msg1,
4217  const char *msg2,
4218  const char *msg3)
4219 {
4220  // Error logging client method
4221 
4222  // Fill the error structure
4223  ErrF(einfo, ecode, msg1, msg2, msg3);
4224 
4225  // Release buffers
4226  REL3(b1,b2,b3);
4227 
4228  // We are done
4229  return (XrdSecCredentials *)0;
4230 }
4231 
4232 //__________________________________________________________________
4233 int XrdSecProtocolgsi::ErrS(String ID, XrdOucErrInfo *einfo,
4234  XrdSutBuffer *b1, XrdSutBuffer *b2,
4235  XrdSutBuffer *b3, kXR_int32 ecode,
4236  const char *msg1, const char *msg2,
4237  const char *msg3)
4238 {
4239  // Error logging server method
4240 
4241  // Fill the error structure
4242  ErrF(einfo, ecode, msg1, msg2, msg3);
4243 
4244  // Release buffers
4245  REL3(b1,b2,b3);
4246 
4247  // We are done
4248  return kgST_error;
4249 }
4250 
4251 //______________________________________________________________________________
4252 bool XrdSecProtocolgsi::CheckRtag(XrdSutBuffer *bm, String &emsg)
4253 {
4254  // Check random tag signature if it was sent with previous packet
4255  EPNAME("CheckRtag");
4256 
4257  // Make sure we got a buffer
4258  if (!bm) {
4259  emsg = "Buffer not defined";
4260  return 0;
4261  }
4262  //
4263  // If we sent out a random tag check its signature
4264  if (hs->Cref && hs->Cref->buf1.len > 0) {
4265  XrdSutBucket *brt = 0;
4266  if ((brt = bm->GetBucket(kXRS_signed_rtag))) {
4267  // Make sure we got the right key to decrypt
4268  if (!(sessionKver)) {
4269  emsg = "Session cipher undefined";
4270  return 0;
4271  }
4272  // Decrypt it with the counter part public key
4273  if (sessionKver->DecryptPublic(*brt) <= 0) {
4274  emsg = "error decrypting random tag with public key";
4275  return 0;
4276  }
4277  } else {
4278  emsg = "random tag missing - protocol error";
4279  return 0;
4280  }
4281  //
4282  // Random tag cross-check: content
4283  if (memcmp(brt->buffer,hs->Cref->buf1.buf,hs->Cref->buf1.len)) {
4284  emsg = "random tag content mismatch";
4285  SafeDelete(hs->Cref);
4286  // Remove: should not be checked a second time
4287  return 0;
4288  }
4289  //
4290  // Reset the cache entry but we will not use the info a second time
4291  memset(hs->Cref->buf1.buf,0,hs->Cref->buf1.len);
4292  hs->Cref->buf1.SetBuf();
4293  //
4294  // Flag successful check
4295  hs->RtagOK = 1;
4297  DEBUG("Random tag successfully checked");
4298  } else {
4299  DEBUG("Nothing to check");
4300  }
4301 
4302  // We are done
4303  return 1;
4304 }
4305 
4306 //______________________________________________________________________________
4307 XrdCryptoX509Crl *XrdSecProtocolgsi::LoadCRL(XrdCryptoX509 *xca, const char *subjhash,
4308  XrdCryptoFactory *CF, int dwld, int &errcrl)
4309 {
4310  // Scan crldir for a valid CRL certificate associated to CA whose
4311  // certificate is xca. If 'dwld' is true try to download the CRL from
4312  // the relevant URI, if any.
4313  // If the CRL is found and is valid according
4314  // to the chosen option, return its content in a X509Crl object.
4315  // Return 0 in any other case
4316  EPNAME("LoadCRL");
4317  XrdCryptoX509Crl *crl = 0;
4318  errcrl = 0;
4319 
4320  // make sure we got what we need
4321  if (!xca || !CF) {
4322  PRINT("Invalid inputs");
4323  errcrl = -1;
4324  return crl;
4325  }
4326 
4327  // Get the CA hash
4328  String cahash(subjhash);
4329  int hashalg = 0;
4330  if (strcmp(subjhash, xca->SubjectHash())) hashalg = 1;
4331  // Drop the extension (".0")
4332  String caroot(cahash, 0, cahash.find(".0")-1);
4333 
4334  // The dir
4335  String crlext = XrdSecProtocolgsi::DefCRLext;
4336 
4337  String crldir;
4338  int from = 0;
4339  while ((from = CRLdir.tokenize(crldir, from, ',')) != -1) {
4340  if (crldir.length() <= 0) continue;
4341  // Add the default CRL extension and the dir
4342  String crlfile = crldir + caroot;
4343  crlfile += crlext;
4344  DEBUG("target file: "<<crlfile);
4345  // Try to init a crl
4346  if ((crl = CF->X509Crl(crlfile.c_str()))) {
4347  if ((errcrl = VerifyCRL(crl, xca, crldir, CF, hashalg)) == 0) return crl;
4348  }
4349  SafeDelete(crl);
4350  }
4351 
4352  // If not required, we are done
4353  if (CRLCheck < 2 || (dwld == 0)) {
4354  // Done
4355  return crl;
4356  }
4357 
4358  // If in 'required' mode, we will also try to load the CRL from the
4359  // information found in the CA certificate or in the certificate directory.
4360  // To avoid this overload, the CRL information should be installed offline, e.g. with
4361  // utils/getCRLcert
4362 
4363  errcrl = 0;
4364  // Try to retrieve it from the URI in the CA certificate, if any
4365  if ((crl = CF->X509Crl(xca))) {
4366  if ((errcrl = VerifyCRL(crl, xca, crldir, CF, hashalg)) == 0) return crl;
4367  SafeDelete(crl);
4368  }
4369 
4370  // Finally try the ".crl_url" file
4371  from = 0;
4372  while ((from = CRLdir.tokenize(crldir, from, ',')) != -1) {
4373  if (crldir.length() <= 0) continue;
4374  SafeDelete(crl);
4375  String crlurl = crldir + caroot;
4376  crlurl += ".crl_url";
4377  DEBUG("target file: "<<crlurl);
4378  FILE *furl = fopen(crlurl.c_str(), "r");
4379  if (!furl) {
4380  PRINT("could not open file: "<<crlurl);
4381  continue;
4382  }
4383  char line[2048];
4384  while ((fgets(line, sizeof(line), furl))) {
4385  if (line[strlen(line) - 1] == '\n') line[strlen(line) - 1] = 0;
4386  if ((crl = CF->X509Crl(line, 1))) {
4387  if ((errcrl = VerifyCRL(crl, xca, crldir, CF, hashalg)) == 0) return crl;
4388  SafeDelete(crl);
4389  }
4390  }
4391  }
4392 
4393  // We need to parse the full dirs: make some cleanup first
4394  from = 0;
4395  while ((from = CRLdir.tokenize(crldir, from, ',')) != -1) {
4396  if (crldir.length() <= 0) continue;
4397  SafeDelete(crl);
4398  // Open directory
4399  DIR *dd = opendir(crldir.c_str());
4400  if (!dd) {
4401  PRINT("could not open directory: "<<crldir<<" (errno: "<<errno<<")");
4402  continue;
4403  }
4404  // Read the content
4405  struct dirent *dent = 0;
4406  while ((dent = readdir(dd))) {
4407  // Do not analyse the CA certificate
4408  if (!strcmp(cahash.c_str(),dent->d_name)) continue;
4409  // File name contain the root CA hash
4410  if (!strstr(dent->d_name,caroot.c_str())) continue;
4411  // candidate name
4412  String crlfile = crldir + dent->d_name;
4413  DEBUG("analysing entry "<<crlfile);
4414  // Try to init a crl
4415  if ((crl = CF->X509Crl(crlfile.c_str()))) {
4416  if ((errcrl = VerifyCRL(crl, xca, crldir, CF, hashalg)) == 0) break;
4417  SafeDelete(crl);
4418  }
4419  }
4420  // Close dir
4421  closedir(dd);
4422  // Are we done?
4423  if (crl) break;
4424  }
4425 
4426  // We are done
4427  return crl;
4428 }
4429 
4430 //______________________________________________________________________________
4431 int XrdSecProtocolgsi::VerifyCRL(XrdCryptoX509Crl *crl, XrdCryptoX509 *xca, String crldir,
4432  XrdCryptoFactory *CF, int hashalg)
4433 {
4434  EPNAME("VerifyCRL");
4435  int rc = 0;
4436  // Make sure they have the same issuer
4437  if (!strcmp(xca->SubjectHash(hashalg), crl->IssuerHash(hashalg))) {
4438  // Signing certificate file
4439  String casigfile = crldir + crl->IssuerHash(hashalg);
4440  DEBUG("CA signing certificate file = "<<casigfile);
4441  // Try to get signing certificate
4442  XrdCryptoX509 *xcasig = 0;
4443  if (!(xcasig = CF->X509(casigfile.c_str()))) {
4444  if (CRLCheck >= 2) {
4445  PRINT("CA certificate to verify the signature ("<<crl->IssuerHash(hashalg)<<
4446  ") could not be loaded - exit");
4447  } else {
4448  DEBUG("CA certificate to verify the signature could not be loaded - verification skipped");
4449  }
4450  rc = -3;
4451  } else {
4452  // Verify signature
4453  if (crl->Verify(xcasig)) {
4454  // Ok, we are done
4455  if (CRLCheck >= 3 && crl && crl->IsExpired()) {
4456  rc = -5;
4457  NOTIFY("CRL is expired (CRLCheck: "<<CRLCheck<<")");
4458  }
4459  } else {
4460  rc = -4;
4461  PRINT("CA signature or CRL verification failed!");
4462  }
4463  SafeDelete(xcasig);
4464  }
4465  } else {
4466  rc = -2;
4467  PRINT("Loaded CRL does not match CA (subject CA "<<xca->SubjectHash(hashalg)<<
4468  " does not match CRL issuer "<<crl->IssuerHash(hashalg)<<"! ");
4469  }
4470  return rc;
4471 }
4472 
4473 //______________________________________________________________________________
4474 String XrdSecProtocolgsi::GetCApath(const char *cahash)
4475 {
4476  // Look in the paths defined by CAdir for the certificate file related to
4477  // 'cahash', in the form <CAdir_entry>/<cahash>.0
4478 
4479  String path;
4480  String ent;
4481  int from = 0;
4482  while ((from = CAdir.tokenize(ent, from, ',')) != -1) {
4483  if (ent.length() > 0) {
4484  path = ent;
4485  if (!path.endswith('/'))
4486  path += "/";
4487  path += cahash;
4488  if (!path.endswith(".0"))
4489  path += ".0";
4490  if (!access(path.c_str(), R_OK))
4491  break;
4492  }
4493  path = "";
4494  }
4495 
4496  // Done
4497  return path;
4498 }
4499 //______________________________________________________________________________
4500 bool XrdSecProtocolgsi::VerifyCA(int opt, X509Chain *cca, XrdCryptoFactory *CF)
4501 {
4502  // Verify the CA in 'cca' according to 'opt':
4503  // opt = 2 full check
4504  // 1 only if self-signed
4505  // 0 no check
4506  EPNAME("VerifyCA");
4507 
4508  bool verified = 0;
4510  cca->SetStatusCA(st);
4511 
4512  // We nust have got a chain
4513  if (!cca) {
4514  PRINT("Invalid input ");
4515  return 0;
4516  }
4517 
4518  // Get the parse function
4520  if (!ParseFile) {
4521  PRINT("Cannot attach to the ParseFile function");
4522  return 0;
4523  }
4524 
4525  // Point to the certificate
4526  XrdCryptoX509 *xc = cca->Begin();
4527  if (!xc) {
4528  PRINT("Cannot attach to first certificate in chain");
4529  return 0;
4530  }
4531  // Make sure it is valid
4532  if (!(xc->IsValid())) {
4533  PRINT("CA certificate is expired ("<<xc->SubjectHash()<<", not_before: "<<xc->NotBefore()<<" secs UTC )");
4534  return 0;
4535  }
4536  // Is it self-signed ?
4537  bool self = (!strcmp(xc->IssuerHash(), xc->SubjectHash())) ? 1 : 0;
4538  if (!self) {
4539  String inam;
4540  if (opt == 2) {
4541  // We are requested to verify it
4542  bool notdone = 1;
4543  // We need to load the issuer(s) CA(s)
4544  XrdCryptoX509 *xd = xc;
4545  while (notdone) {
4546  X509Chain *ch = 0;
4547  int ncis = -1;
4548  for (int ha = 0; ha < 2; ha++) {
4549  inam = GetCApath(xd->IssuerHash(ha));
4550  if (inam.length() <= 0) continue;
4551  ch = new X509Chain();
4552  ncis = (*ParseFile)(inam.c_str(), ch, 0);
4553  if (ncis >= 1) break;
4554  SafeDelete(ch);
4555  }
4556  if (ncis < 1) break;
4557  XrdCryptoX509 *xi = ch->Begin();
4558  while (xi) {
4559  if (!strcmp(xd->IssuerHash(), xi->SubjectHash()))
4560  break;
4561  xi = ch->Next();
4562  }
4563  if (xi) {
4564  // Add the certificate to the requested CA chain
4565  ch->Remove(xi);
4566  cca->PutInFront(xi);
4567  SafeDelete(ch);
4568  // We may be over
4569  if (!strcmp(xi->IssuerHash(), xi->SubjectHash())) {
4570  notdone = 0;
4571  break;
4572  } else {
4573  // This becomes the daughter
4574  xd = xi;
4575  }
4576  } else {
4577  break;
4578  }
4579  }
4580  if (!notdone) {
4581  // Verify the chain
4583  x509ChainVerifyOpt_t vopt = {kOptsCheckSubCA, 0, -1, 0};
4584  if (!(verified = cca->Verify(e, &vopt)))
4585  PRINT("CA certificate not self-signed: verification failed for '"<<xc->SubjectHash()<<"': error: "<< cca->X509ChainError(e));
4586  } else {
4587  PRINT("CA certificate not self-signed: cannot verify integrity ("<<xc->SubjectHash()<<")");
4588  }
4589  } else {
4590  // Fill CA information
4591  cca->CheckCA(0);
4592  // Set OK in any case
4593  verified = 1;
4594  // Notify if some sort of check was required
4595  if (opt == 1) {
4596  NOTIFY("Warning: CA certificate not self-signed and"
4597  " integrity not checked: assuming OK ("<<xc->SubjectHash()<<")");
4598  }
4599  }
4600  } else {
4601  if (CACheck > caNoVerify) {
4602  // Check self-signature and fail if needed
4603  bool checkselfsigned = (CACheck > caVerifyss) ? true : false;
4604  if (!(verified = cca->CheckCA(checkselfsigned)))
4605  PRINT("CA certificate self-signed: integrity check failed ("<<xc->SubjectHash()<<")");
4606  } else {
4607  // Set OK in any case
4608  verified = 1;
4609  // Notify if some sort of check was required
4610  NOTIFY("Warning: CA certificate self-signed but"
4611  " integrity not checked: assuming OK ("<<xc->SubjectHash()<<")");
4612  }
4613  }
4614 
4615  // Set the status in the chain
4616  st = (verified) ? XrdCryptoX509Chain::kValid : st;
4617  cca->SetStatusCA(st);
4618 
4619  // Done
4620  return verified;
4621 }
4622 
4623 //_____________________________________________________________________________
4624 static bool GetCACheck(XrdSutCacheEntry *e, void *a) {
4625 
4626  EPNAME("GetCACheck");
4627 
4628  int crl_check = (*((XrdSutCacheArg_t *)a)).arg1;
4629  int crl_refresh = (*((XrdSutCacheArg_t *)a)).arg2;
4630  time_t ts_ref = (time_t)(*((XrdSutCacheArg_t *)a)).arg3;
4631 
4632  if (!e) return false;
4633 
4634  X509Chain *chain = 0;
4635  // If we had already something, check it, as we may be done
4636  bool goodca = 0;
4637  if ((chain = (X509Chain *)(e->buf1.buf))) {
4638  // Check the validity of the certificates in the chain; if a certificate became invalid,
4639  // we need to reload a valid one for the same CA.
4640  if (chain->CheckValidity() == 0) {
4641  goodca = 1;
4642  } else {
4643  PRINT("CA entry for '"<<e->name<<"' needs refreshing: clean the related entry cache first");
4644  return false;
4645  }
4646  }
4647  if (goodca) {
4648  XrdCryptoX509Crl *crl = (XrdCryptoX509Crl *)(e->buf2.buf);
4649  bool goodcrl = 1;
4650  if ((crl_check == 2 && !crl) || (crl_check == 3 && crl->IsExpired())) goodcrl = 0;
4651  if (crl_refresh > 0 && ((ts_ref - e->mtime) > crl_refresh)) goodcrl = 0;
4652  if (goodcrl) {
4653  return true;
4654  } else if (crl) {
4655  PRINT("CRL entry for '"<<e->name<<"' needs refreshing: clean the related entry cache first ("<<e<<")");
4656  }
4657  }
4658  return false;
4659 }
4660 
4661 //______________________________________________________________________________
4662 int XrdSecProtocolgsi::GetCA(const char *cahash,
4663  XrdCryptoFactory *cf, gsiHSVars *hs)
4664 {
4665  // Gets entry for CA with hash cahash for crypt factory cf.
4666  // If not found in cache, try loading from <CAdir>/<cahash>.0 .
4667  // If 'hs' is defined, store pointers to chain and crl into 'hs'.
4668  // Return 0 if ok, -1 if not available, -2 if CRL not ok
4669  EPNAME("GetCA");
4670  XrdSutCERef ceref;
4671  int rc = 0;
4672 
4673  // We nust have got a CA hash
4674  if (!cahash || !cf) {
4675  PRINT("Invalid input ");
4676  return -1;
4677  }
4678 
4679  // Timestamp
4680  time_t timestamp = (hs) ? hs->TimeStamp : time(0);
4681 
4682  // The tag
4683  String tag(cahash,20);
4684  tag += ':';
4685  tag += cf->ID();
4686  DEBUG("Querying cache for tag: "<<tag<<" (timestamp:"<<timestamp<<
4687  ", refresh fq:"<< CRLRefresh <<")");
4688 
4689  bool rdlock = false;
4690  XrdSutCacheArg_t arg = {CRLCheck, CRLRefresh, timestamp, -1};
4691  XrdSutCacheEntry *cent = cacheCA.Get(tag.c_str(), rdlock, GetCACheck, (void *) &arg);
4692  if (!cent) {
4693  PRINT("unable to get a valid entry from cache for " << tag);
4694  return -1;
4695  }
4696  ceref.Set(&(cent->rwmtx));
4697 
4698  // Point to the content
4699  X509Chain *chain = (X509Chain *)(cent->buf1.buf);
4700  XrdCryptoX509Crl *crl = (XrdCryptoX509Crl *)(cent->buf2.buf);
4701 
4702  // If invalid we fail
4703  if (cent->status == kCE_inactive) {
4704  // Cleanup and remove existing invalid entries
4705  if (chain) stackCA.Del(chain);
4706  if (crl) stackCRL->Del(crl);
4707  PRINT("unable to get a valid entry from cache for " << tag);
4708  return -1;
4709  }
4710 
4711  // Check if we are done
4712  if (rdlock) {
4713  // Save chain
4714  if (hs) hs->Chain = chain;
4715  stackCA.Add(chain);
4716  // Save crl
4717  if (crl) {
4718  if (hs) hs->Crl = crl;
4719  // Add to the stack for proper cleaning of invalidated CRLs
4720  stackCRL->Add(crl);
4721  }
4722  return 0;
4723  }
4724 
4725  // Cleanup and remove existing invalid entries
4726  if (chain) stackCA.Del(chain);
4727  if (crl) stackCRL->Del(crl);
4728 
4729  chain = 0;
4730  crl = 0;
4731  cent->buf1.buf = 0;
4732  cent->buf2.buf = 0;
4733 
4734  // If not, prepare the file name
4735  String fnam = GetCApath(cahash);
4736  DEBUG("trying to load CA certificate from "<<fnam);
4737 
4738  // Create chain ?
4739  bool createchain = (hs && hs->Chain) ? 0 : 1;
4740  chain = (createchain) ? new X509Chain() : hs->Chain;
4741  if (!chain) {
4742  PRINT("could not attach-to or create new GSI chain");
4743  rc = -1;
4744  }
4745 
4746  // Get the parse function
4748  if (rc == 0 && ParseFile) {
4749  int nci = (createchain) ? (*ParseFile)(fnam.c_str(), chain, 0) : 1;
4750  bool ok = 0, verified = 0;
4751  if (nci == 1) {
4752  // Verify the CA
4753  verified = VerifyCA(CACheck, chain, cf);
4754  XrdCryptoX509Crl *crl = 0;
4755  if (verified) {
4756  // Get CRL, if required
4757  ok = 1;
4758  if (CRLCheck > 0) {
4759  int errcrl = 0;
4760  if ((crl = LoadCRL(chain->EffCA(), cahash, cf, CRLDownload, errcrl))) {
4761  // Good CA
4762  DEBUG("CRL successfully loaded");
4763  } else {
4764  String em = "missing or expired: ignoring";
4765  if ((CRLCheck == 1 && errcrl != 0 && errcrl != -5) || (CRLCheck >= 2 && errcrl != 0)) {
4766  ok = 0;
4767  em = "invalid: failing";
4768  } else if (CRLCheck >= 2) {
4769  ok = 0;
4770  em = "missing or expired: failing";
4771  }
4772  NOTIFY("CRL is "<<em<<" (CRLCheck: "<<CRLCheck<<")");
4773  }
4774  }
4775  }
4776  //
4777  if (ok) {
4778  // Add to the cache
4779  cent->buf1.buf = (char *)(chain);
4780  cent->buf1.len = 0; // Just a flag
4781  stackCA.Add(chain);
4782  if (crl) {
4783  cent->buf2.buf = (char *)(crl);
4784  cent->buf2.len = 0; // Just a flag
4785  stackCRL->Add(crl);
4786  }
4787  cent->mtime = timestamp;
4788  cent->status = kCE_ok;
4789  cent->cnt = 0;
4790  // Fill output, if required
4791  if (hs) {
4792  hs->Chain = chain;
4793  hs->Crl = crl;
4794  if (strcmp(cahash, chain->Begin()->SubjectHash())) hs->HashAlg = 1;
4795  }
4796  } else {
4797  SafeDelete(crl);
4798  SafeDelete(chain);
4799  rc = -2;
4800  }
4801  } else {
4802  SafeDelete(chain);
4803  NOTIFY("certificate not found or invalid (nci: "<<nci<<", CA: "<<
4804  (int)(verified)<<")");
4805  rc = -1;
4806  }
4807  }
4808 
4809  // We are done: release the lock
4810  ceref.UnLock();
4811 
4812  // We are done
4813  return (rc != 0) ? rc : 0;
4814 }
4815 
4816 //______________________________________________________________________________
4817 int XrdSecProtocolgsi::InitProxy(ProxyIn_t *pi, XrdCryptoFactory *cf, X509Chain *ch, XrdCryptoRSA **kp)
4818 {
4819  // Invoke 'grid-proxy-init' via the shell to create a valid the proxy file
4820  // If the variable GLOBUS_LOCATION is defined it prepares the external shell
4821  // by sourcing $GLOBUS_LOCATION/etc/globus-user-env.sh .
4822  // Return 0 in cse of success, != 0 in any other case .
4823  EPNAME("InitProxy");
4824  int rc = 0;
4825 
4826  // We must be able to get an answer
4827  if (isatty(0) == 0 || isatty(1) == 0) {
4828  NOTIFY("Not a tty: cannot prompt for proxies - do nothing ");
4829  return -1;
4830  }
4831 
4832  //
4833  // Use internal function for proxy initialization
4834  //
4835  // Make sure we got a chain and a key to fill
4836  if (!ch || !kp) {
4837  PRINT("chain or key container undefined");
4838  return -1;
4839  }
4840  // Check existence and permission of the key file
4841  struct stat st;
4842  if (stat(pi->key, &st) != 0) {
4843  DEBUG("cannot access private key file: "<<pi->key);
4844  return 1;
4845  }
4846  if (!S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) ||
4847  (st.st_mode & (S_IWGRP | S_IWOTH)) != 0 ||
4848  (st.st_mode & (S_IRGRP | S_IROTH)) != 0) {
4849  DEBUG("wrong permissions for file: "<<pi->key<< " (should be 0600)");
4850  return 1;
4851  }
4852  //
4853  // Validity
4854  int valid = (pi->valid) ? XrdSutParseTime(pi->valid, 1) : -1;
4855  //
4856  // Options
4857  XrdProxyOpt_t pxopt = {pi->bits, // bits in key
4858  valid, // duration validity in secs
4859  pi->deplen}; // signature path depth
4860  //
4861  // Init now
4862  XrdCryptoX509CreateProxy_t X509CreateProxy = cf->X509CreateProxy();
4863  if (!X509CreateProxy) {
4864  PRINT("cannot attach to X509CreateProxy function!");
4865  return 1;
4866  }
4867  rc = (*X509CreateProxy)(pi->cert, pi->key, &pxopt, ch, kp, pi->out);
4868 
4869  // We are done
4870  return rc;
4871 }
4872 
4873 //__________________________________________________________________________
4874 int XrdSecProtocolgsi::ParseCAlist(String calist)
4875 {
4876  // Parse received ca list, find the first available CA in the list
4877  // and return a chain initialized with such a CA.
4878  // If nothing found return 0.
4879  EPNAME("ParseCAlist");
4880 
4881  // Check inputs
4882  if (calist.length() <= 0) {
4883  PRINT("nothing to parse");
4884  return -1;
4885  }
4886  DEBUG("parsing list: "<<calist);
4887 
4888  // Load module and define relevant pointers
4889  hs->Chain = 0;
4890  String cahash = "";
4891  // Parse list
4892  if (calist.length()) {
4893  int from = 0;
4894  while ((from = calist.tokenize(cahash, from, '|')) != -1) {
4895  // Check this hash
4896  if (cahash.length()) {
4897  // Make sure the extension ".0" if there, as external implementations may not
4898  // include it
4899  if (!cahash.endswith(".0")) cahash += ".0";
4900  // Get the CA chain
4901  if (GetCA(cahash.c_str(), sessionCF, hs) == 0)
4902  return 0;
4903  }
4904  }
4905  }
4906 
4907  // We did not find it
4908  return -1;
4909 }
4910 
4911 //__________________________________________________________________________
4912 int XrdSecProtocolgsi::ParseCrypto(String clist)
4913 {
4914  // Parse crypto list clist, extracting the first available module
4915  // and getting a related local cipher and a related reference
4916  // cipher to be used to agree the session cipher; the local lists
4917  // crypto info is updated, if needed
4918  // The results are used to fill the handshake part of the protocol
4919  // instance.
4920  EPNAME("ParseCrypto");
4921 
4922  // Check inputs
4923  if (clist.length() <= 0) {
4924  NOTIFY("empty list: nothing to parse");
4925  return -1;
4926  }
4927  DEBUG("parsing list: "<<clist);
4928 
4929  // Load module and define relevant pointers
4930  hs->CryptoMod = "";
4931 
4932  // Parse list
4933  int from = 0;
4934  while ((from = clist.tokenize(hs->CryptoMod, from, '|')) != -1) {
4935  // Check this module
4936  if (hs->CryptoMod.length() > 0) {
4937  DEBUG("found module: "<<hs->CryptoMod);
4938  // Padding support?
4939  bool otherHasPad = true;
4940  if (hs->RemVers >= XrdSecgsiVersDHsigned) {
4941  if (hs->CryptoMod.endswith(gNoPadTag)) {
4942  otherHasPad = false;
4943  hs->CryptoMod.replace(gNoPadTag, "");
4944  }
4945  } else {
4946  otherHasPad = false;
4947  }
4948  // Load the crypto factory
4949  if ((sessionCF =
4951  sessionCF->SetTrace(GSITrace->What);
4952  if (QTRACE(Debug)) sessionCF->Notify();
4953  if (otherHasPad && sessionCF->HasPaddingSupport()) hs->HasPad = 1;
4954  int fid = sessionCF->ID();
4955  int i = 0;
4956  // Retrieve the index in local table
4957  while (i < ncrypt) {
4958  if (cryptID[i] == fid) break;
4959  i++;
4960  }
4961  if (i >= ncrypt) {
4962  if (ncrypt == XrdCryptoMax) {
4963  DEBUG("max number of crypto slots reached - do nothing");
4964  return 0;
4965  } else {
4966  // Add new entry
4967  cryptF[i] = sessionCF;
4968  cryptID[i] = fid;
4969  ncrypt++;
4970  }
4971  }
4972  // On servers the ref cipher should be defined at this point
4973  hs->Rcip = sessionCF->Cipher(hs->HasPad, 0,0,0);
4974  // we are done
4975  return 0;
4976  }
4977  }
4978  }
4979 
4980  // Nothing found
4981  return -1;
4982 }
4983 
4984 //_____________________________________________________________________________
4985 static bool QueryProxyCheck(XrdSutCacheEntry *e, void *a) {
4986 
4987  time_t ts_ref = (time_t)(*((XrdSutCacheArg_t *)a)).arg1;
4988 
4989  if (e && e->buf1.buf) {
4990  X509Chain *chain = (X509Chain *)(e->buf1.buf);
4991  if (chain->CheckValidity(1, ts_ref) == 0) return true;
4992  }
4993  return false;
4994 }
4995 
4996 
4997 //__________________________________________________________________________
4998 int XrdSecProtocolgsi::QueryProxy(bool checkcache, XrdSutCache *cache,
4999  const char *tag, XrdCryptoFactory *cf,
5000  time_t timestamp, ProxyIn_t *pi, ProxyOut_t *po)
5001 {
5002  // Query users proxies, initializing if needed
5003  EPNAME("QueryProxy");
5004  XrdSutCERef ceref;
5005 
5006  bool hasproxy = 0;
5007  // We may already loaded valid proxies
5008  bool rdlock = false;
5009  XrdSutCacheArg_t arg = {timestamp, -1, -1, -1};
5010  XrdSutCacheEntry *cent = cache->Get(tag, rdlock, QueryProxyCheck, (void *) &arg);
5011  if (!cent) {
5012  PRINT("cannot get cache entry for: "<<tag);
5013  return -1;
5014  }
5015  ceref.Set(&(cent->rwmtx));
5016 
5017  if (checkcache && rdlock) {
5018  po->chain = (X509Chain *)(cent->buf1.buf);
5019  po->ksig = (XrdCryptoRSA *)(cent->buf2.buf);
5020  po->cbck = (XrdSutBucket *)(cent->buf3.buf);
5021  // We are done
5022  ceref.UnLock();
5023  return 0;
5024  }
5025 
5026  // Cleanup the chain
5027  po->chain = (X509Chain *)(cent->buf1.buf);
5028  if (po->chain) po->chain->Cleanup();
5029  SafeDelete(po->chain);
5030 
5031  // Cleanup cache entry
5032  cent->buf1.buf = 0;
5033  cent->buf1.len = 0;
5034  // The key is deleted by the certificate destructor
5035  // Just reset the buffer
5036  cent->buf2.buf = 0;
5037  cent->buf2.len = 0;
5038  // and the related bucket
5039  if (cent->buf3.buf)
5040  delete (XrdSutBucket *)(cent->buf3.buf);
5041  cent->buf3.buf = 0;
5042  cent->buf3.len = 0;
5043 
5044  //
5045  // We do not have good proxies, try load (user may have initialized
5046  // them in the meanwhile)
5047  // Create a new chain first, if needed
5048  if (!(po->chain))
5049  po->chain = new X509Chain();
5050  if (!(po->chain)) {
5051  PRINT("cannot create new chain!");
5052  return -1;
5053  }
5054  int ntry = 3;
5055  bool parsefile = 1;
5056  bool exportbucket = 0;
5058  XrdCryptoX509ParseBucket_t ParseBucket = 0;
5059  while (!hasproxy && ntry > 0) {
5060 
5061  // Try init as last option if not in pure cert/key mode
5062  if (ntry == 1 && pi->createpxy) {
5063 
5064  // Cleanup the chain
5065  po->chain->Cleanup();
5066 
5067  if (InitProxy(pi, cf, po->chain, &(po->ksig)) != 0) {
5068  NOTIFY("problems initializing proxy via external shell");
5069  ntry--;
5070  continue;
5071  }
5072  // We need to explicitely export the proxy in a bucket
5073  exportbucket = 1;
5074  // Chain is already loaded if we used the internal function
5075  // to initialize the proxies
5076  parsefile = 0;
5077  timestamp = time(0);
5078  }
5079  ntry--;
5080 
5081  //
5082  // A proxy chain may have been passed via XrdSecCREDS: check that first
5083  if (ntry == 2) {
5084 
5085  char *cbuf = getenv("XrdSecCREDS");
5086  if (cbuf) {
5087  // Import into a bucket
5088  XrdSutBucket xbck(0, 0, kXRS_x509);
5089  // Fill bucket
5090  xbck.SetBuf(cbuf, strlen(cbuf));
5091  // Parse the bucket
5092  if (!(ParseBucket = cf->X509ParseBucket())) {
5093  PRINT("cannot attach to ParseBucket function!");
5094  continue;
5095  }
5096  int nci = (*ParseBucket)(&xbck, po->chain);
5097  if (nci < 2) {
5098  NOTIFY("proxy bucket must have at least two certificates"
5099  " (found: "<<nci<<")");
5100  continue;
5101  }
5102  } else {
5103  // No env: parse the file
5104  ntry--;
5105  }
5106  }
5107  if (ntry == 1) {
5108  if (parsefile) {
5109  if (!ParseFile) {
5110  if (!(ParseFile = cf->X509ParseFile())) {
5111  PRINT("cannot attach to ParseFile function!");
5112  continue;
5113  }
5114  }
5115 
5116  // Parse the proxy file
5117  int nci = (*ParseFile)(pi->out, po->chain, 0);
5118  if (nci < 2) {
5119  DEBUG("proxy files must have at least 2 certificates"
5120  " (found: "<<nci<<")");
5121  if (!pi->createpxy) {
5122  // Parse the cert file if requested
5123  int nci = (*ParseFile)(pi->cert, po->chain, pi->key);
5124  if (nci < 1) {
5125  DEBUG("cert files must have at least 1 certificates"
5126  " (found: "<<nci<<")");
5127  continue;
5128  }
5129  } else {
5130  continue;
5131  }
5132  }
5133 
5134  // Check if any CA was in the file
5135  bool checkselfsigned = (CACheck > caVerifyss) ? true : false;
5136  po->chain->CheckCA(checkselfsigned);
5137  exportbucket = 1;
5138  }
5139  }
5140 
5141  // Check validity in time
5142  if (po->chain->CheckValidity(1, timestamp) != 0) {
5143  NOTIFY("proxy files contains expired certificates");
5144  continue;
5145  }
5146 
5147  // Reorder chain
5148  if (po->chain->Reorder() != 0) {
5149  NOTIFY("proxy files contains inconsistent certificates");
5150  continue;
5151  }
5152 
5153  // Check key
5154  po->ksig = po->chain->End()->PKI();
5155  if (po->ksig->status != XrdCryptoRSA::kComplete) {
5156  NOTIFY("proxy files contain invalid key pair");
5157  continue;
5158  }
5159 
5160  XrdCryptoX509ExportChain_t ExportChain = cf->X509ExportChain();
5161  if (!ExportChain) {
5162  PRINT("cannot attach to ExportChain function!");
5163  continue;
5164  }
5165 
5166  // Create bucket for export
5167  if (exportbucket) {
5168  po->cbck = (*ExportChain)(po->chain, 0);
5169  if (!(po->cbck)) {
5170  PRINT("could not create bucket for export");
5171  continue;
5172  }
5173  }
5174 
5175  // Save info in cache
5176  cent->mtime = po->chain->End()->NotAfter(); // the expiring time
5177  cent->status = kCE_special; // distinguish from normal certs
5178  cent->cnt = 0;
5179  // The chain
5180  cent->buf1.buf = (char *)(po->chain);
5181  cent->buf1.len = 0; // Just a flag
5182  // The key
5183  cent->buf2.buf = (char *)(po->chain->End()->PKI());
5184  cent->buf2.len = 0; // Just a flag
5185  // The export bucket
5186  cent->buf3.buf = (char *)(po->cbck);
5187  cent->buf3.len = 0; // Just a flag
5188 
5189  // Set the positive flag
5190  hasproxy = 1;
5191  }
5192  // Always unlock
5193  ceref.UnLock();
5194 
5195  // We are done
5196  if (!hasproxy) {
5197  // Some cleanup
5198  po->chain->Cleanup();
5199  SafeDelete(po->chain);
5200  SafeDelete(po->cbck);
5201  return -1;
5202  }
5203  return 0;
5204 }
5205 
5206 
5207 //_____________________________________________________________________________
5208 static bool QueryGMAPCheck(XrdSutCacheEntry *e, void *a) {
5209  int st_ref = (*((XrdSutCacheArg_t *)a)).arg1;
5210  time_t ts_ref = (time_t)(*((XrdSutCacheArg_t *)a)).arg2;
5211  long to_ref = (*((XrdSutCacheArg_t *)a)).arg3;
5212  if (e) {
5213  // Check expiration, if required
5214  if ((e->status != st_ref) ||
5215  ((e->status == st_ref) &&
5216  (to_ref > 0) &&
5217  ((ts_ref - e->mtime) > to_ref))) {
5218  return false;
5219  } else {
5220  return true;
5221  }
5222  }
5223  return false;
5224 }
5225 
5226 //__________________________________________________________________________
5227 void XrdSecProtocolgsi::QueryGMAP(XrdCryptoX509Chain *chain, int now, String &usrs)
5228 {
5229  // Resolve usernames associated with this proxy. The lookup is typically
5230  // based on the 'dn' (either in the grid mapfile or via the 'GMAPFun' plugin) but
5231  // it can also be based on the full proxy via the AuthzFun plugin.
5232  // For 'grid mapfile' and 'GMAPFun' the result is kept valid for a certain amount
5233  // of time, hashed on the 'dn'.
5234  // On return, an empty string in 'usrs' indicates failure.
5235  // Note that 'usrs' can be a comma-separated list of usernames.
5236  EPNAME("QueryGMAP");
5237 
5238  // List of user names attached to the entity
5239  usrs = "";
5240 
5241  // The chain must be defined
5242  if (!chain) {
5243  PRINT("input chain undefined!");
5244  return;
5245  }
5246 
5247  // Now we check the DN-mapping function and eventually the gridmap file.
5248  // The result can be cached for a while.
5249  const char *dn = chain->EECname();
5250  if (GMAPFun) {
5251  XrdSutCERef ceref;
5252  bool rdlock = false;
5253  XrdSutCacheArg_t arg = {kCE_ok, now, GMAPCacheTimeOut, -1};
5254  XrdSutCacheEntry *cent = cacheGMAPFun.Get(dn, rdlock, QueryGMAPCheck, (void *) &arg);
5255  if (!cent) {
5256  PRINT("unable to get a valid entry from cache for dn: " << dn);
5257  return;
5258  }
5259  ceref.Set(&(cent->rwmtx));
5260 
5261  // Check if we need to get/update the content
5262  if (!rdlock) {
5263  // Run the search via the external function
5264  char *name = (*GMAPFun)(dn, now);
5265  if (name) {
5266  cent->status = kCE_ok;
5267  // Add username
5268  SafeDelArray(cent->buf1.buf);
5269  cent->buf1.buf = name;
5270  cent->buf1.len = strlen(name);
5271  }
5272  // Fill up the rest
5273  cent->cnt = 0;
5274  cent->mtime = now; // creation time
5275  }
5276  // Retrieve result form cache
5277  usrs = cent->buf1.buf;
5278  // We are done with the cache
5279  ceref.UnLock();
5280  }
5281 
5282  // Check the map file, if any
5283  //
5284  if (servGMap) {
5285  char u[65];
5286  if (servGMap->dn2user(dn, u, sizeof(u), now) == 0) {
5287  if (usrs.length() > 0) usrs += ",";
5288  usrs += (const char *)u;
5289  }
5290  }
5291 
5292  // Done
5293  return;
5294 }
5295 
5296 //_____________________________________________________________________________
5297 XrdSecgsiGMAP_t XrdSecProtocolgsi::LoadGMAPFun(const char *plugin,
5298  const char *parms)
5299 {
5300  // Load the DN-Username mapping function from the specified plug-in
5301  EPNAME("LoadGMAPFun");
5302  char errBuff[2048];
5303 
5304  // Make sure the input config file is defined
5305  if (!plugin || strlen(plugin) <= 0) {
5306  PRINT("plug-in file undefined");
5307  return (XrdSecgsiGMAP_t)0;
5308  }
5309 
5310  // Create the plug-in instance
5311  XrdOucPinLoader gmapLib(errBuff,sizeof(errBuff),gsiVersion,"gmaplib",plugin);
5312 
5313  // Use global symbols?
5314  bool useglobals = 0;
5315  XrdOucString params, ps(parms), p;
5316  int from = 0;
5317  while ((from = ps.tokenize(p, from, '|')) != -1) {
5318  if (p == "useglobals") {
5319  useglobals = 1;
5320  } else {
5321  if (params.length() > 0) params += " ";
5322  params += p;
5323  }
5324  }
5325  DEBUG("params: '"<< params<<"'; useglobals: "<<useglobals);
5326 
5327  // Get the function
5328  XrdSecgsiGMAP_t ep = 0;
5329  if (useglobals) gmapLib.Global(true);
5330  ep = (XrdSecgsiGMAP_t) gmapLib.Resolve("XrdSecgsiGMAPFun");
5331 
5332  if (!ep) {
5333  PRINT(errBuff);
5334  PRINT("could not find 'XrdSecgsiGMAPFun()' in "<<plugin);
5335  return (XrdSecgsiGMAP_t)0;
5336  }
5337 
5338  // Init it
5339  if ((*ep)(params.c_str(), 0) == (char *)-1) {
5340  PRINT("could not initialize 'XrdSecgsiGMAPFun()'");
5341  return (XrdSecgsiGMAP_t)0;
5342  }
5343 
5344  // Notify
5345  PRINT("using 'XrdSecgsiGMAPFun()' from "<<plugin);
5346 
5347  // Done
5348  return ep;
5349 }
5350 
5351 //_____________________________________________________________________________
5352 XrdSecgsiAuthz_t XrdSecProtocolgsi::LoadAuthzFun(const char *plugin,
5353  const char *parms, int &certfmt)
5354 {
5355  // Load the authorization function from the specified plug-in.
5356  // The plug-in must contain three functions, to be all declared as 'extern C'.
5357  //
5358  // 1. The main function:
5359  //
5360  // int XrdSecgsiAuthzFun(XrdSecEntity &entity)
5361  //
5362  // here entity is the XrdSecEntity object associated with the handshake on the
5363  // server side. On input entity contains:
5364  // - in 'name' the username, DN, DN hash according to the GMAP option
5365  // - in 'host' the client hostname
5366  // - in 'creds'the proxy chain
5367  // The proxy chain can be either in 'raw' or 'PEM base64' format (see below).
5368  // This function returns
5369  // 0 on success
5370  // <0 on error (implies authentication failure)
5371  //
5372  // 2. The initialization function:
5373  //
5374  // int XrdSecgsiAuthzInit(const char *)
5375  //
5376  // here 'parameters' is the string of parameters, separated by ' '.
5377  // This function return <0 in case of failure or the format type of the proxy chain
5378  // expected by the main function:
5379  // 0 raw, to be used with XrdCrypto tools
5380  // 1 PEM (base64 standard string)
5381  //
5382  // 3. The key function:
5383  //
5384  // int XrdSecgsiAuthzKey(XrdSecEntity &entity, char **key)
5385  //
5386  // here entity is the XrdSecEntity object associated with the handshake on the
5387  // server side. On input entity contains in 'creds' the proxy chain, with the same
5388  // convention for the format as above. The function is expecetd to fill in '*key'
5389  // the key to be used to cache the result of the main function and to return the
5390  // length of the key. The key will be destroyed with 'delete []', so it must be
5391  // allocated internally with 'new char[]'.
5392  //
5393  EPNAME("LoadAuthzFun");
5394  char errBuff[2048];
5395 
5396  certfmt = -1;
5397  // Make sure the input config file is defined
5398  if (!plugin || strlen(plugin) <= 0) {
5399  PRINT("plug-in file undefined");
5400  return (XrdSecgsiAuthz_t)0;
5401  }
5402 
5403  // Create the plug-in instance
5404  XrdOucPinLoader authzLib(errBuff,sizeof(errBuff),gsiVersion,"authzlib",plugin);
5405 
5406  // Use global symbols?
5407  bool useglobals = 0;
5408  XrdOucString params, ps(parms), p;
5409  int from = 0;
5410  while ((from = ps.tokenize(p, from, '|')) != -1) {
5411  if (p == "useglobals") {
5412  useglobals = 1;
5413  } else {
5414  if (params.length() > 0) params += " ";
5415  params += p;
5416  }
5417  }
5418  DEBUG("params: '"<< params<<"'; useglobals: "<<useglobals);
5419 
5420  // Get the function
5421  XrdSecgsiAuthz_t ep = 0;
5422  if (useglobals) authzLib.Global(true);
5423  ep = (XrdSecgsiAuthz_t) authzLib.Resolve("XrdSecgsiAuthzFun");
5424  if (!ep) {
5425  PRINT(errBuff);
5426  PRINT("could not find 'XrdSecgsiAuthzFun()' in "<<plugin);
5427  return (XrdSecgsiAuthz_t)0;
5428  }
5429 
5430  // Get the key function
5431  AuthzKey = (XrdSecgsiAuthzKey_t) authzLib.Resolve("XrdSecgsiAuthzKey");
5432  if (!AuthzKey) {
5433  PRINT(errBuff);
5434  PRINT("could not find 'XrdSecgsiAuthzKey()' in "<<plugin);
5435  return (XrdSecgsiAuthz_t)0;
5436  }
5437 
5438  // Get the init function
5439  XrdSecgsiAuthzInit_t epinit = 0;
5440  epinit = (XrdSecgsiAuthzInit_t) authzLib.Resolve("XrdSecgsiAuthzInit");
5441  if (!epinit) {
5442  PRINT("could not find 'XrdSecgsiAuthzInit()' in "<<plugin);
5443  return (XrdSecgsiAuthz_t)0;
5444  }
5445 
5446  // Init it
5447  if ((certfmt = (*epinit)(params.c_str())) == -1) {
5448  PRINT("problems executing 'XrdSecgsiAuthzInit()' (rc: "<<certfmt<<")");
5449  return (XrdSecgsiAuthz_t)0;
5450  }
5451 
5452  // Notify
5453  PRINT("using 'XrdSecgsiAuthzFun()' from "<<plugin);
5454 
5455  // Done
5456  return ep;
5457 }
5458 
5459 //_____________________________________________________________________________
5460 XrdSecgsiVOMS_t XrdSecProtocolgsi::LoadVOMSFun(const char *plugin,
5461  const char *parms, int &certfmt)
5462 {
5463  // Load the authorization function from the specified plug-in.
5464  // The plug-in must contain two functions, to be all declared as 'extern C'.
5465  //
5466  // 1. The main function:
5467  //
5468  // int XrdSecgsiVOMSFun(XrdSecEntity &entity)
5469  //
5470  // here entity is the XrdSecEntity object associated with the handshake on the
5471  // server side. On input entity contains:
5472  // - in 'name' the username, DN, DN hash according to the GMAP option
5473  // - in 'host' the client hostname
5474  // - in 'creds'the proxy chain
5475  // The proxy chain can be either in 'raw' or 'PEM base64' format (see below).
5476  // This function returns
5477  // 0 on success
5478  // <0 on error (implies authentication failure)
5479  //
5480  // 2. The initialization function:
5481  //
5482  // int XrdSecgsiVOMSInit(const char *)
5483  //
5484  // here 'parameters' is the string of parameters, separated by ' '.
5485  // This function return <0 in case of failure or the format type of the proxy chain
5486  // expected by the main function:
5487  // 0 raw, to be used with XrdCrypto tools
5488  // 1 PEM (base64 standard string)
5489  //
5490  EPNAME("LoadVOMSFun");
5491  char errBuff[2048];
5492 
5493  certfmt = -1;
5494  // Make sure the input config file is defined
5495  if (!plugin || strlen(plugin) <= 0) {
5496  PRINT("plug-in file undefined");
5497  return (XrdSecgsiAuthz_t)0;
5498  }
5499 
5500  // Create the plug-in instance
5501  XrdOucPinLoader vomsLib(errBuff,sizeof(errBuff),gsiVersion,"vomslib",plugin);
5502 
5503  // Use global symbols?
5504  bool useglobals = 0;
5505  XrdOucString params, ps(parms), p;
5506  int from = 0;
5507  while ((from = ps.tokenize(p, from, '|')) != -1) {
5508  if (p == "useglobals") {
5509  useglobals = 1;
5510  } else {
5511  if (params.length() > 0) params += " ";
5512  params += p;
5513  }
5514  }
5515  DEBUG("params: '"<< params<<"'; useglobals: "<<useglobals);
5516 
5517  // Get the function
5518  XrdSecgsiVOMS_t ep = 0;
5519  if (useglobals) vomsLib.Global(true);
5520  ep = (XrdSecgsiVOMS_t) vomsLib.Resolve("XrdSecgsiVOMSFun");
5521  if (!ep) {
5522  PRINT(errBuff);
5523  PRINT("could not find 'XrdSecgsiVOMSFun()' in "<<plugin);
5524  return (XrdSecgsiAuthz_t)0;
5525  }
5526 
5527  // Get the init function
5528  XrdSecgsiVOMSInit_t epinit = 0;
5529  epinit = (XrdSecgsiVOMSInit_t) vomsLib.Resolve("XrdSecgsiVOMSInit");
5530  if (!epinit) {
5531  PRINT(errBuff);
5532  PRINT("could not find 'XrdSecgsiVOMSInit()' in "<<plugin);
5533  return (XrdSecgsiVOMS_t)0;
5534  }
5535 
5536  // Init it
5537  if ((certfmt = (*epinit)(params.c_str())) == -1) {
5538  PRINT("problems executing 'XrdSecgsiVOMSInit()' (rc: "<<certfmt<<")");
5539  return (XrdSecgsiVOMS_t)0;
5540  }
5541 
5542  // Notify
5543  PRINT("using 'XrdSecgsiVOMSFun()' from "<<plugin);
5544 
5545  // Done
5546  return ep;
5547 }
5548 
5549 
5550 //_____________________________________________________________________________
5551 bool XrdSecProtocolgsi::ServerCertNameOK(const char *subject, const char *hname, XrdOucString &emsg)
5552 {
5553  // Check that the server certificate subject name is consistent with the
5554  // expectations defined by the static SrvAllowedNames
5555 
5556  // The subject must be defined
5557  if (!subject || strlen(subject) <= 0) return 0;
5558 
5559  bool allowed = 0;
5560  emsg = "";
5561 
5562  // The server subject and its CN
5563  String srvsubj(subject);
5564  String srvcn;
5565  int cnidx = srvsubj.find("CN=");
5566  if (cnidx != STR_NPOS) srvcn.assign(srvsubj, cnidx + 3);
5567 
5568  // Always check if the server CN is in the standard form "[*/]<target host name>[/*]"
5569  if (hname) {
5570  size_t ih = srvcn.find("/");
5571  if (ih != std::string::npos) {
5572  srvcn.erasefromstart(ih + 1);
5573  }
5574  allowed = XrdCryptoX509::MatchHostnames(srvcn.c_str(), hname);
5575 
5576  // Update the error msg, if the case
5577  if (!allowed) {
5578  if (emsg.length() <= 0) {
5579  emsg = "server certificate CN '"; emsg += srvcn;
5580  emsg += "' does not match the expected format(s):";
5581  }
5582  String defcn("[*/]"); defcn += hname; defcn += "[/*]";
5583  emsg += " '"; emsg += defcn; emsg += "' (default)";
5584  }
5585  }
5586 
5587  // Take into account specific requests, if any
5588  if (SrvAllowedNames.length() > 0) {
5589  // The SrvAllowedNames string contains the allowed formats separated by a '|'.
5590  // The specifications can contain the <host> or <fqdn> placeholders which
5591  // are replaced by hname; they can also contain the '*' wildcard, in
5592  // which case XrdOucString::matches is used. A '-' before the specification
5593  // will deny the matching CN's; the last matching wins.
5594  String allowedfmts(SrvAllowedNames);
5595  allowedfmts.replace("<host>", hname);
5596  allowedfmts.replace("<fqdn>", hname);
5597  int from = 0;
5598  String fmt;
5599  while ((from = allowedfmts.tokenize(fmt, from, '|')) != -1) {
5600  // Check if this should be denied
5601  bool deny = 0;
5602  if (fmt.beginswith("-")) {
5603  deny = 1;
5604  fmt.erasefromstart(1);
5605  }
5606  if (srvcn.matches(fmt.c_str()) > 0) allowed = (deny) ? 0 : 1;
5607  }
5608  // Update the error msg, if the case
5609  if (!allowed) {
5610  if (emsg.length() <= 0) {
5611  emsg = "server certificate CN '"; emsg += srvcn;
5612  emsg += "' does not match the expected format:";
5613  }
5614  emsg += " '"; emsg += SrvAllowedNames; emsg += "' (exceptions)";
5615  }
5616  }
5617  // Reset error msg, if the match was successful
5618  if (allowed)
5619  emsg = "";
5620  else
5621  emsg += "; exceptions are controlled by the env XrdSecGSISRVNAMES";
5622 
5623  // Done
5624  return allowed;
5625 }
5626 
5627 //_____________________________________________________________________________
5628 static bool GetSrvCertEntCheck(XrdSutCacheEntry *e, void *a) {
5629  int st_ref = (*((XrdSutCacheArg_t *)a)).arg1;
5630  time_t ts_ref = (time_t)(*((XrdSutCacheArg_t *)a)).arg2;
5631  if (e) {
5632  if (e->status > st_ref) {
5633  if (e->mtime >= ts_ref)
5634  return true;
5635  }
5636  }
5637  return false;
5638 }
5639 
5640 //_____________________________________________________________________________
5641 XrdSutCacheEntry *XrdSecProtocolgsi::GetSrvCertEnt(XrdSutCERef &ceref,
5642  XrdCryptoFactory *cf,
5643  time_t timestamp, String &certcalist)
5644 {
5645  // Get cache entry for server certificate. This function checks the cache
5646  // and loads or re-loads the certificate form the specified files if required.
5647  // make sure we got what we need
5648  EPNAME("GetSrvCertEnt");
5649 
5650  if (!cf) {
5651  PRINT("Invalid inputs");
5652  return (XrdSutCacheEntry *)0;
5653  }
5654 
5655  bool rdlock = false;
5656  XrdSutCacheArg_t arg = {kCE_allowed, timestamp, -1, -1};
5657  XrdSutCacheEntry *cent = cacheCert.Get(cf->Name(), rdlock, GetSrvCertEntCheck, (void *) &arg);
5658  if (!cent) {
5659  PRINT("unable to get a valid entry from cache for " << cf->Name());
5660  return (XrdSutCacheEntry *)0;
5661  }
5662  ceref.Set(&(cent->rwmtx));
5663 
5664  // Are we done ?
5665  if (rdlock) return cent;
5666  if (cent->buf1.buf) PRINT("entry has expired: trying to renew ...");
5667 
5668  // Try get one or renew-it
5669  if (cent->status == kCE_special) {
5670  // Try init proxies
5671  ProxyIn_t pi = {SrvCert.c_str(), SrvKey.c_str(), CAdir.c_str(),
5672  UsrProxy.c_str(), PxyValid.c_str(), 0, 512, false};
5673  X509Chain *ch = 0;
5674  XrdCryptoRSA *k = 0;
5675  XrdSutBucket *b = 0;
5676  ProxyOut_t po = {ch, k, b };
5677  // We lock inside
5678  ceref.UnLock(false);
5679  if (QueryProxy(0, &cacheCert, cf->Name(), cf, timestamp, &pi, &po) != 0) {
5680  PRINT("proxy expired and cannot be renewed");
5681  return (XrdSutCacheEntry *)0;
5682  }
5683  // When successful we return read-locked (this flow needs checking; but it is not mainstream)
5684  ceref.ReadLock();
5685  return cent;
5686  }
5687 
5688  // Reset the entry
5689  XrdCryptoX509 *buf1 = (XrdCryptoX509*) cent->buf1.buf;
5690  XrdSutBucket *buf3 = (XrdSutBucket*) cent->buf3.buf;
5691 
5692  if (buf1)
5693  delete buf1; // Destroys also xsrv->PKI() pointed in cent->buf2.buf
5694  if (buf3)
5695  delete buf3;
5696 
5697  cent->buf1.buf = nullptr;
5698  cent->buf2.buf = nullptr;
5699  cent->buf3.buf = nullptr;
5700 
5701  //
5702  // Get the IDs of the file: we need them to acquire the right privileges when opening
5703  // the certificate
5704  uid_t gsi_uid = geteuid();
5705  gid_t gsi_gid = getegid();
5706  struct stat st;
5707  if (!stat(SrvKey.c_str(), &st)) {
5708  if (st.st_uid != gsi_uid || st.st_gid != gsi_gid) {
5709  gsi_uid = st.st_uid;
5710  gsi_gid = st.st_gid;
5711  }
5712  }
5713 
5714  // Check normal certificates
5715  XrdCryptoX509 *xsrv = cf->X509(SrvCert.c_str(), SrvKey.c_str());
5716  if (xsrv) {
5717  // Must be of EEC type
5718  if (xsrv->type != XrdCryptoX509::kEEC) {
5719  PRINT("problems loading srv cert: not EEC but: "<<xsrv->Type());
5720  SafeDelete(xsrv);
5721  ceref.UnLock();
5722  return (XrdSutCacheEntry *)0;
5723  }
5724  // Must be valid
5725  if (!(xsrv->IsValid())) {
5726  PRINT("problems loading srv cert: invalid");
5727  SafeDelete(xsrv);
5728  ceref.UnLock();
5729  return (XrdSutCacheEntry *)0;
5730  }
5731  // PKI must have been successfully initialized
5732  if (!xsrv->PKI() || xsrv->PKI()->status != XrdCryptoRSA::kComplete) {
5733  PRINT("problems loading srv cert: invalid PKI");
5734  SafeDelete(xsrv);
5735  ceref.UnLock();
5736  return (XrdSutCacheEntry *)0;
5737  }
5738  // Must be exportable
5739  XrdSutBucket *xbck = xsrv->Export();
5740  if (!xbck) {
5741  PRINT("problems loading srv cert: cannot export into bucket");
5742  SafeDelete(xsrv);
5743  ceref.UnLock();
5744  return (XrdSutCacheEntry *)0;
5745  }
5746  // We must have the issuing CA certificate
5747  int rcgetca = 0;
5748  if ((rcgetca = GetCA(xsrv->IssuerHash(), cf)) != 0) {
5749  String emsg(xsrv->IssuerHash());
5750  // Try different name hash, if it makes sense
5751  if (strcmp(xsrv->IssuerHash(1), xsrv->IssuerHash(0))) {
5752  if ((rcgetca = GetCA(xsrv->IssuerHash(1), cf)) != 0) {
5753  emsg += "|";
5754  emsg += xsrv->IssuerHash(1);
5755  }
5756  }
5757  if (rcgetca != 0) {
5758  // We do not have it, really
5759  if (rcgetca == -1) {
5760  PRINT("do not have certificate for the issuing CA '"<<emsg<<"'");
5761  } else {
5762  PRINT("failed to load certificate for the issuing CA '"<<emsg<<"'");
5763  }
5764  SafeDelete(xsrv);
5765  SafeDelete(xbck);
5766  ceref.UnLock();
5767  return (XrdSutCacheEntry *)0;
5768  }
5769  }
5770 
5771  // Ok: save it into the cache
5772  cent->status = kCE_ok;
5773  cent->cnt = 0;
5774  cent->mtime = xsrv->NotAfter(); // expiration time
5775 
5776  // Save pointer to certificate (destroys also xsrv->PKI())
5777  if (cent->buf1.buf)
5778  delete (XrdCryptoX509 *) cent->buf1.buf;
5779  cent->buf1.buf = (char *)xsrv;
5780  cent->buf1.len = 0; // just a flag
5781 
5782  // Save pointer to key
5783  cent->buf2.buf = (char *)(xsrv->PKI());
5784  cent->buf2.len = 0; // just a flag
5785 
5786  // Save pointer to bucket
5787  if (cent->buf3.buf)
5788  delete (XrdSutBucket *) cent->buf3.buf;
5789  cent->buf3.buf = (char *)(xbck);
5790  cent->buf3.len = 0; // just a flag
5791 
5792  // Save CA hash in list to communicate to clients
5793  if (certcalist.find(xsrv->IssuerHash()) == STR_NPOS) {
5794  if (certcalist.length() > 0) certcalist += "|";
5795  certcalist += xsrv->IssuerHash();
5796  }
5797  // Save also old CA hash in list to communicate to clients, if relevant
5798  if (HashCompatibility && xsrv->IssuerHash(1) &&
5799  strcmp(xsrv->IssuerHash(1),xsrv->IssuerHash())) {
5800  if (certcalist.find(xsrv->IssuerHash(1)) == STR_NPOS) {
5801  if (certcalist.length() > 0) certcalist += "|";
5802  certcalist += xsrv->IssuerHash(1);
5803  }
5804  }
5805  } else {
5806  PRINT("failed to load certificate from files ("<< SrvCert <<","<<SrvKey<<")");
5807  }
5808 
5809  // When successful we return read-locked; need to write-unlock before to avoid dead locking
5810  ceref.UnLock(false);
5811  ceref.ReadLock();
5812 
5813  // Done
5814  return cent;
5815 }
5816 
int kXR_int32
Definition: XPtypes.hh:89
#define DEBUG(x)
Definition: XrdBwmTrace.hh:54
#define EPNAME(x)
Definition: XrdBwmTrace.hh:56
#define TRACE_Debug
Definition: XrdCmsTrace.hh:37
#define QTRACE(act)
Definition: XrdCmsTrace.hh:49
void XrdCryptoSetTrace(kXR_int32 trace)
Definition: XrdCryptoAux.cc:49
static XrdSysError eDest(0,"crypto_")
#define cryptoTRACE_Notify
Definition: XrdCryptoAux.hh:49
#define cryptoTRACE_Dump
Definition: XrdCryptoAux.hh:47
#define cryptoTRACE_Debug
Definition: XrdCryptoAux.hh:48
#define XrdCryptoDefRSABits
Definition: XrdCryptoAux.hh:53
int(* XrdCryptoX509ChainToFile_t)(XrdCryptoX509Chain *, const char *)
int(* XrdCryptoX509CreateProxy_t)(const char *, const char *, XrdProxyOpt_t *, XrdCryptogsiX509Chain *, XrdCryptoRSA **, const char *)
int(* XrdCryptoX509SignProxyReq_t)(XrdCryptoX509 *, XrdCryptoRSA *, XrdCryptoX509Req *, XrdCryptoX509 **)
int(* XrdCryptoX509ParseBucket_t)(XrdSutBucket *, XrdCryptoX509Chain *)
XrdSutBucket *(* XrdCryptoX509ExportChain_t)(XrdCryptoX509Chain *, bool)
int(* XrdCryptoX509ParseFile_t)(const char *fname, XrdCryptoX509Chain *, const char *)
int(* XrdCryptoX509CreateProxyReq_t)(XrdCryptoX509 *, XrdCryptoX509Req **, XrdCryptoRSA **)
const int kOptsCheckSubCA
#define PRINT(y)
XrdOucGMap * XrdOucgetGMap(XrdOucGMapArgs)
Definition: XrdOucGMap.cc:92
#define STR_NPOS
int access(const char *path, int amode)
int closedir(DIR *dirp)
DIR * opendir(const char *path)
#define fopen(a, b)
Definition: XrdPosix.hh:54
#define stat(a, b)
Definition: XrdPosix.hh:101
#define readdir(a)
Definition: XrdPosix.hh:86
XrdSecBuffer XrdSecParameters
XrdSecBuffer XrdSecCredentials
static bool GetCACheck(XrdSutCacheEntry *e, void *a)
static const char * gGSErrStr[]
static const char * gsiServerSteps[]
static bool QueryProxyCheck(XrdSutCacheEntry *e, void *a)
static const int kOneDay
XrdSecProtocol * XrdSecProtocolgsiObject(const char mode, const char *hostname, XrdNetAddrInfo &endPoint, const char *parms, XrdOucErrInfo *erp)
static const char * gNoPadTag
static const char * ServerStepStr(int ksrv)
static const char * gUsrPxyDef
static const kXR_int32 Version
static String ProtoID
static bool GetSrvCertEntCheck(XrdSutCacheEntry *e, void *a)
static bool QueryGMAPCheck(XrdSutCacheEntry *e, void *a)
XrdVERSIONINFO(XrdSecProtocolgsiObject, secgsi)
#define POPTS(t, y)
static String Prefix
static const char * gsiClientSteps[]
char * XrdSecProtocolgsiInit(const char mode, const char *parms, XrdOucErrInfo *erp)
static bool AuthzFunCheck(XrdSutCacheEntry *e, void *a)
XrdOucTrace * gsiTrace
static const char * ClientStepStr(int kclt)
@ kOptsDelChn
@ kOptsDelPxy
@ kOptsSigReq
@ kOptsFwdPxy
@ kOptsPxCred
@ kOptsSrvReq
@ kOptsDlgPxy
@ kOptsCreatePxy
@ kOptsPxFile
#define SafeDelete(x)
const char * valid
int(* XrdSecgsiAuthz_t)(XrdSecEntity &)
XrdSutBucket * cbck
const char * out
XrdCryptoRSA * ksig
XrdCryptogsiX509Chain X509Chain
const char * key
#define REL2(x, y)
@ kXGS_cert
@ kXGS_none
@ kXGS_pxyreq
@ kXGS_init
@ kXGS_reserved
XrdSecgsiAuthz_t XrdSecgsiVOMS_t
int(* XrdSecgsiAuthzKey_t)(XrdSecEntity &, char **)
#define XrdSecgsiVersCertKey
#define XrdSecgsiVersDHsigned
@ kgST_ok
@ kgST_error
@ kgST_more
#define SafeFree(x)
int(* XrdSecgsiAuthzInit_t)(const char *)
char *(* XrdSecgsiGMAP_t)(const char *, int)
const char * cert
#define SafeDelArray(x)
#define XrdCryptoMax
@ kXGC_sigpxy
@ kXGC_cert
@ kXGC_reserved
@ kXGC_none
@ kXGC_certreq
#define XrdSecPROTOIDLEN
XrdSecgsiAuthzInit_t XrdSecgsiVOMSInit_t
#define REL3(x, y, z)
@ kGSErrExportPuK
@ kGSErrBadRndmTag
@ kGSErrNoCipher
@ kGSErrInit
@ kGSErrParseBuffer
@ kGSErrBadProtocol
@ kGSErrNoPublic
@ kGSErrSerialBuffer
@ kGSErrDecodeBuffer
@ kGSErrBadOpt
@ kGSErrAddBucket
@ kGSErrError
@ kGSErrCreateBucket
@ kGSErrNoBuffer
#define XrdSecPROTOIDENT
#define XrdSecgsiVERSION
X509Chain * chain
#define XrdSecNOIPCHK
#define TRACE_Authen
Definition: XrdSecTrace.hh:62
#define LIB_XRDVOMS
XrdCryptoX509ParseFile_t ParseFile
XrdOucString CAdir
XrdOucString CRLdir
bool Debug
XrdOucString CryptoMod
#define NOTIFY(y)
int ncrypt
XrdOucString DefCrypto
XrdOucString CryptList
XrdCryptoFactory ** CF
void ParseCrypto()
struct myOpts opts
int emsg(int rc, char *msg)
int XrdSutParseTime(const char *tstr, int opt)
Definition: XrdSutAux.cc:534
int XrdSutExpand(XrdOucString &path)
Definition: XrdSutAux.cc:360
int XrdSutResolve(XrdOucString &path, const char *ho, const char *vo, const char *gr, const char *us)
Definition: XrdSutAux.cc:419
const char * XrdSutHome()
Definition: XrdSutAux.cc:459
const char * XrdSutBuckStr(int kbck)
Definition: XrdSutAux.cc:121
void XrdSutSetTrace(kXR_int32 trace)
Definition: XrdSutAux.cc:93
@ kXRS_issuer_hash
Definition: XrdSutAux.hh:80
@ kXRS_user
Definition: XrdSutAux.hh:65
@ kXRS_signed_rtag
Definition: XrdSutAux.hh:64
@ kXRS_cipher_alg
Definition: XrdSutAux.hh:82
@ kXRS_rtag
Definition: XrdSutAux.hh:63
@ kXRS_version
Definition: XrdSutAux.hh:71
@ kXRS_message
Definition: XrdSutAux.hh:68
@ kXRS_x509
Definition: XrdSutAux.hh:79
@ kXRS_puk
Definition: XrdSutAux.hh:61
@ kXRS_cipher
Definition: XrdSutAux.hh:62
@ kXRS_main
Definition: XrdSutAux.hh:58
@ kXRS_x509_req
Definition: XrdSutAux.hh:81
@ kXRS_md_alg
Definition: XrdSutAux.hh:83
@ kXRS_cryptomod
Definition: XrdSutAux.hh:57
@ kXRS_clnt_opts
Definition: XrdSutAux.hh:76
#define sutTRACE_Notify
Definition: XrdSutAux.hh:100
#define sutTRACE_Debug
Definition: XrdSutAux.hh:99
#define sutTRACE_Dump
Definition: XrdSutAux.hh:98
@ kCE_special
@ kCE_ok
@ kCE_allowed
@ kCE_disabled
@ kCE_inactive
if(Avsz)
size_t strlcpy(char *dst, const char *src, size_t sz)
#define TRACE(act, x)
Definition: XrdTrace.hh:63
#define TRACE_ALL
Definition: XrdTrace.hh:35
#define ID
void Add(T *t)
void Del(T *t)
virtual int Length() const
virtual char * Buffer() const
virtual void SetIV(int l, const char *iv)
virtual int Decrypt(const char *in, int lin, char *out)
virtual int DecOutLength(int l)
virtual char * RefreshIV(int &l)
virtual int Encrypt(const char *in, int lin, char *out)
virtual int MaxIVLength() const
virtual XrdSutBucket * AsBucket()
virtual char * Public(int &lpub)
virtual bool IsValid()
virtual int EncOutLength(int l)
virtual bool Finalize(bool padded, char *pub, int lpub, const char *t)
virtual bool HasPaddingSupport()
virtual XrdCryptoX509ParseBucket_t X509ParseBucket()
virtual XrdCryptoX509CreateProxyReq_t X509CreateProxyReq()
virtual XrdCryptoX509 * X509(const char *cf, const char *kf=0)
virtual void SetTrace(kXR_int32 trace)
virtual XrdCryptoX509ParseFile_t X509ParseFile()
virtual XrdCryptoX509CreateProxy_t X509CreateProxy()
virtual XrdCryptoX509ChainToFile_t X509ChainToFile()
char * Name() const
virtual XrdCryptoCipher * Cipher(const char *t, int l=0)
virtual XrdCryptoRSA * RSA(int b=0, int e=0)
virtual bool SupportedMsgDigest(const char *dgst)
virtual XrdCryptoMsgDigest * MsgDigest(const char *dgst)
virtual XrdCryptoX509Crl * X509Crl(const char *crlfile, int opt=0)
static XrdCryptoFactory * GetCryptoFactory(const char *factoryname)
virtual bool SupportedCipher(const char *t)
virtual XrdCryptoX509Req * X509Req(XrdSutBucket *bck)
virtual XrdCryptoX509SignProxyReq_t X509SignProxyReq()
virtual XrdCryptoX509ExportChain_t X509ExportChain()
virtual void Notify()
virtual int Update(const char *b, int l)
virtual int Reset(const char *dgst)
virtual int ExportPrivate(char *out, int lout)
ERSAStatus status
Definition: XrdCryptoRSA.hh:58
virtual int EncryptPrivate(const char *in, int lin, char *out, int lout)
virtual int GetOutlen(int lin)
Definition: XrdCryptoRSA.cc:59
virtual int ImportPrivate(const char *in, int lin)
Definition: XrdCryptoRSA.cc:99
virtual int DecryptPublic(const char *in, int lin, char *out, int lout)
virtual int GetPrilen()
Definition: XrdCryptoRSA.cc:75
bool IsValid()
Definition: XrdCryptoRSA.hh:69
virtual int ExportPublic(char *out, int lout)
Definition: XrdCryptoRSA.cc:91
bool CheckCA(bool checkselfsigned=1)
XrdCryptoX509 * Next()
virtual int CheckValidity(bool outatfirst=1, int when=0)
XrdCryptoX509 * Begin()
XrdCryptoX509 * End() const
void Cleanup(bool keepCA=0)
void Remove(XrdCryptoX509 *c)
void SetStatusCA(ECAStatus st)
void PushBack(XrdCryptoX509 *c)
const char * X509ChainError(EX509ChainErr e)
XrdCryptoX509 * EffCA() const
const char * LastError() const
void PutInFront(XrdCryptoX509 *c)
virtual const char * IssuerHash(int)
virtual bool IsExpired(int when=0)
virtual bool Verify(XrdCryptoX509 *ref)
virtual XrdSutBucket * Export()
void SetVersion(int v)
virtual const char * Subject()
const char * Type(EX509Type t=kUnknown) const
virtual bool MatchesSAN(const char *fqdn, bool &hasSAN)=0
virtual XrdCryptoRSA * PKI()
virtual const char * SubjectHash(int)
virtual time_t NotBefore()
virtual const char * IssuerHash(int)
virtual XrdSutBucket * Export()
static bool MatchHostnames(const char *match_pattern, const char *fqdn)
virtual bool IsValid(int when=0)
virtual time_t NotAfter()
EX509Type type
bool Verify(EX509ChainErr &e, x509ChainVerifyOpt_t *vopt=0)
static const int noPort
Do not add port number.
static bool isHostName(const char *name)
int Format(char *bAddr, int bLen, fmtUse fmtType=fmtAuto, int fmtOpts=0)
@ fmtName
Hostname if it is resolvable o/w use fmtAddr.
const char * Name(const char *eName=0, const char **eText=0)
const char * Set(const char *hSpec, int pNum=PortInSpec)
Definition: XrdNetAddr.cc:216
char * Get(const char *varname)
Definition: XrdOucEnv.hh:69
const char * getErrText()
int setErrInfo(int code, const char *emsg)
XrdOucEnv * getEnv()
virtual int dn2user(const char *dn, char *user, int ulen, time_t now=0)
Definition: XrdOucGMap.cc:292
void insert(const int i, int start=-1)
const char * c_str() const
void assign(const char *s, int j, int k=-1)
int erasefromstart(int sz=0)
bool endswith(char c)
bool beginswith(char c)
int erase(int start=0, int size=0)
int matches(const char *s, char wch=' *')
int replace(const char *s1, const char *s2, int from=0, int to=-1)
int find(const char c, int start=0, bool forward=1)
int length() const
int form(const char *fmt,...)
int tokenize(XrdOucString &tok, int from, char del=':')
char * GetToken(char **rest=0, int lowcase=0)
bool Add(XrdSecAttr &attr)
char * vorg
Entity's virtual organization(s)
Definition: XrdSecEntity.hh:71
int credslen
Length of the 'creds' data.
Definition: XrdSecEntity.hh:78
XrdNetAddrInfo * addrInfo
Entity's connection details.
Definition: XrdSecEntity.hh:80
XrdSecEntityAttr * eaAPI
non-const API to attributes
Definition: XrdSecEntity.hh:92
const char * tident
Trace identifier always preset.
Definition: XrdSecEntity.hh:81
char prot[XrdSecPROTOIDSIZE]
Auth protocol used (e.g. krb5)
Definition: XrdSecEntity.hh:67
char * caps
Entity's capabilities.
Definition: XrdSecEntity.hh:74
char * creds
Raw entity credentials or cert.
Definition: XrdSecEntity.hh:77
char * grps
Entity's group name(s)
Definition: XrdSecEntity.hh:73
char * name
Entity's name.
Definition: XrdSecEntity.hh:69
char * role
Entity's role(s)
Definition: XrdSecEntity.hh:72
char * endorsements
Protocol specific endorsements.
Definition: XrdSecEntity.hh:75
char * moninfo
Information for monitoring.
Definition: XrdSecEntity.hh:76
char * host
Entity's host name dnr dependent.
Definition: XrdSecEntity.hh:70
XrdSecEntity Entity
static XrdOucTrace * EnableTracing()
int Authenticate(XrdSecCredentials *cred, XrdSecParameters **parms, XrdOucErrInfo *einfo=0)
int Verify(const char *inbuf, int inlen, const char *sigbuf, int siglen)
XrdSecProtocolgsi(int opts, const char *hname, XrdNetAddrInfo &endPoint, const char *parms=0)
int Decrypt(const char *inbuf, int inlen, XrdSecBuffer **outbuf)
int Encrypt(const char *inbuf, int inlen, XrdSecBuffer **outbuf)
void Delete()
Delete the protocol object. DO NOT use C++ delete() on this object.
static char * Init(gsiOptions o, XrdOucErrInfo *erp)
XrdSecCredentials * getCredentials(XrdSecParameters *parm=0, XrdOucErrInfo *einfo=0)
int getKey(char *kbuf=0, int klen=0)
int Sign(const char *inbuf, int inlen, XrdSecBuffer **outbuf)
int setKey(char *kbuf, int klen)
kXR_int32 type
Definition: XrdSutBucket.hh:46
kXR_int32 size
Definition: XrdSutBucket.hh:47
int SetBuf(const char *nb=0, int ns=0)
void ToString(XrdOucString &s)
void Update(char *nb=0, int ns=0, int ty=0)
Definition: XrdSutBucket.cc:95
int AddBucket(char *bp=0, int sz=0, int ty=0)
Definition: XrdSutBuffer.hh:59
int UpdateBucket(const char *bp, int sz, int ty)
int Serialized(char **buffer, char opt='n')
const char * GetOptions() const
Definition: XrdSutBuffer.hh:87
void SetStep(int s)
Definition: XrdSutBuffer.hh:90
void Dump(const char *stepstr=0, bool all=false)
int GetStep() const
Definition: XrdSutBuffer.hh:89
XrdSutBucket * GetBucket(kXR_int32 type, const char *tag=0)
kXR_int32 MarshalBucket(kXR_int32 type, kXR_int32 code)
const char * GetProtocol() const
Definition: XrdSutBuffer.hh:88
void Deactivate(kXR_int32 type)
kXR_int32 UnmarshalBucket(kXR_int32 type, kXR_int32 &code)
void UnLock(bool reset=true)
void ReadLock(XrdSysRWLock *lock=0)
void Set(XrdSysRWLock *lock)
XrdSysRWLock rwmtx
XrdSutCacheEntryBuf buf2
XrdSutCacheEntryBuf buf1
XrdSutCacheEntryBuf buf3
XrdSutCacheEntry * Get(const char *tag)
Definition: XrdSutCache.hh:54
void SetBuf(const char *b=0, kXR_int32 l=0)
kXR_int32 len
kXR_int32 mtime
XrdSutPFBuf buf1
XrdSutPFBuf buf4
static int GetRndmTag(XrdOucString &rtag)
Definition: XrdSutRndm.cc:235
XrdSysLogger * logger(XrdSysLogger *lp=0)
Definition: XrdSysError.hh:141
XrdSutPFEntry * Cref
X509Chain * PxyChain
XrdCryptoX509Crl * Crl
XrdSutBuffer * Parms
XrdSutBucket * Cbck
void Dump(XrdSecProtocolgsi *p=0)
X509Chain * Chain
XrdSutPFEntry * Pent
XrdCryptoCipher * Rcip
void Print(XrdOucTrace *t)
XrdSysLogger Logger
Definition: XrdGlobals.cc:47
Generic structure to pass security information back and forth.
char * buffer
Pointer to the buffer.
int size
Size of the buffer or length of data in the buffer.