More lib migration, purged old thread/error template code.
[shibboleth/cpp-sp.git] / siterefresh / siterefresh.cpp
1 /*
2  *  Copyright 2001-2005 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /* siterefresh.cpp - command-line tool to refresh and verify metadata
18
19    Scott Cantor
20    5/12/03
21
22    $Id$
23 */
24
25 #include <saml/SAMLConfig.h>
26 #include <saml/saml2/metadata/Metadata.h>
27 #include <saml/util/SAMLConstants.h>
28 #include <xmltooling/XMLToolingConfig.h>
29 #include <xmltooling/signature/Signature.h>
30 #include <xmltooling/util/XMLHelper.h>
31
32 #include <fstream>
33 #include <log4cpp/Category.hh>
34 #include <log4cpp/OstreamAppender.hh>
35 #include <xercesc/framework/URLInputSource.hpp>
36 #include <xercesc/framework/StdInInputSource.hpp>
37 #include <xercesc/framework/Wrapper4InputSource.hpp>
38 #include <xsec/enc/XSECCryptoProvider.hpp>
39 #include <xsec/enc/XSECKeyInfoResolverDefault.hpp>
40 #include <xsec/enc/XSECCryptoException.hpp>
41 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
42 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyRSA.hpp>
43 #include <xsec/framework/XSECProvider.hpp>
44 #include <xsec/framework/XSECException.hpp>
45 #include <xsec/dsig/DSIGTransformC14n.hpp>
46 #include <xsec/dsig/DSIGReference.hpp>
47 #include <xsec/dsig/DSIGTransformList.hpp>
48
49 using namespace xmlsignature;
50 using namespace xmlconstants;
51 using namespace xmltooling;
52 using namespace samlconstants;
53 using namespace opensaml::saml2md;
54 using namespace opensaml;
55 using namespace log4cpp;
56 using namespace std;
57
58 void verifySignature(DOMDocument* doc, DOMNode* sigNode, const char* cert=NULL)
59 {
60     Category& log=Category::getInstance("siterefresh");
61     static const XMLCh ID[]={chLatin_I, chLatin_D, chNull};
62
63     // Load the signature.
64     XSECProvider prov;
65     DSIGSignature* sig=NULL;
66     try {
67         sig=prov.newSignatureFromDOM(doc,sigNode);
68         sig->load();
69
70         bool valid=false;
71
72         // Verify the signature coverage.
73         DSIGReferenceList* refs=sig->getReferenceList();
74         if (sig->getSignatureMethod()==SIGNATURE_RSA && refs && refs->getSize()==1) {
75             DSIGReference* ref=refs->item(0);
76             if (ref) {
77                 const XMLCh* URI=ref->getURI();
78                 if (!URI || !*URI || (*URI==chPound &&
79                         !XMLString::compareString(&URI[1],static_cast<DOMElement*>(sigNode->getParentNode())->getAttributeNS(NULL,ID)))) {
80                     DSIGTransformList* tlist=ref->getTransforms();
81                     for (unsigned int i=0; tlist && i<tlist->getSize(); i++) {
82                         if (tlist->item(i)->getTransformType()==TRANSFORM_ENVELOPED_SIGNATURE)
83                             valid=true;
84                         else if (tlist->item(i)->getTransformType()!=TRANSFORM_EXC_C14N) {
85                             valid=false;
86                             break;
87                         }
88                     }
89                 }
90             }
91         }
92     
93         if (!valid) {
94             log.error("detected an invalid signature profile");
95             throw SignatureException("detected an invalid signature profile");
96         }
97
98         if (cert) {
99             // Load the certificate, stripping the header and trailer.
100             string certbuf,line;
101             auto_ptr<OpenSSLCryptoX509> x509(new OpenSSLCryptoX509());
102             bool sawheader=false;
103             ifstream infile(cert);
104             while (!getline(infile,line).fail()) {
105                 if (line.find("CERTIFICATE-----")==string::npos) {
106                     if (sawheader)
107                         certbuf+=line + '\n';
108                 }
109                 else
110                     sawheader=true;
111             }
112             x509->loadX509Base64Bin(certbuf.data(),certbuf.length());
113             sig->setSigningKey(x509->clonePublicKey());
114         }
115         else {
116             log.warn("verifying with key inside signature, this is a sanity check but provides no security");
117             XSECKeyInfoResolverDefault resolver;
118             sig->setKeyInfoResolver(resolver.clone());
119         }
120         
121         if (!sig->verify()) {
122             log.error("detected an invalid signature value");
123             throw SignatureException("detected an invalid signature value");
124         }
125
126         prov.releaseSignature(sig);
127     }
128     catch(...) {
129         if (sig)
130             prov.releaseSignature(sig);
131         throw;
132     }
133 }
134
135 int main(int argc,char* argv[])
136 {
137     int ret=0;
138     SAMLConfig& conf=SAMLConfig::getConfig();
139     bool verify=true;
140     char* url_param=NULL;
141     char* cert_param=NULL;
142     char* out_param=NULL;
143     char* path=getenv("SHIBSCHEMAS");
144     char* ns_param=NULL;
145     char* name_param=NULL;
146
147     for (int i=1; i<argc; i++) {
148         if (!strcmp(argv[i],"--schema") && i+1<argc)
149             path=argv[++i];
150         else if (!strcmp(argv[i],"--url") && i+1<argc)
151             url_param=argv[++i];
152         else if (!strcmp(argv[i],"--noverify"))
153             verify=false;
154         else if (!strcmp(argv[i],"--cert") && i+1<argc)
155             cert_param=argv[++i];
156         else if (!strcmp(argv[i],"--out") && i+1<argc)
157             out_param=argv[++i];
158         else if (!strcmp(argv[i],"--rootns") && i+1<argc)
159             ns_param=argv[++i];
160         else if (!strcmp(argv[i],"--rootname") && i+1<argc)
161             name_param=argv[++i];
162     }
163
164     if (verify && !cert_param) {
165         cout << "usage: " << argv[0] << endl <<
166             "\t--url <URL of metadata>" << endl <<
167             "\t--noverify OR --cert <PEM Certificate>" << endl <<
168             "\t[--out <pathname to copy data to>]" << endl <<
169             "\t[--schema <schema path>]" << endl <<
170             "\t[--rootns <root element XML namespace>]" << endl <<
171             "\t[--rootname <root element name>]" << endl;
172         return -100;
173     }
174
175     Category::setRootPriority(Priority::WARN);
176     Category::getRoot().addAppender(new OstreamAppender("default",&cerr));
177     Category& log=Category::getInstance("siterefresh");
178     if (!conf.init())
179         return -10;
180
181     /*
182     saml::XML::registerSchema(shibtarget::XML::SAML2META_NS,shibtarget::XML::SAML2META_SCHEMA_ID);
183     saml::XML::registerSchema(shibtarget::XML::SAML2ASSERT_NS,shibtarget::XML::SAML2ASSERT_SCHEMA_ID);
184     saml::XML::registerSchema(shibtarget::XML::XMLENC_NS,shibtarget::XML::XMLENC_SCHEMA_ID);
185     */
186
187     try {
188         // Parse the specified document.
189         static XMLCh base[]={chLatin_f, chLatin_i, chLatin_l, chLatin_e, chColon, chForwardSlash, chForwardSlash, chForwardSlash, chNull};
190         DOMDocument* doc=NULL;
191         if (url_param && *url_param) {
192             URLInputSource src(base,url_param);
193             Wrapper4InputSource dsrc(&src,false);
194             doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
195         }
196         else {
197             StdInInputSource src;
198             Wrapper4InputSource dsrc(&src,false);
199             doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
200         }
201     
202         // Check root element.
203         if (ns_param && name_param) {
204             auto_ptr_XMLCh ns(ns_param);
205             auto_ptr_XMLCh name(name_param);
206             if (!XMLHelper::isNodeNamed(doc->getDocumentElement(),ns.get(),name.get()))
207                 throw XMLObjectException(string("Root element does not match specified QName of {") + ns_param + "}:" + name_param);
208         }
209         else if (!XMLHelper::isNodeNamed(doc->getDocumentElement(),SAML20MD_NS,EntitiesDescriptor::LOCAL_NAME) &&
210                  !XMLHelper::isNodeNamed(doc->getDocumentElement(),SAML20MD_NS,EntityDescriptor::LOCAL_NAME))
211             throw XMLObjectException("Root element does not signify a known metadata format");
212
213         // Verify the "root" signature.
214         DOMElement* rootSig=XMLHelper::getFirstChildElement(doc->getDocumentElement(),XMLSIG_NS,Signature::LOCAL_NAME);
215         if (verify) {
216             if (rootSig) {
217                 verifySignature(doc,rootSig,cert_param);
218             }
219             else {
220                 doc->release();
221                 log.error("unable to locate root signature to verify in document");
222                 throw SignatureException("Verification implies that the document must be signed");
223             }
224         }
225         else if (rootSig) {
226             log.warn("verification of signer disabled, make sure you trust the source of this file!");
227             verifySignature(doc,rootSig,cert_param);
228         }
229         else {
230             log.warn("verification disabled, and file is unsigned!");
231         }
232
233         // Verify all signatures.
234         DOMNodeList* siglist=doc->getElementsByTagNameNS(XMLSIG_NS,Signature::LOCAL_NAME);
235         for (unsigned int i=0; siglist && i<siglist->getLength(); i++)
236             verifySignature(doc,siglist->item(i),cert_param);
237
238         if (out_param) {
239             // Output the data to the specified file.
240             ofstream outfile(out_param);
241             outfile << *(doc->getDocumentElement());
242         }
243         else
244             cout << *(doc->getDocumentElement());
245         doc->release();
246     }
247     catch (SignatureException&) {
248         ret=-1;
249     }
250     catch(XMLToolingException& e) {
251         log.errorStream() << "caught an XMLTooling exception: " << e.what() << CategoryStream::ENDLINE;
252         ret=-2;
253     }
254     catch(XMLException& e) {
255         auto_ptr_char temp(e.getMessage());
256         log.errorStream() << "caught an XML exception: " << temp.get() << CategoryStream::ENDLINE;
257         ret=-3;
258     }
259     catch(XSECException& e) {
260         auto_ptr_char temp(e.getMsg());
261         log.errorStream() << "caught an XMLSec exception: " << temp.get() << CategoryStream::ENDLINE;
262         ret=-4;
263     }
264     catch(XSECCryptoException& e) {
265         log.errorStream() << "caught an XMLSecCrypto exception: " << e.getMsg() << CategoryStream::ENDLINE;
266         ret=-5;
267     }
268     catch(...) {
269         log.errorStream() << "caught an unknown exception" << CategoryStream::ENDLINE;
270         ret=-6;
271     }
272
273     conf.term();
274     return ret;
275 }