XRootD
XrdCryptosslX509.cc
Go to the documentation of this file.
1 /******************************************************************************/
2 /* */
3 /* X r d C r y p t o s s l X 5 0 9 . 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 /* ************************************************************************** */
30 /* */
31 /* OpenSSL implementation of XrdCryptoX509 */
32 /* */
33 /* ************************************************************************** */
38 
39 #include <openssl/pem.h>
40 
41 #include <cerrno>
42 #include <memory>
43 
44 #include <fcntl.h>
45 #include <unistd.h>
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 
49 #define BIO_PRINT(b,c) \
50  BUF_MEM *bptr; \
51  BIO_get_mem_ptr(b, &bptr); \
52  if (bptr) { \
53  char *s = new char[bptr->length+1]; \
54  memcpy(s, bptr->data, bptr->length); \
55  s[bptr->length] = '\0'; \
56  PRINT(c << s); \
57  delete [] s; \
58  } else { \
59  PRINT("ERROR: "<<c<<" BIO internal buffer undefined!"); \
60  } \
61  if (b) BIO_free(b);
62 
63 const char *XrdCryptosslX509::cpxytype[5] = { "", "unknown", "RFC", "GSI3", "legacy" };
64 
65 //_____________________________________________________________________________
66 XrdCryptosslX509::XrdCryptosslX509(const char *cf, const char *kf)
67  : XrdCryptoX509()
68 {
69  // Constructor certificate from file 'cf'. If 'kf' is defined,
70  // complete the key of the certificate with the private key in kf.
71  EPNAME("X509::XrdCryptosslX509_file");
72 
73  // Init private members
74  cert = 0; // The certificate object
75  notbefore = -1; // begin-validity time in secs since Epoch
76  notafter = -1; // end-validity time in secs since Epoch
77  subject = ""; // subject;
78  issuer = ""; // issuer;
79  subjecthash = ""; // hash of subject;
80  issuerhash = ""; // hash of issuer;
81  subjectoldhash = ""; // hash of subject (md5 algorithm);
82  issueroldhash = ""; // hash of issuer (md5 algorithm);
83  srcfile = ""; // source file;
84  bucket = 0; // bucket for serialization
85  pki = 0; // PKI of the certificate
86  pxytype = 0; // Proxy sub-type
87 
88  // Make sure file name is defined;
89  if (!cf) {
90  DEBUG("file name undefined");
91  return;
92  }
93  // Make sure file exists;
94  struct stat st;
95  int fd = open(cf, O_RDONLY);
96 
97  if (fd == -1) {
98  if (errno == ENOENT) {
99  DEBUG("file "<<cf<<" does not exist - do nothing");
100  } else {
101  DEBUG("cannot open file "<<cf<<" (errno: "<<errno<<")");
102  }
103  return;
104  }
105 
106  if (fstat(fd, &st) != 0) {
107  DEBUG("cannot stat file "<<cf<<" (errno: "<<errno<<")");
108  close(fd);
109  return;
110  }
111  //
112  // Open file in read mode
113  FILE *fc = fdopen(fd, "r");
114  if (!fc) {
115  DEBUG("cannot fdopen file "<<cf<<" (errno: "<<errno<<")");
116  close(fd);
117  return;
118  }
119  //
120  // Read the content:
121  if (!PEM_read_X509(fc, &cert, 0, 0)) {
122  DEBUG("Unable to load certificate from file");
123  fclose(fc);
124  return;
125  } else {
126  DEBUG("certificate successfully loaded");
127  }
128  //
129  // Close the file
130  fclose(fc);
131  //
132  // Save source file name
133  srcfile = cf;
134 
135  // Init some of the private members (the others upon need)
136  Subject();
137  Issuer();
138  CertType();
139 
140  // Get the public key
141  EVP_PKEY *evpp = 0;
142  // Read the private key file, if specified
143  if (kf) {
144  int fd = open(kf, O_RDONLY);
145  if (fd == -1) {
146  DEBUG("cannot open file "<<kf<<" (errno: "<<errno<<")");
147  return;
148  }
149  if (fstat(fd, &st) == -1) {
150  DEBUG("cannot stat private key file "<<kf<<" (errno:"<<errno<<")");
151  close(fd);
152  return;
153  }
154  if (!S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) ||
155  (st.st_mode & (S_IROTH | S_IWOTH)) != 0 ||
156  (st.st_mode & (S_IWGRP)) != 0) {
157  DEBUG("private key file "<<kf<<" has wrong permissions "<<
158  (st.st_mode & 0777) << " (should be at most 0640)");
159  close(fd);
160  return;
161  }
162  // Open file in read mode
163  FILE *fk = fdopen(fd, "r");
164  if (!fk) {
165  DEBUG("cannot open file "<<kf<<" (errno: "<<errno<<")");
166  close(fd);
167  return;
168  }
169  // This call fills the full key, i.e. also the public part (not really documented, though)
170  if ((evpp = PEM_read_PrivateKey(fk,0,0,0))) {
171  DEBUG("RSA key completed ");
172  // Test consistency
173  auto tmprsa = std::make_unique<XrdCryptosslRSA>(evpp, 1);
174  if (tmprsa->status == XrdCryptoRSA::kComplete) {
175  // Save it in pki
176  pki = tmprsa.release();
177  }
178  } else {
179  DEBUG("cannot read the key from file");
180  }
181  // Close the file
182  fclose(fk);
183  }
184  // If there were no private key or we did not manage to import it
185  // init pki with the partial key
186  if (!pki)
187  pki = new XrdCryptosslRSA(X509_get_pubkey(cert), 0);
188 }
189 
190 //_____________________________________________________________________________
192 {
193  // Constructor certificate from BIO 'bcer'
194  EPNAME("X509::XrdCryptosslX509_bio");
195 
196  // Init private members
197  cert = 0; // The certificate object
198  notbefore = -1; // begin-validity time in secs since Epoch
199  notafter = -1; // end-validity time in secs since Epoch
200  subject = ""; // subject;
201  issuer = ""; // issuer;
202  subjecthash = ""; // hash of subject;
203  issuerhash = ""; // hash of issuer;
204  subjectoldhash = ""; // hash of subject (md5 algorithm);
205  issueroldhash = ""; // hash of issuer (md5 algorithm);
206  srcfile = ""; // source file;
207  bucket = 0; // bucket for serialization
208  pki = 0; // PKI of the certificate
209  pxytype = 0; // Proxy sub-type
210 
211  // Make sure we got something;
212  if (!buck) {
213  DEBUG("got undefined opaque buffer");
214  return;
215  }
216 
217  //
218  // Create a bio_mem to store the certificates
219  BIO *bmem = BIO_new(BIO_s_mem());
220  if (!bmem) {
221  DEBUG("unable to create BIO for memory operations");
222  return;
223  }
224 
225  // Write data to BIO
226  int nw = BIO_write(bmem,(const void *)(buck->buffer),buck->size);
227  if (nw != buck->size) {
228  DEBUG("problems writing data to memory BIO (nw: "<<nw<<")");
229  return;
230  }
231 
232  // Get certificate from BIO
233  if (!(cert = PEM_read_bio_X509(bmem,0,0,0))) {
234  DEBUG("unable to read certificate to memory BIO");
235  return;
236  }
237  //
238  // Free BIO
239  BIO_free(bmem);
240 
241  //
242  // Init some of the private members (the others upon need)
243  Subject();
244  Issuer();
245  CertType();
246 
247  // Get the public key
248  EVP_PKEY *evpp = X509_get_pubkey(cert);
249  //
250  if (evpp) {
251  // init pki with the partial key
252  if (!pki)
253  pki = new XrdCryptosslRSA(evpp, 0);
254  } else {
255  DEBUG("could not access the public key");
256  }
257 }
258 
259 //_____________________________________________________________________________
261 {
262  // Constructor: import X509 object
263  EPNAME("X509::XrdCryptosslX509_x509");
264 
265  // Init private members
266  cert = 0; // The certificate object
267  notbefore = -1; // begin-validity time in secs since Epoch
268  notafter = -1; // end-validity time in secs since Epoch
269  subject = ""; // subject;
270  issuer = ""; // issuer;
271  subjecthash = ""; // hash of subject;
272  issuerhash = ""; // hash of issuer;
273  subjectoldhash = ""; // hash of subject (md5 algorithm);
274  issueroldhash = ""; // hash of issuer (md5 algorithm);
275  srcfile = ""; // source file;
276  bucket = 0; // bucket for serialization
277  pki = 0; // PKI of the certificate
278  pxytype = 0; // Proxy sub-type
279 
280  // Make sure we got something;
281  if (!xc) {
282  DEBUG("got undefined X509 object");
283  return;
284  }
285 
286  // Set certificate
287  cert = xc;
288 
289  //
290  // Init some of the private members (the others upon need)
291  Subject();
292  Issuer();
293  CertType();
294 
295  // Get the public key
296  EVP_PKEY *evpp = X509_get_pubkey(cert);
297  //
298  if (evpp) {
299  // init pki with the partial key
300  if (!pki)
301  pki = new XrdCryptosslRSA(evpp, 0);
302  } else {
303  DEBUG("could not access the public key");
304  }
305 }
306 
307 //_____________________________________________________________________________
309 {
310  // Destructor
311 
312  // Cleanup certificate
313  if (cert) X509_free(cert);
314  // Cleanup key
315  if (pki) delete pki;
316 }
317 
318 //_____________________________________________________________________________
319 void XrdCryptosslX509::CertType()
320 {
321  // Determine the certificate type
322  // Check the type of this certificate
323  EPNAME("X509::CertType");
324 
325  // Make sure we got something to look for
326  if (!cert) {
327  PRINT("ERROR: certificate is not initialized");
328  return;
329  }
330 
331  // Default for an initialized certificate
332  type = kEEC;
333 
334  // Are there any extension?
335  int numext = X509_get_ext_count(cert);
336  if (numext <= 0) {
337  DEBUG("certificate has got no extensions");
338  return;
339  }
340  TRACE(ALL,"certificate has "<<numext<<" extensions");
341 
342  bool done = 0;
343  // Check the extensions
344  X509_EXTENSION *ext = 0;
345  int idx = -1;
346 
347  // For CAs we are looking for a "basicConstraints"
348  int crit;
349  BASIC_CONSTRAINTS *bc = 0;
350  if ((bc = (BASIC_CONSTRAINTS *)X509_get_ext_d2i(cert, NID_basic_constraints, &crit, &idx)) &&
351  bc->ca) {
352  type = kCA;
353  DEBUG("CA certificate");
354  done = 1;
355  }
356  if (bc) BASIC_CONSTRAINTS_free(bc);
357  if (done) return;
358 
359  // Is this a proxy?
360  idx = -1;
361  // Proxy names
362  XrdOucString common(subject, 0, subject.rfind("/CN=") - 1);
363  bool pxyname = 0;
364  if (issuer == common) {
365  pxyname = 1;
366  pxytype = 1;
367  }
368 
369  if (pxyname) {
370  type = kUnknown;
371  if ((idx = X509_get_ext_by_NID(cert, NID_proxyCertInfo,-1)) == -1) {
372  int xcp = -1;
374  if ((xcp = XrdCryptosslX509CheckProxy3(this, emsg)) == 0) {
375  type = kProxy;
376  pxytype = 3;
377  DEBUG("Found GSI 3 proxyCertInfo extension");
378  } else if (xcp == -1) {
379  PRINT("ERROR: "<<emsg);
380  }
381  } else {
382  if ((ext = X509_get_ext(cert,idx)) == 0) {
383  PRINT("ERROR: could not get proxyCertInfo extension");
384  }
385  }
386  }
387  if (ext) {
388  // RFC compliant or GSI 3 proxy
389  if (X509_EXTENSION_get_critical(ext)) {
390  PROXY_CERT_INFO_EXTENSION *pci = (PROXY_CERT_INFO_EXTENSION *)X509V3_EXT_d2i(ext);
391  if (pci != 0) {
392  if ((pci->proxyPolicy) != 0) {
393  if ((pci->proxyPolicy->policyLanguage) != 0) {
394  type = kProxy;
395  done = 1;
396  pxytype = 2;
397  DEBUG("Found RFC 382{0,1}compliant proxyCertInfo extension");
398  if (X509_get_ext_by_NID(cert, NID_proxyCertInfo, idx) != -1) {
399  PRINT("WARNING: multiple proxyCertInfo extensions found: taking the first");
400  }
401  } else {
402  PRINT("ERROR: accessing policy language from proxyCertInfo extension");
403  }
404  } else {
405  PRINT("ERROR: accessing policy from proxyCertInfo extension");
406  }
407  PROXY_CERT_INFO_EXTENSION_free(pci);
408  } else {
409  PRINT("ERROR: proxyCertInfo conversion error");
410  }
411  } else {
412  PRINT("ERROR: proxyCertInfo not flagged as critical");
413  }
414  }
415  if (!pxyname || done) return;
416 
417  // Check if GSI 2 legacy proxy
418  XrdOucString lastcn(subject, subject.rfind("/CN=") + 4, -1);
419  if (lastcn == "proxy" || lastcn == "limited proxy") {
420  pxytype = 4;
421  type = kProxy;
422  }
423 
424  // We are done
425  return;
426 }
427 
428 //_____________________________________________________________________________
430 {
431  // SetPKI:
432  // if newpki is null does nothing
433  // if newpki contains a consistent private & public key we take ownership
434  // so that this->PKI()->status will be kComplete.
435  // otherwise, newpki is not consistent:
436  // if the previous PKI() was null or was already kComplete it is and reset
437  // so that this->PKI()->status will be kInvalid.
438 
439  if (!newpki) return;
440 
441  auto tmprsa = std::make_unique<XrdCryptosslRSA>((EVP_PKEY*)newpki, 1);
442  if (!pki || pki->status == XrdCryptoRSA::kComplete ||
443  tmprsa->status == XrdCryptoRSA::kComplete) {
444  // Cleanup any existing key first
445  if (pki)
446  delete pki;
447 
448  // Set PKI
449  pki = tmprsa.release();
450  }
451 }
452 
453 //_____________________________________________________________________________
455 {
456  // Begin-validity time in secs since Epoch
457 
458  // If we do not have it already, try extraction
459  if (notbefore < 0) {
460  // Make sure we have a certificate
461  if (cert)
462  // Extract UTC time in secs from Epoch
463  notbefore = XrdCryptosslASN1toUTC(X509_get_notBefore(cert));
464  }
465  // return what we have
466  return notbefore;
467 }
468 
469 //_____________________________________________________________________________
471 {
472  // End-validity time in secs since Epoch
473 
474  // If we do not have it already, try extraction
475  if (notafter < 0) {
476  // Make sure we have a certificate
477  if (cert)
478  // Extract UTC time in secs from Epoch
479  notafter = XrdCryptosslASN1toUTC(X509_get_notAfter(cert));
480  }
481  // return what we have
482  return notafter;
483 }
484 
485 //_____________________________________________________________________________
487 {
488  // Return subject name
489  EPNAME("X509::Subject");
490 
491  // If we do not have it already, try extraction
492  if (subject.length() <= 0) {
493 
494  // Make sure we have a certificate
495  if (!cert) {
496  DEBUG("WARNING: no certificate available - cannot extract subject name");
497  return (const char *)0;
498  }
499 
500  // Extract subject name
501  XrdCryptosslNameOneLine(X509_get_subject_name(cert), subject);
502  }
503 
504  // return what we have
505  return (subject.length() > 0) ? subject.c_str() : (const char *)0;
506 }
507 
508 //_____________________________________________________________________________
510 {
511  // Return issuer name
512  EPNAME("X509::Issuer");
513 
514  // If we do not have it already, try extraction
515  if (issuer.length() <= 0) {
516 
517  // Make sure we have a certificate
518  if (!cert) {
519  DEBUG("WARNING: no certificate available - cannot extract issuer name");
520  return (const char *)0;
521  }
522 
523  // Extract issuer name
524  XrdCryptosslNameOneLine(X509_get_issuer_name(cert), issuer);
525  }
526 
527  // return what we have
528  return (issuer.length() > 0) ? issuer.c_str() : (const char *)0;
529 }
530 
531 //_____________________________________________________________________________
532 const char *XrdCryptosslX509::IssuerHash(int alg)
533 {
534  // Return hash of issuer name
535  // Use default algorithm (X509_NAME_hash) for alg = 0, old algorithm
536  // (for v>=1.0.0) when alg = 1
537  EPNAME("X509::IssuerHash");
538 
539  if (alg == 1) {
540  // md5 based
541  if (issueroldhash.length() <= 0) {
542  // Make sure we have a certificate
543  if (cert) {
544  char chash[30] = {0};
545  snprintf(chash, sizeof(chash),
546  "%08lx.0",X509_NAME_hash_old(X509_get_issuer_name(cert)));
547  issueroldhash = chash;
548  } else {
549  DEBUG("WARNING: no certificate available - cannot extract issuer hash (md5)");
550  }
551  }
552  // return what we have
553  return (issueroldhash.length() > 0) ? issueroldhash.c_str() : (const char *)0;
554  }
555 
556  // If we do not have it already, try extraction
557  if (issuerhash.length() <= 0) {
558 
559  // Make sure we have a certificate
560  if (cert) {
561  char chash[30] = {0};
562  snprintf(chash, sizeof(chash),
563  "%08lx.0",X509_NAME_hash(X509_get_issuer_name(cert)));
564  issuerhash = chash;
565  } else {
566  DEBUG("WARNING: no certificate available - cannot extract issuer hash (default)");
567  }
568  }
569 
570  // return what we have
571  return (issuerhash.length() > 0) ? issuerhash.c_str() : (const char *)0;
572 }
573 
574 //_____________________________________________________________________________
575 const char *XrdCryptosslX509::SubjectHash(int alg)
576 {
577  // Return hash of subject name
578  // Use default algorithm (X509_NAME_hash) for alg = 0, old algorithm
579  // (for v>=1.0.0) when alg = 1
580  EPNAME("X509::SubjectHash");
581 
582  if (alg == 1) {
583  // md5 based
584  if (subjectoldhash.length() <= 0) {
585  // Make sure we have a certificate
586  if (cert) {
587  char chash[30] = {0};
588  snprintf(chash, sizeof(chash),
589  "%08lx.0",X509_NAME_hash_old(X509_get_subject_name(cert)));
590  subjectoldhash = chash;
591  } else {
592  DEBUG("WARNING: no certificate available - cannot extract subject hash (md5)");
593  }
594  }
595  // return what we have
596  return (subjectoldhash.length() > 0) ? subjectoldhash.c_str() : (const char *)0;
597  }
598 
599  // If we do not have it already, try extraction
600  if (subjecthash.length() <= 0) {
601 
602  // Make sure we have a certificate
603  if (cert) {
604  char chash[30] = {0};
605  snprintf(chash, sizeof(chash),
606  "%08lx.0",X509_NAME_hash(X509_get_subject_name(cert)));
607  subjecthash = chash;
608  } else {
609  DEBUG("WARNING: no certificate available - cannot extract subject hash (default)");
610  }
611  }
612 
613  // return what we have
614  return (subjecthash.length() > 0) ? subjecthash.c_str() : (const char *)0;
615 }
616 
617 //_____________________________________________________________________________
619 {
620  // Return serial number as a kXR_int64
621 
622  kXR_int64 sernum = -1;
623  if (cert && X509_get_serialNumber(cert)) {
624  BIGNUM *bn = BN_new();
625  ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), bn);
626  char *sn = BN_bn2dec(bn);
627  sernum = strtoll(sn, 0, 10);
628  BN_free(bn);
629  OPENSSL_free(sn);
630  }
631 
632  return sernum;
633 }
634 
635 //_____________________________________________________________________________
637 {
638  // Return serial number as a hex string
639 
640  XrdOucString sernum;
641  if (cert && X509_get_serialNumber(cert)) {
642  BIGNUM *bn = BN_new();
643  ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), bn);
644  char *sn = BN_bn2hex(bn);
645  sernum = sn;
646  BN_free(bn);
647  OPENSSL_free(sn);
648  }
649 
650  return sernum;
651 }
652 
653 //_____________________________________________________________________________
655 {
656  // Return pointer to extension with OID oid, if any, in
657  // opaque form
658  EPNAME("X509::GetExtension");
659  XrdCryptoX509data ext = 0;
660 
661  // Make sure we got something to look for
662  if (!oid) {
663  DEBUG("OID string not defined");
664  return ext;
665  }
666 
667  // Make sure we got something to look for
668  if (!cert) {
669  DEBUG("certificate is not initialized");
670  return ext;
671  }
672 
673  // Are there any extension?
674  int numext = X509_get_ext_count(cert);
675  if (numext <= 0) {
676  DEBUG("certificate has got no extensions");
677  return ext;
678  }
679  DEBUG("certificate has "<<numext<<" extensions");
680 
681  // If the string is the Standard Name of a known extension check
682  // searche the corresponding NID
683  int nid = OBJ_sn2nid(oid);
684  bool usenid = (nid > 0);
685 
686  // Loop to identify the one we would like
687  int i = 0;
688  X509_EXTENSION *wext = 0;
689  for (i = 0; i< numext; i++) {
690  wext = X509_get_ext(cert, i);
691  if (usenid) {
692  int enid = OBJ_obj2nid(X509_EXTENSION_get_object(wext));
693  if (enid == nid)
694  break;
695  } else {
696  // Try matching of the text
697  char s[256];
698  OBJ_obj2txt(s, sizeof(s), X509_EXTENSION_get_object(wext), 1);
699  if (!strcmp(s, oid))
700  break;
701  }
702  // Do not free the extension: its owned by the certificate
703  wext = 0;
704  }
705 
706  // We are done if nothing was found
707  if (!wext) {
708  DEBUG("Extension "<<oid<<" not found");
709  return ext;
710  }
711 
712  // We are done
713  return (XrdCryptoX509data)wext;
714 }
715 
716 //_____________________________________________________________________________
718 {
719  // Export in form of bucket
720  EPNAME("X509::Export");
721 
722  // If we have already done it, return the previous result
723  if (bucket) {
724  DEBUG("serialization already performed:"
725  " return previous result ("<<bucket->size<<" bytes)");
726  return bucket;
727  }
728 
729  // Make sure we got something to export
730  if (!cert) {
731  DEBUG("certificate is not initialized");
732  return 0;
733  }
734 
735  //
736  // Now we create a bio_mem to serialize the certificate
737  BIO *bmem = BIO_new(BIO_s_mem());
738  if (!bmem) {
739  DEBUG("unable to create BIO for memory operations");
740  return 0;
741  }
742 
743  // Write certificate to BIO
744  if (!PEM_write_bio_X509(bmem, cert)) {
745  DEBUG("unable to write certificate to memory BIO");
746  return 0;
747  }
748 
749  // Extract pointer to BIO data and length of segment
750  char *bdata = 0;
751  int blen = BIO_get_mem_data(bmem, &bdata);
752  DEBUG("BIO data: "<<blen<<" bytes at 0x"<<(int *)bdata);
753 
754  // create the bucket now
755  bucket = new XrdSutBucket(0,0,kXRS_x509);
756  if (bucket) {
757  // Fill bucket
758  bucket->SetBuf(bdata, blen);
759  DEBUG("result of serialization: "<<bucket->size<<" bytes");
760  } else {
761  DEBUG("unable to create bucket for serialized format");
762  BIO_free(bmem);
763  return 0;
764  }
765  //
766  // Free BIO
767  BIO_free(bmem);
768  //
769  // We are done
770  return bucket;
771 }
772 
773 //_____________________________________________________________________________
775 {
776  // Verify certificate signature with pub key of ref cert
777  EPNAME("X509::Verify");
778 
779  // We must have been initialized
780  if (!cert)
781  return 0;
782 
783  // We must have something to check with
784  X509 *r = ref ? (X509 *)(ref->Opaque()) : 0;
785  EVP_PKEY *rk = r ? X509_get_pubkey(r) : 0;
786  if (!rk)
787  return 0;
788 
789  // Ok: we can verify
790  int rc = X509_verify(cert, rk);
791  EVP_PKEY_free(rk);
792  if (rc <= 0) {
793  if (rc == 0) {
794  // Signatures are not OK
795  DEBUG("signature not OK");
796  } else {
797  // General failure
798  DEBUG("could not verify signature");
799  }
800  return 0;
801  }
802  // Success
803  return 1;
804 }
805 
806 //____________________________________________________________________________
807 int XrdCryptosslX509::DumpExtensions(bool dumpunknown)
808 {
809  // Dump our extensions, if any
810  // Returns -1 on failure, 0 on success
811  EPNAME("DumpExtensions");
812 
813  int rc = -1;
814  // Point to the cerificate
815  X509 *xpi = (X509 *) Opaque();
816 
817  // Make sure we got the right inputs
818  if (!xpi) {
819  PRINT("we are empty! Do nothing");
820  return rc;
821  }
822 
823  rc = 1;
824  // Go through the extensions
825  X509_EXTENSION *xpiext = 0;
826  int npiext = X509_get_ext_count(xpi);
827  PRINT("found "<<npiext<<" extensions ");
828  int i = 0;
829  for (i = 0; i< npiext; i++) {
830  xpiext = X509_get_ext(xpi, i);
831  char s[256];
832  OBJ_obj2txt(s, sizeof(s), X509_EXTENSION_get_object(xpiext), 1);
833  int crit = X509_EXTENSION_get_critical(xpiext);
834  // Notify what we found
835  PRINT(i << ": found extension '"<<s<<"', critical: " << crit);
836  // Dump its content
837  rc = 0;
838  const unsigned char *pp = (const unsigned char *) X509_EXTENSION_get_data(xpiext)->data;
839  long length = X509_EXTENSION_get_data(xpiext)->length;
840  int ret = FillUnknownExt(&pp, length, dumpunknown);
841  PRINT("ret: " << ret);
842  }
843 
844  // Done
845  return rc;
846 }
847 
848 //____________________________________________________________________________
849 int XrdCryptosslX509::FillUnknownExt(const unsigned char **pp, long length, bool dump)
850 {
851  // Do the actual filling of the bio; can be called recursevely
852  EPNAME("FillUnknownExt");
853 
854  const unsigned char *p,*ep,*tot,*op,*opp;
855  long len;
856  int tag, xclass, ret = 0;
857  int nl,hl,j,r;
858  ASN1_OBJECT *o = 0;
859  ASN1_OCTET_STRING *os = 0;
860  /* ASN1_BMPSTRING *bmp=NULL;*/
861  int dump_indent = 6;
862  int depth = 0;
863  int indent = 0;
864 
865  p = *pp;
866  tot = p + length;
867  op = p - 1;
868  while ((p < tot) && (op < p)) {
869  op = p;
870  j = ASN1_get_object(&p, &len, &tag, &xclass, length);
871 #ifdef LINT
872  j = j;
873 #endif
874  if (j & 0x80) {
875  if (dump) PRINT("ERROR: error in encoding");
876  ret = 0;
877  goto end;
878  }
879  hl = (p-op);
880  length -= hl;
881  /* if j == 0x21 it is a constructed indefinite length object */
882 
883  if (j != (V_ASN1_CONSTRUCTED | 1)) {
884  if (dump) PRINT("PRIM: d="<<depth<<" hl="<<hl<<" l="<<len);
885  } else {
886  if (dump) PRINT("CONST: d="<<depth<<" hl="<<hl<<" l=inf ");
887  }
888  if (!Asn1PrintInfo(tag, xclass, j, (indent) ? depth : 0))
889  goto end;
890  if (j & V_ASN1_CONSTRUCTED) {
891  ep = p + len;
892  if (dump) PRINT(" ");
893  if (len > length) {
894  if (dump) PRINT("ERROR:CONST: length is greater than " <<length);
895  ret=0;
896  goto end;
897  }
898  if ((j == 0x21) && (len == 0)) {
899  for (;;) {
900  r = FillUnknownExt(&p, (long)(tot-p), dump);
901  if (r == 0) {
902  ret = 0;
903  goto end;
904  }
905  if ((r == 2) || (p >= tot))
906  break;
907  }
908  } else {
909  while (p < ep) {
910  r = FillUnknownExt(&p, (long)len, dump);
911  if (r == 0) {
912  ret = 0;
913  goto end;
914  }
915  }
916  }
917  } else if (xclass != 0) {
918  p += len;
919  if (dump) PRINT(" ");
920  } else {
921  nl = 0;
922  if ((tag == V_ASN1_PRINTABLESTRING) ||
923  (tag == V_ASN1_T61STRING) ||
924  (tag == V_ASN1_IA5STRING) ||
925  (tag == V_ASN1_VISIBLESTRING) ||
926  (tag == V_ASN1_NUMERICSTRING) ||
927  (tag == V_ASN1_UTF8STRING) ||
928  (tag == V_ASN1_UTCTIME) ||
929  (tag == V_ASN1_GENERALIZEDTIME)) {
930  if (len > 0) {
931  char *s = new char[len + 1];
932  memcpy(s, p, len);
933  s[len] = 0;
934  if (dump) PRINT("GENERIC:" << s <<" (len: "<<(int)len<<")");
935  delete [] s;
936  } else {
937  if (dump) PRINT("GENERIC: (len: "<<(int)len<<")");
938  }
939  } else if (tag == V_ASN1_OBJECT) {
940  opp = op;
941  if (d2i_ASN1_OBJECT(&o, &opp, len+hl)) {
942  BIO *mem = BIO_new(BIO_s_mem());
943  i2a_ASN1_OBJECT(mem, o);
944  XrdOucString objstr;
945  if (dump) { BIO_PRINT(mem, "AOBJ:"); }
946  } else {
947  if (dump) PRINT("ERROR:AOBJ: BAD OBJECT");
948  }
949  } else if (tag == V_ASN1_BOOLEAN) {
950  if (len != 1) {
951  if (dump) PRINT("ERROR:BOOL: Bad boolean");
952  goto end;
953  }
954  if (dump) PRINT("BOOL:"<< p[0]);
955  } else if (tag == V_ASN1_BMPSTRING) {
956  /* do the BMP thang */
957  } else if (tag == V_ASN1_OCTET_STRING) {
958  int i, printable = 1;
959  opp = op;
960  os = d2i_ASN1_OCTET_STRING(0, &opp, len + hl);
961  if (os && os->length > 0) {
962  opp = os->data;
963  /* testing whether the octet string is * printable */
964  for (i=0; i<os->length; i++) {
965  if (( (opp[i] < ' ') && (opp[i] != '\n') &&
966  (opp[i] != '\r') && (opp[i] != '\t')) || (opp[i] > '~')) {
967  printable = 0;
968  break;
969  }
970  }
971  if (printable) {
972  /* printable string */
973  char *s = new char[os->length + 1];
974  memcpy(s, opp, os->length);
975  s[os->length] = 0;
976  if (dump) PRINT("OBJS:" << s << " (len: "<<os->length<<")");
977  delete [] s;
978  } else {
979  /* print the normal dump */
980  if (!nl) PRINT("OBJS:");
981  BIO *mem = BIO_new(BIO_s_mem());
982  if (BIO_dump_indent(mem, (const char *)opp, os->length, dump_indent) <= 0) {
983  if (dump) PRINT("ERROR:OBJS: problems dumping to BIO");
984  BIO_free(mem);
985  goto end;
986  }
987  if (dump) { BIO_PRINT(mem, "OBJS:"); }
988  nl = 1;
989  }
990  }
991  if (os) {
992  ASN1_OCTET_STRING_free(os);
993  os = 0;
994  }
995  } else if (tag == V_ASN1_INTEGER) {
996  ASN1_INTEGER *bs;
997  int i;
998 
999  opp = op;
1000  bs = d2i_ASN1_INTEGER(0, &opp, len+hl);
1001  if (bs) {
1002  if (dump) PRINT("AINT:");
1003  if (bs->type == V_ASN1_NEG_INTEGER)
1004  if (dump) PRINT("-");
1005  BIO *mem = BIO_new(BIO_s_mem());
1006  for (i = 0; i < bs->length; i++) {
1007  if (BIO_printf(mem, "%02X", bs->data[i]) <= 0) {
1008  if (dump) PRINT("ERROR:AINT: problems printf-ing to BIO");
1009  BIO_free(mem);
1010  goto end;
1011  }
1012  }
1013  if (dump) { BIO_PRINT(mem, "AINT:"); }
1014  if (bs->length == 0) PRINT("00");
1015  } else {
1016  if (dump) PRINT("ERROR:AINT: BAD INTEGER");
1017  }
1018  ASN1_INTEGER_free(bs);
1019  } else if (tag == V_ASN1_ENUMERATED) {
1020  ASN1_ENUMERATED *bs;
1021  int i;
1022 
1023  opp = op;
1024  bs = d2i_ASN1_ENUMERATED(0, &opp, len+hl);
1025  if (bs) {
1026  if (dump) PRINT("AENU:");
1027  if (bs->type == V_ASN1_NEG_ENUMERATED)
1028  if (dump) PRINT("-");
1029  BIO *mem = BIO_new(BIO_s_mem());
1030  for (i = 0; i < bs->length; i++) {
1031  if (BIO_printf(mem, "%02X", bs->data[i]) <= 0) {
1032  if (dump) PRINT("ERROR:AENU: problems printf-ing to BIO");
1033  BIO_free(mem);
1034  goto end;
1035  }
1036  }
1037  if (dump) { BIO_PRINT(mem, "AENU:"); }
1038  if (bs->length == 0) PRINT("00");
1039  } else {
1040  if (dump) PRINT("ERROR:AENU: BAD ENUMERATED");
1041  }
1042  ASN1_ENUMERATED_free(bs);
1043  }
1044 
1045  if (!nl && dump) PRINT(" ");
1046 
1047  p += len;
1048  if ((tag == V_ASN1_EOC) && (xclass == 0)) {
1049  ret = 2; /* End of sequence */
1050  goto end;
1051  }
1052  }
1053  length -= len;
1054  }
1055  ret = 1;
1056 end:
1057  if (o) ASN1_OBJECT_free(o);
1058  if (os) ASN1_OCTET_STRING_free(os);
1059  *pp = p;
1060  if (dump) PRINT("ret: "<<ret);
1061 
1062  return ret;
1063 }
1064 
1065 //____________________________________________________________________________
1066 int XrdCryptosslX509::Asn1PrintInfo(int tag, int xclass, int constructed, int indent)
1067 {
1068  // Print the BIO content
1069  EPNAME("Asn1PrintInfo");
1070 
1071  static const char fmt[]="%-18s";
1072  static const char fmt2[]="%2d %-15s";
1073  char str[128];
1074  const char *p, *p2 = 0;
1075 
1076  BIO *bp = BIO_new(BIO_s_mem());
1077  if (constructed & V_ASN1_CONSTRUCTED)
1078  p = "cons: ";
1079  else
1080  p = "prim: ";
1081  if (BIO_write(bp, p, 6) < 6)
1082  goto err;
1083  BIO_indent(bp, indent, 128);
1084 
1085  p = str;
1086  if ((xclass & V_ASN1_PRIVATE) == V_ASN1_PRIVATE)
1087  BIO_snprintf(str,sizeof str,"priv [ %d ] ",tag);
1088  else if ((xclass & V_ASN1_CONTEXT_SPECIFIC) == V_ASN1_CONTEXT_SPECIFIC)
1089  BIO_snprintf(str,sizeof str,"cont [ %d ]",tag);
1090  else if ((xclass & V_ASN1_APPLICATION) == V_ASN1_APPLICATION)
1091  BIO_snprintf(str,sizeof str,"appl [ %d ]",tag);
1092  else if (tag > 30)
1093  BIO_snprintf(str,sizeof str,"<ASN1 %d>",tag);
1094  else
1095  p = ASN1_tag2str(tag);
1096 
1097  if (p2) {
1098  if (BIO_printf(bp,fmt2,tag,p2) <= 0)
1099  goto err;
1100  } else {
1101  if (BIO_printf(bp, fmt, p) <= 0)
1102  goto err;
1103  }
1104  BIO_PRINT(bp, "A1PI:");
1105  return(1);
1106 err:
1107  BIO_free(bp);
1108  return(0);
1109 }
1110 
1111 //____________________________________________________________________________
1112 bool XrdCryptosslX509::MatchesSAN(const char *fqdn, bool &hasSAN)
1113 {
1114  EPNAME("MatchesSAN");
1115 
1116  // Statically allocated array for hostname lengths. RFC1035 limits
1117  // valid lengths to 255 characters.
1118  char san_fqdn[256];
1119 
1120  // Assume we have no SAN extension. Failure may allow the caller to try
1121  // using the common name before giving up.
1122  hasSAN = false;
1123 
1124  GENERAL_NAMES *gens = static_cast<GENERAL_NAMES *>(X509_get_ext_d2i(cert,
1125  NID_subject_alt_name, NULL, NULL));
1126  if (!gens)
1127  return false;
1128 
1129  // Only an EEC is usable as a host certificate.
1130  if (type != kEEC)
1131  return false;
1132 
1133  // All failures are under the notion that we have a SAN extension.
1134  hasSAN = true;
1135 
1136  if (!fqdn)
1137  return false;
1138 
1139  bool success = false;
1140  for (int idx = 0; idx < sk_GENERAL_NAME_num(gens); idx++) {
1141  GENERAL_NAME *gen;
1142  ASN1_STRING *cstr;
1143  gen = sk_GENERAL_NAME_value(gens, idx);
1144  if (gen->type != GEN_DNS)
1145  continue;
1146  cstr = gen->d.dNSName;
1147  if (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING)
1148  continue;
1149  int san_fqdn_len = ASN1_STRING_length(cstr);
1150  if (san_fqdn_len > 255)
1151  continue;
1152  memcpy(san_fqdn, ASN1_STRING_get0_data(cstr), san_fqdn_len);
1153  san_fqdn[san_fqdn_len] = '\0';
1154  if (strlen(san_fqdn) != static_cast<size_t>(san_fqdn_len)) // Avoid embedded null's.
1155  continue;
1156  DEBUG("Comparing SAN " << san_fqdn << " with " << fqdn);
1157  if (MatchHostnames(san_fqdn, fqdn)) {
1158  DEBUG("SAN " << san_fqdn << " matches with " << fqdn);
1159  success = true;
1160  break;
1161  }
1162  }
1163  sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
1164  return success;
1165 }
long long kXR_int64
Definition: XPtypes.hh:98
#define DEBUG(x)
Definition: XrdBwmTrace.hh:54
#define EPNAME(x)
Definition: XrdBwmTrace.hh:56
void * XrdCryptoX509data
void XrdCryptosslNameOneLine(X509_NAME *nm, XrdOucString &s)
time_t XrdCryptosslASN1toUTC(const ASN1_TIME *tsn1)
int XrdCryptosslX509CheckProxy3(XrdCryptoX509 *, XrdOucString &)
#define PRINT(y)
#define BIO_PRINT(b, c)
int fclose(FILE *stream)
#define close(a)
Definition: XrdPosix.hh:48
#define fstat(a, b)
Definition: XrdPosix.hh:62
#define open
Definition: XrdPosix.hh:78
#define stat(a, b)
Definition: XrdPosix.hh:105
int emsg(int rc, char *msg)
@ kXRS_x509
Definition: XrdSutAux.hh:79
#define TRACE(act, x)
Definition: XrdTrace.hh:63
ERSAStatus status
Definition: XrdCryptoRSA.hh:58
const char * IssuerHash()
virtual XrdCryptoX509data Opaque()
const char * SubjectHash()
static bool MatchHostnames(const char *match_pattern, const char *fqdn)
EX509Type type
const char * Issuer()
XrdCryptoX509data GetExtension(const char *oid)
const char * Subject()
kXR_int64 SerialNumber()
int DumpExtensions(bool dumpunknown=0)
virtual ~XrdCryptosslX509()
XrdOucString SerialNumberString()
XrdCryptoX509data Opaque()
bool Verify(XrdCryptoX509 *ref)
XrdSutBucket * Export()
virtual bool MatchesSAN(const char *, bool &)
XrdCryptosslX509(const char *cf, const char *kf=0)
void SetPKI(XrdCryptoX509data pki)
const char * c_str() const
int rfind(const char c, int start=STR_NPOS)
int length() const
kXR_int32 size
Definition: XrdSutBucket.hh:47
int SetBuf(const char *nb=0, int ns=0)