Add verify features.
[shibboleth/cpp-opensaml.git] / samlsign / samlsign.cpp
1 /*
2  *  Copyright 2001-2007 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:siterefresh.cpp 2252 2007-05-20 20:20:57Z cantor $
23 */
24
25 #if defined (_MSC_VER) || defined(__BORLANDC__)
26 # include "config_win32.h"
27 #else
28 # include "config.h"
29 #endif
30
31 #ifdef WIN32
32 # define _CRT_NONSTDC_NO_DEPRECATE 1
33 # define _CRT_SECURE_NO_DEPRECATE 1
34 #endif
35
36 #include <saml/SAMLConfig.h>
37 #include <saml/saml2/metadata/Metadata.h>
38 #include <saml/saml2/metadata/MetadataProvider.h>
39 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
40 #include <saml/signature/SignatureProfileValidator.h>
41 #include <saml/util/SAMLConstants.h>
42 #include <xmltooling/logging.h>
43 #include <xmltooling/XMLToolingConfig.h>
44 #include <xmltooling/security/SignatureTrustEngine.h>
45 #include <xmltooling/signature/Signature.h>
46 #include <xmltooling/signature/SignatureValidator.h>
47 #include <xmltooling/util/XMLHelper.h>
48
49 #include <fstream>
50 #include <xercesc/framework/LocalFileInputSource.hpp>
51 #include <xercesc/framework/URLInputSource.hpp>
52 #include <xercesc/framework/StdInInputSource.hpp>
53 #include <xercesc/framework/Wrapper4InputSource.hpp>
54
55 using namespace xmlsignature;
56 using namespace xmlconstants;
57 using namespace xmltooling::logging;
58 using namespace xmltooling;
59 using namespace samlconstants;
60 using namespace opensaml::saml2md;
61 using namespace opensaml;
62 using namespace xercesc;
63 using namespace std;
64
65 template<class T> T* buildPlugin(const char* path, PluginManager<T,string,const DOMElement*>& mgr)
66 {
67     ifstream in(path);
68     DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(in);
69     XercesJanitor<DOMDocument> janitor(doc);
70     
71     static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
72     auto_ptr_char type(doc->getDocumentElement()->getAttributeNS(NULL,_type));
73     if (type.get() && *type.get())
74         return mgr.newPlugin(type.get(), doc->getDocumentElement());
75     throw XMLToolingException("Missing type in plugin configuration.");
76 }
77
78 CredentialResolver* buildSimpleResolver(const char* key, const char* cert)
79 {
80     static const XMLCh _CredentialResolver[] =  UNICODE_LITERAL_18(C,r,e,d,e,n,t,i,a,l,R,e,s,o,l,v,e,r);
81     static const XMLCh _certificate[] =     UNICODE_LITERAL_11(c,e,r,t,i,f,i,c,a,t,e);
82     static const XMLCh _key[] =             UNICODE_LITERAL_3(k,e,y);
83
84     DOMDocument* doc = XMLToolingConfig::getConfig().getParser().newDocument();
85     XercesJanitor<DOMDocument> janitor(doc);
86     DOMElement* root = doc->createElementNS(NULL, _CredentialResolver);
87     if (key) {
88         auto_ptr_XMLCh widenit(key);
89         root->setAttributeNS(NULL, _key, widenit.get());
90     }
91     if (cert) {
92         auto_ptr_XMLCh widenit(cert);
93         root->setAttributeNS(NULL, _certificate, widenit.get());
94     }
95
96     return XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(FILESYSTEM_CREDENTIAL_RESOLVER, root);
97 }
98
99 class DummyCredentialResolver : public CredentialResolver
100 {
101 public:
102     DummyCredentialResolver() {}
103     ~DummyCredentialResolver() {}
104     
105     Lockable* lock() {return this;}
106     void unlock() {}
107     
108     const Credential* resolve(const CredentialCriteria* criteria=NULL) const {return NULL;}
109     vector<const Credential*>::size_type resolve(
110         vector<const Credential*>& results, const CredentialCriteria* criteria=NULL
111         ) const {return 0;}
112 };
113
114 int main(int argc,char* argv[])
115 {
116     bool verify=true;
117     char* url_param=NULL;
118     char* path_param=NULL;
119     char* key_param=NULL;
120     char* cert_param=NULL;
121     char* cr_param=NULL;
122     char* t_param=NULL;
123     char* id_param=NULL;
124
125     // metadata lookup options
126     char* m_param=NULL;
127     char* issuer=NULL;
128     char* prot = NULL;
129     const XMLCh* protocol = NULL;
130     char* rname = NULL;
131     char* rns = NULL;
132
133     for (int i=1; i<argc; i++) {
134         if (!strcmp(argv[i],"-u") && i+1<argc)
135             url_param=argv[++i];
136         else if (!strcmp(argv[i],"-f") && i+1<argc)
137             path_param=argv[++i];
138         else if (!strcmp(argv[i],"-id") && i+1<argc)
139             id_param=argv[++i];
140         else if (!strcmp(argv[i],"-s"))
141             verify=false;
142         else if (!strcmp(argv[i],"-k") && i+1<argc)
143             key_param=argv[++i];
144         else if (!strcmp(argv[i],"-c") && i+1<argc)
145             cert_param=argv[++i];
146         else if (!strcmp(argv[i],"-R") && i+1<argc)
147             cr_param=argv[++i];
148         else if (!strcmp(argv[i],"-T") && i+1<argc)
149             t_param=argv[++i];
150         else if (!strcmp(argv[i],"-M") && i+1<argc)
151             m_param=argv[++i];
152         else if (!strcmp(argv[i],"-i") && i+1<argc)
153             issuer=argv[++i];
154         else if (!strcmp(argv[i],"-p") && i+1<argc)
155             prot=argv[++i];
156         else if (!strcmp(argv[i],"-r") && i+1<argc)
157             rname=argv[++i];
158         else if (!strcmp(argv[i],"-ns") && i+1<argc)
159             rns=argv[++i];
160         else if (!strcmp(argv[i],"-saml10"))
161             protocol=samlconstants::SAML10_PROTOCOL_ENUM;
162         else if (!strcmp(argv[i],"-saml11"))
163             protocol=samlconstants::SAML11_PROTOCOL_ENUM;
164         else if (!strcmp(argv[i],"-saml2"))
165             protocol=samlconstants::SAML20P_NS;
166         else if (!strcmp(argv[i],"-idp"))
167             rname="IDPSSODescriptor";
168         else if (!strcmp(argv[i],"-aa"))
169             rname="AttributeAuthorityDescriptor";
170         else if (!strcmp(argv[i],"-pdp"))
171             rname="PDPDescriptor";
172         else if (!strcmp(argv[i],"-sp"))
173             rname="SPSSODescriptor";
174     }
175
176     if (verify && !cert_param && !cr_param && !t_param) {
177         cerr << "either -c or -R or -T option required when verifiying, see documentation for usage" << endl;
178         return -1;
179     }
180     else if (!verify && !key_param && !cr_param) {
181         cerr << "either -k or -R option required when signing, see documentation for usage" << endl;
182         return -1;
183     }
184
185     SAMLConfig& conf=SAMLConfig::getConfig();
186     if (!conf.init())
187         return -2;
188     XMLToolingConfig& xmlconf = XMLToolingConfig::getConfig();
189     Category& log = Category::getInstance("OpenSAML.Utility.SAMLSign");
190
191     int ret = 0;
192
193     try {
194         // Parse the specified document.
195         static XMLCh base[]={chLatin_f, chLatin_i, chLatin_l, chLatin_e, chColon, chForwardSlash, chForwardSlash, chForwardSlash, chNull};
196         DOMDocument* doc=NULL;
197         if (url_param) {
198             URLInputSource src(base,url_param);
199             Wrapper4InputSource dsrc(&src,false);
200             doc=xmlconf.getParser().parse(dsrc);
201         }
202         else if (path_param) {
203             auto_ptr_XMLCh widenit(path_param);
204             LocalFileInputSource src(base,widenit.get());
205             Wrapper4InputSource dsrc(&src,false);
206             doc=xmlconf.getParser().parse(dsrc);
207         }
208         else {
209             StdInInputSource src;
210             Wrapper4InputSource dsrc(&src,false);
211             doc=xmlconf.getParser().parse(dsrc);
212         }
213     
214         // Unmarshall it.
215         XercesJanitor<DOMDocument> jan(doc);
216         auto_ptr<XMLObject> sourcewrapper(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
217         jan.release();
218
219         // Navigate to the selected node, or use the root if no ID specified.
220         // Then make sure it's a SignableSAMLObject.
221         XMLObject* source = sourcewrapper.get();
222         if (id_param) {
223             auto_ptr_XMLCh widenit(id_param);
224             source = XMLHelper::getXMLObjectById(*source, widenit.get());
225             if (!source)
226                 throw XMLToolingException("Element with ID ($1) not found.", params(1,id_param));
227         }
228         SignableObject* signable = dynamic_cast<SignableObject*>(source);
229         if (!signable)
230             throw XMLToolingException("Input is not a signable SAML object.");
231
232         if (verify) {
233             if (!signable->getSignature())
234                 throw SignatureException("Cannot verify unsigned object.");
235
236             // Check the profile.
237             SignatureProfileValidator sigval;
238             sigval.validate(signable->getSignature());
239
240             if (cert_param || cr_param) {
241                 // Build a resolver to supply trusted credentials.
242                 auto_ptr<CredentialResolver> cr(
243                     cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(NULL, cert_param)
244                     );
245                 Locker locker(cr.get());
246
247                 // Set up criteria.
248                 CredentialCriteria cc;
249                 cc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
250                 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
251                 if (issuer)
252                     cc.setPeerName(issuer);
253
254                 // Try every credential we can find.
255                 vector<const Credential*> creds;
256                 if (cr->resolve(creds, &cc)) {
257                     bool good=false;
258                     SignatureValidator sigValidator;
259                     for (vector<const Credential*>::const_iterator i = creds.begin(); i != creds.end(); ++i) {
260                         try {
261                             sigValidator.setCredential(*i);
262                             sigValidator.validate(signable->getSignature());
263                             log.info("successful signature verification");
264                             good = true;
265                             break;
266                         }
267                         catch (exception&) {
268                         }
269                     }
270                     if (!good)
271                         throw SignatureException("CredentialResolver did not supply a successful verification key.");
272                 }
273                 else {
274                     throw SignatureException("CredentialResolver did not supply any verification keys.");
275                 }
276             }
277             else {
278                 // TrustEngine-based verification, so try and build the plugins.
279                 auto_ptr<TrustEngine> trust(buildPlugin(t_param, xmlconf.TrustEngineManager));
280                 SignatureTrustEngine* sigtrust = dynamic_cast<SignatureTrustEngine*>(trust.get());
281                 if (m_param && rname && issuer) {
282                     if (!protocol) {\r
283                         if (prot)\r
284                             protocol = XMLString::transcode(prot);\r
285                     }\r
286                     if (!protocol) {\r
287                         conf.term();\r
288                         cerr << "use of metadata option requires a protocol option" << endl;\r
289                         return -1;\r
290                     }\r
291                     auto_ptr<MetadataProvider> metadata(buildPlugin(m_param, conf.MetadataProviderManager));
292                     metadata->init();
293                     
294                     Locker locker(metadata.get());
295                     const EntityDescriptor* entity = metadata->getEntityDescriptor(issuer);\r
296                     if (!entity)\r
297                         throw MetadataException("no metadata found for ($1)", params(1, issuer));\r
298                     const XMLCh* ns = rns ? XMLString::transcode(rns) : samlconstants::SAML20MD_NS;\r
299                     auto_ptr_XMLCh n(rname);\r
300                     QName q(ns, n.get());\r
301                     const RoleDescriptor* role = entity->getRoleDescriptor(q, protocol);\r
302                     if (!role)\r
303                         throw MetadataException("compatible role $1 not found for ($2)", params(2, q.toString().c_str(), issuer));\r
304 \r
305                     MetadataCredentialCriteria mcc(*role);\r
306                     if (sigtrust->validate(*signable->getSignature(), *metadata.get(), &mcc))\r
307                         log.info("successful signature verification");
308                     else\r
309                         throw SignatureException("Unable to verify signature with TrustEngine and supplied metadata.");\r
310                 }
311                 else {
312                     // Set up criteria.
313                     CredentialCriteria cc;
314                     cc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
315                     cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
316                     if (issuer)
317                         cc.setPeerName(issuer);
318                     DummyCredentialResolver dummy;
319                     if (sigtrust->validate(*signable->getSignature(), dummy, &cc))\r
320                         log.info("successful signature verification");
321                     else\r
322                         throw SignatureException("Unable to verify signature with TrustEngine (no metadata supplied).");\r
323                 }
324             }
325         }
326         else {
327             // Build a resolver to supply a credential.
328             auto_ptr<CredentialResolver> cr(
329                 cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(key_param, cert_param)
330                 );
331             Locker locker(cr.get());
332             CredentialCriteria cc;
333             cc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
334             const Credential* cred = cr->resolve(&cc);
335             if (!cred)
336                 throw XMLSecurityException("Unable to resolve a signing credential.");
337
338             // Attach new signature.
339             Signature* sig = SignatureBuilder::buildSignature();
340             signable->setSignature(sig);
341
342             // Sign response while re-marshalling.
343             vector<Signature*> sigs(1,sig);
344             XMLHelper::serialize(signable->marshall((DOMDocument*)NULL,&sigs,cred), cout);
345         }
346     }
347     catch(exception& e) {
348         log.errorStream() << "caught an exception: " << e.what() << CategoryStream::ENDLINE;
349         ret=-10;
350     }
351     catch(XMLException& e) {
352         auto_ptr_char temp(e.getMessage());
353         log.errorStream() << "caught a Xerces exception: " << temp.get() << CategoryStream::ENDLINE;
354         ret=-20;
355     }
356
357     conf.term();
358     return ret;
359 }