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