Corrected cert parsing
[shibboleth/cpp-sp.git] / siterefresh / siterefresh.cpp
1 /*
2  * The Shibboleth License, Version 1.
3  * Copyright (c) 2002
4  * University Corporation for Advanced Internet Development, Inc.
5  * All rights reserved
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer.
13  *
14  * Redistributions in binary form must reproduce the above copyright notice,
15  * this list of conditions and the following disclaimer in the documentation
16  * and/or other materials provided with the distribution, if any, must include
17  * the following acknowledgment: "This product includes software developed by
18  * the University Corporation for Advanced Internet Development
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20  * may appear in the software itself, if and wherever such third-party
21  * acknowledgments normally appear.
22  *
23  * Neither the name of Shibboleth nor the names of its contributors, nor
24  * Internet2, nor the University Corporation for Advanced Internet Development,
25  * Inc., nor UCAID may be used to endorse or promote products derived from this
26  * software without specific prior written permission. For written permission,
27  * please contact shibboleth@shibboleth.org
28  *
29  * Products derived from this software may not be called Shibboleth, Internet2,
30  * UCAID, or the University Corporation for Advanced Internet Development, nor
31  * may Shibboleth appear in their name, without prior written permission of the
32  * University Corporation for Advanced Internet Development.
33  *
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 /* siterefresh.cpp - command-line tool to refresh and verify site metadata
51
52    Scott Cantor
53    5/12/03
54
55    $History:$
56 */
57
58 #include "../shib/shib.h"
59
60 #include <fstream>
61 #include <log4cpp/Category.hh>
62 #include <xercesc/framework/URLInputSource.hpp>
63 #include <xsec/enc/XSECCryptoProvider.hpp>
64 #include <xsec/enc/XSECKeyInfoResolverDefault.hpp>
65 #include <xsec/enc/XSECCryptoException.hpp>
66 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
67 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyRSA.hpp>
68 #include <xsec/framework/XSECProvider.hpp>
69 #include <xsec/framework/XSECException.hpp>
70 #include <xsec/dsig/DSIGTransformC14n.hpp>
71 #include <xsec/dsig/DSIGReference.hpp>
72 #include <xsec/dsig/DSIGTransformList.hpp>
73
74 #ifdef WIN32
75 # define DEFAULT_SCHEMA_DIR "/shibboleth/etc/shibboleth/"
76 #else
77 # define DEFAULT_SCHEMA_DIR "/opt/shibboleth/etc/shibboleth/"
78 #endif
79
80 using namespace std;
81 using namespace saml;
82 using namespace shibboleth;
83 using namespace log4cpp;
84
85 void verifySignature(DOMDocument* doc, DOMElement* sigNode, const char* cert)
86 {
87     Category& log=Category::getInstance("siterefresh");
88
89     // Load the certificate, stripping the first and last lines.
90     string certbuf,line;
91     auto_ptr<OpenSSLCryptoX509> x509(new OpenSSLCryptoX509());
92     ifstream infile(cert);
93     while (!getline(infile,line).fail())
94         if (line.find("CERTIFICATE")==string::npos)
95             certbuf+=line + '\n';
96     x509->loadX509Base64Bin(certbuf.data(),certbuf.length());
97
98     // Load the signature.
99     XSECProvider prov;
100     DSIGSignature* sig=NULL;
101     try
102     {
103         sig=prov.newSignatureFromDOM(doc,sigNode);
104         sig->load();
105
106         bool valid=false;
107
108         // Verify the signature coverage.
109         DSIGReferenceList* refs=sig->getReferenceList();
110         if (sig->getSignatureMethod()==SIGNATURE_RSA && refs && refs->getSize()==1)
111         {
112             DSIGReference* ref=refs->item(0);
113             if (ref)
114             {
115                 const XMLCh* URI=ref->getURI();
116                 if (URI==NULL || *URI==0)
117                 {
118                     DSIGTransformList* tlist=ref->getTransforms();
119                     for (int i=0; tlist && i<tlist->getSize(); i++)
120                     {
121                         if (tlist->item(i)->getTransformType()==TRANSFORM_ENVELOPED_SIGNATURE)
122                             valid=true;
123                         else if (tlist->item(i)->getTransformType()!=TRANSFORM_EXC_C14N)
124                         {
125                             valid=false;
126                             break;
127                         }
128                     }
129                 }
130             }
131         }
132     
133         if (!valid)
134         {
135             log.error("detected an invalid signature profile");
136             throw InvalidCryptoException("detected an invalid signature profile");
137         }
138
139         sig->setSigningKey(x509->clonePublicKey());
140         if (!sig->verify())
141         {
142             log.error("detected an invalid signature value");
143             throw InvalidCryptoException("detected an invalid signature value");
144         }
145
146         prov.releaseSignature(sig);
147     }
148     catch(...)
149     {
150         if (sig)
151             prov.releaseSignature(sig);
152         throw;
153     }
154 }
155
156 int main(int argc,char* argv[])
157 {
158     int ret=0;
159     SAMLConfig& conf=SAMLConfig::getConfig();
160     char* url_param=NULL;
161     char* cert_param=NULL;
162     char* out_param=NULL;
163     char* path=DEFAULT_SCHEMA_DIR;
164
165     for (int i=1; i<argc; i++)
166     {
167         if (!strcmp(argv[i],"--schema") && i+1<argc)
168             path=argv[++i];
169         else if (!strcmp(argv[i],"--url") && i+1<argc)
170             url_param=argv[++i];
171         else if (!strcmp(argv[i],"--cert") && i+1<argc)
172             cert_param=argv[++i];
173         else if (!strcmp(argv[i],"--out") && i+1<argc)
174             out_param=argv[++i];
175     }
176
177     if (!url_param || !out_param)
178     {
179         cout << "usage: " << argv[0] << " --url <URL of metadata> --out <pathname to copy data into> [--cert <PEM Certificate> --schema <schema path>]" << endl;
180         exit(0);
181     }
182
183     Category::setRootPriority(Priority::ERROR);
184     conf.schema_dir=path;
185     if (!conf.init())
186         return -10;
187
188     Category& log=Category::getInstance("siterefresh");
189     saml::XML::registerSchema(shibboleth::XML::SHIB_NS,shibboleth::XML::SHIB_SCHEMA_ID);
190
191     try
192     {
193         // Parse the specified document.
194         saml::XML::Parser p;
195         static XMLCh base[]={chLatin_f, chLatin_i, chLatin_l, chLatin_e, chColon, chForwardSlash, chForwardSlash, chForwardSlash, chNull};
196         URLInputSource src(base,url_param);
197         Wrapper4InputSource dsrc(&src,false);
198         DOMDocument* doc=p.parse(dsrc);
199
200         // Examine the root element to be sure we know what we have.
201                 DOMElement* e=doc->getDocumentElement();
202         if (XMLString::compareString(shibboleth::XML::SHIB_NS,e->getNamespaceURI()) ||
203             XMLString::compareString(shibboleth::XML::Literals::Sites,e->getLocalName()))
204         {
205             doc->release();
206                         log.error("requires a valid site file: (shib:Sites as root element)");
207                         throw OriginSiteMapperException("Construction requires a valid site file: (shib:Sites as root element)");
208                 }
209
210         // If we're verifying, grab the embedded signature.
211         if (cert_param)
212         {
213             DOMNode* n=e->getLastChild();
214             while (n && n->getNodeType()!=DOMNode::ELEMENT_NODE)
215                 n=n->getPreviousSibling();
216             if (n && !XMLString::compareString(saml::XML::XMLSIG_NS,n->getNamespaceURI()) &&
217                 !XMLString::compareString(L(Signature),n->getLocalName()))
218             {
219                 verifySignature(doc,static_cast<DOMElement*>(n),cert_param);
220             }
221             else
222             {
223                 doc->release();
224                             log.error("unable to locate a signature to verify in document");
225                             throw OriginSiteMapperException("Verification implies that the document must be signed");
226             }
227         }
228
229         // Output the data to the specified file.
230         ofstream outfile(out_param);
231         outfile << *e;
232         
233         doc->release();
234     }
235     catch (OriginSiteMapperException&)
236     {
237         ret=-1;
238     }
239     catch(SAMLException& e)
240     {
241         log.errorStream() << "caught a SAML exception: " << e << CategoryStream::ENDLINE;
242         ret=-2;
243     }
244     catch(XMLException& e)
245     {
246         auto_ptr<char> temp(XMLString::transcode(e.getMessage()));
247         log.errorStream() << "caught an XML exception: " << temp.get() << CategoryStream::ENDLINE;
248         ret=-3;
249     }
250     catch(XSECException& e)
251     {
252         auto_ptr<char> temp(XMLString::transcode(e.getMsg()));
253         log.errorStream() << "caught an XMLSec exception: " << temp.get() << CategoryStream::ENDLINE;
254     }
255     catch(XSECCryptoException& e)
256     {
257         log.errorStream() << "caught an XMLSecCrypto exception: " << e.getMsg() << CategoryStream::ENDLINE;
258     }
259     catch(...)
260     {
261         log.errorStream() << "caught an unknown exception" << CategoryStream::ENDLINE;
262         ret=-4;
263     }
264
265     conf.term();
266     return ret;
267 }