Set fourth file version digit to signify rebuild.
[shibboleth/cpp-opensaml.git] / samlsign / samlsign.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * samlsign.cpp
23  *
24  * Command-line tool to sign and verify objects.
25  */
26
27 #if defined (_MSC_VER) || defined(__BORLANDC__)
28 # include "config_win32.h"
29 #else
30 # include "config.h"
31 #endif
32
33 #ifdef WIN32
34 # define _CRT_NONSTDC_NO_DEPRECATE 1
35 # define _CRT_SECURE_NO_DEPRECATE 1
36 #endif
37
38 #include <saml/SAMLConfig.h>
39 #include <saml/saml2/metadata/Metadata.h>
40 #include <saml/saml2/metadata/MetadataProvider.h>
41 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
42 #include <saml/signature/ContentReference.h>
43 #include <saml/signature/SignatureProfileValidator.h>
44 #include <saml/util/SAMLConstants.h>
45 #include <xmltooling/logging.h>
46 #include <xmltooling/XMLToolingConfig.h>
47 #include <xmltooling/security/Credential.h>
48 #include <xmltooling/security/SignatureTrustEngine.h>
49 #include <xmltooling/signature/Signature.h>
50 #include <xmltooling/signature/SignatureValidator.h>
51 #include <xmltooling/util/ParserPool.h>
52 #include <xmltooling/util/XMLHelper.h>
53
54 #include <fstream>
55 #include <xercesc/framework/LocalFileInputSource.hpp>
56 #include <xercesc/framework/StdInInputSource.hpp>
57 #include <xercesc/framework/Wrapper4InputSource.hpp>
58
59 using namespace xmlsignature;
60 using namespace xmlconstants;
61 using namespace xmltooling::logging;
62 using namespace xmltooling;
63 using namespace samlconstants;
64 using namespace opensaml::saml2md;
65 using namespace opensaml;
66 using namespace xercesc;
67 using namespace std;
68
69 template<class T> T* buildPlugin(const char* path, PluginManager<T,string,const DOMElement*>& mgr)
70 {
71     ifstream in(path);
72     DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(in);
73     XercesJanitor<DOMDocument> janitor(doc);
74
75     static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
76     auto_ptr_char type(doc->getDocumentElement()->getAttributeNS(nullptr,_type));
77     if (type.get() && *type.get())
78         return mgr.newPlugin(type.get(), doc->getDocumentElement());
79     throw XMLToolingException("Missing type in plugin configuration.");
80 }
81
82 CredentialResolver* buildSimpleResolver(const char* key, const char* cert)
83 {
84     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);
85     static const XMLCh _certificate[] =     UNICODE_LITERAL_11(c,e,r,t,i,f,i,c,a,t,e);
86     static const XMLCh _key[] =             UNICODE_LITERAL_3(k,e,y);
87
88     DOMDocument* doc = XMLToolingConfig::getConfig().getParser().newDocument();
89     XercesJanitor<DOMDocument> janitor(doc);
90     DOMElement* root = doc->createElementNS(nullptr, _CredentialResolver);
91     if (key) {
92         auto_ptr_XMLCh widenit(key);
93         root->setAttributeNS(nullptr, _key, widenit.get());
94     }
95     if (cert) {
96         auto_ptr_XMLCh widenit(cert);
97         root->setAttributeNS(nullptr, _certificate, widenit.get());
98     }
99
100     return XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(FILESYSTEM_CREDENTIAL_RESOLVER, root);
101 }
102
103 class DummyCredentialResolver : public CredentialResolver
104 {
105 public:
106     DummyCredentialResolver() {}
107     ~DummyCredentialResolver() {}
108
109     Lockable* lock() {return this;}
110     void unlock() {}
111
112     const Credential* resolve(const CredentialCriteria* criteria=nullptr) const {return nullptr;}
113     vector<const Credential*>::size_type resolve(
114         vector<const Credential*>& results, const CredentialCriteria* criteria=nullptr
115         ) const {return 0;}
116 };
117
118 int main(int argc,char* argv[])
119 {
120     bool verify=true,validate=false;
121     char* url_param=nullptr;
122     char* path_param=nullptr;
123     char* key_param=nullptr;
124     char* cert_param=nullptr;
125     char* cr_param=nullptr;
126     char* t_param=nullptr;
127     char* id_param=nullptr;
128     char* alg_param=nullptr;
129     char* dig_param=nullptr;
130
131     // metadata lookup options
132     char* m_param=nullptr;
133     char* issuer=nullptr;
134     char* prot = nullptr;
135     const XMLCh* protocol = nullptr;
136     const char* rname = nullptr;
137     char* rns = nullptr;
138
139     for (int i=1; i<argc; i++) {
140         if (!strcmp(argv[i],"-u") && i+1<argc)
141             url_param=argv[++i];
142         else if (!strcmp(argv[i],"-f") && i+1<argc)
143             path_param=argv[++i];
144         else if (!strcmp(argv[i],"-id") && i+1<argc)
145             id_param=argv[++i];
146         else if (!strcmp(argv[i],"-s"))
147             verify=false;
148         else if (!strcmp(argv[i],"-k") && i+1<argc)
149             key_param=argv[++i];
150         else if (!strcmp(argv[i],"-c") && i+1<argc)
151             cert_param=argv[++i];
152         else if (!strcmp(argv[i],"-R") && i+1<argc)
153             cr_param=argv[++i];
154         else if (!strcmp(argv[i],"-T") && i+1<argc)
155             t_param=argv[++i];
156         else if (!strcmp(argv[i],"-M") && i+1<argc)
157             m_param=argv[++i];
158         else if (!strcmp(argv[i],"-i") && i+1<argc)
159             issuer=argv[++i];
160         else if (!strcmp(argv[i],"-p") && i+1<argc)
161             prot=argv[++i];
162         else if (!strcmp(argv[i],"-r") && i+1<argc)
163             rname=argv[++i];
164         else if (!strcmp(argv[i],"-V"))
165             validate = true;
166         else if (!strcmp(argv[i],"-ns") && i+1<argc)
167             rns=argv[++i];
168         else if (!strcmp(argv[i],"-alg") && i+1<argc)
169             alg_param=argv[++i];
170         else if (!strcmp(argv[i],"-dig") && i+1<argc)
171             dig_param=argv[++i];
172         else if (!strcmp(argv[i],"-saml10"))
173             protocol=samlconstants::SAML10_PROTOCOL_ENUM;
174         else if (!strcmp(argv[i],"-saml11"))
175             protocol=samlconstants::SAML11_PROTOCOL_ENUM;
176         else if (!strcmp(argv[i],"-saml2"))
177             protocol=samlconstants::SAML20P_NS;
178         else if (!strcmp(argv[i],"-idp"))
179             rname="IDPSSODescriptor";
180         else if (!strcmp(argv[i],"-aa"))
181             rname="AttributeAuthorityDescriptor";
182         else if (!strcmp(argv[i],"-pdp"))
183             rname="PDPDescriptor";
184         else if (!strcmp(argv[i],"-sp"))
185             rname="SPSSODescriptor";
186     }
187
188     if (verify && !cert_param && !cr_param && !t_param) {
189         cerr << "either -c or -R or -T option required when verifiying, see documentation for usage" << endl;
190         return -1;
191     }
192     else if (!verify && !key_param && !cr_param) {
193         cerr << "either -k or -R option required when signing, see documentation for usage" << endl;
194         return -1;
195     }
196
197     XMLToolingConfig& xmlconf = XMLToolingConfig::getConfig();
198     xmlconf.log_config(getenv("OPENSAML_LOG_CONFIG"));
199     if (getenv("OPENSAML_SCHEMAS"))
200         xmlconf.catalog_path = getenv("OPENSAML_SCHEMAS");
201     SAMLConfig& conf=SAMLConfig::getConfig();
202     if (!conf.init())
203         return -2;
204     Category& log = Category::getInstance("OpenSAML.Utility.SAMLSign");
205
206     int ret = 0;
207
208     try {
209         // Parse the specified document.
210         DOMDocument* doc=nullptr;
211         if (url_param) {
212             auto_ptr_XMLCh wideurl(url_param);
213             URLInputSource src(wideurl.get());
214             Wrapper4InputSource dsrc(&src,false);
215             if (validate)
216                 doc = xmlconf.getValidatingParser().parse(dsrc);
217             else
218                 doc = xmlconf.getParser().parse(dsrc);
219         }
220         else if (path_param) {
221             auto_ptr_XMLCh widenit(path_param);
222             LocalFileInputSource src(widenit.get());
223             Wrapper4InputSource dsrc(&src,false);
224             if (validate)
225                 doc = xmlconf.getValidatingParser().parse(dsrc);
226             else
227                 doc = xmlconf.getParser().parse(dsrc);
228         }
229         else {
230             StdInInputSource src;
231             Wrapper4InputSource dsrc(&src,false);
232             if (validate)
233                 doc = xmlconf.getValidatingParser().parse(dsrc);
234             else
235                 doc = xmlconf.getParser().parse(dsrc);
236         }
237
238         // Unmarshall it.
239         XercesJanitor<DOMDocument> jan(doc);
240         auto_ptr<XMLObject> sourcewrapper(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
241         jan.release();
242
243         // Navigate to the selected node, or use the root if no ID specified.
244         // Then make sure it's a SignableSAMLObject.
245         XMLObject* source = sourcewrapper.get();
246         if (id_param) {
247             auto_ptr_XMLCh widenit(id_param);
248             source = XMLHelper::getXMLObjectById(*source, widenit.get());
249             if (!source)
250                 throw XMLToolingException("Element with ID ($1) not found.", params(1,id_param));
251         }
252         SignableObject* signable = dynamic_cast<SignableObject*>(source);
253         if (!signable)
254             throw XMLToolingException("Input is not a signable SAML object.");
255
256         if (verify) {
257             if (!signable->getSignature())
258                 throw SignatureException("Cannot verify unsigned object.");
259
260             // Check the profile.
261             SignatureProfileValidator sigval;
262             sigval.validate(signable->getSignature());
263
264             if (cert_param || cr_param) {
265                 // Build a resolver to supply trusted credentials.
266                 auto_ptr<CredentialResolver> cr(
267                     cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(nullptr, cert_param)
268                     );
269                 Locker locker(cr.get());
270
271                 // Set up criteria.
272                 CredentialCriteria cc;
273                 cc.setUsage(Credential::SIGNING_CREDENTIAL);
274                 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
275                 if (issuer)
276                     cc.setPeerName(issuer);
277
278                 // Try every credential we can find.
279                 vector<const Credential*> creds;
280                 if (cr->resolve(creds, &cc)) {
281                     bool good=false;
282                     SignatureValidator sigValidator;
283                     for (vector<const Credential*>::const_iterator i = creds.begin(); i != creds.end(); ++i) {
284                         try {
285                             sigValidator.setCredential(*i);
286                             sigValidator.validate(signable->getSignature());
287                             log.info("successful signature verification");
288                             good = true;
289                             break;
290                         }
291                         catch (exception& e) {
292                             log.info("error trying verification key: %s", e.what());
293                         }
294                     }
295                     if (!good)
296                         throw SignatureException("CredentialResolver did not supply a successful verification key.");
297                 }
298                 else {
299                     throw SignatureException("CredentialResolver did not supply any verification keys.");
300                 }
301             }
302             else {
303                 // TrustEngine-based verification, so try and build the plugins.
304                 auto_ptr<TrustEngine> trust(buildPlugin(t_param, xmlconf.TrustEngineManager));
305                 SignatureTrustEngine* sigtrust = dynamic_cast<SignatureTrustEngine*>(trust.get());
306                 if (m_param && rname && issuer) {
307                     if (!protocol) {
308                         if (prot)
309                             protocol = XMLString::transcode(prot);
310                     }
311                     if (!protocol) {
312                         conf.term();
313                         cerr << "use of metadata option requires a protocol option" << endl;
314                         return -1;
315                     }
316                     auto_ptr<MetadataProvider> metadata(buildPlugin(m_param, conf.MetadataProviderManager));
317                     metadata->init();
318
319                     const XMLCh* ns = rns ? XMLString::transcode(rns) : samlconstants::SAML20MD_NS;
320                     auto_ptr_XMLCh n(rname);
321                     xmltooling::QName q(ns, n.get());
322
323                     Locker locker(metadata.get());
324                     MetadataProvider::Criteria mc(issuer, &q, protocol);
325                     pair<const EntityDescriptor*,const RoleDescriptor*> entity = metadata->getEntityDescriptor(mc);
326                     if (!entity.first)
327                         throw MetadataException("no metadata found for ($1)", params(1, issuer));
328                     else if (!entity.second)
329                         throw MetadataException("compatible role $1 not found for ($2)", params(2, q.toString().c_str(), issuer));
330
331                     MetadataCredentialCriteria mcc(*entity.second);
332                     if (sigtrust->validate(*signable->getSignature(), *metadata.get(), &mcc))
333                         log.info("successful signature verification");
334                     else
335                         throw SignatureException("Unable to verify signature with TrustEngine and supplied metadata.");
336                 }
337                 else {
338                     // Set up criteria.
339                     CredentialCriteria cc;
340                     cc.setUsage(Credential::SIGNING_CREDENTIAL);
341                     cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
342                     if (issuer)
343                         cc.setPeerName(issuer);
344                     DummyCredentialResolver dummy;
345                     if (sigtrust->validate(*signable->getSignature(), dummy, &cc))
346                         log.info("successful signature verification");
347                     else
348                         throw SignatureException("Unable to verify signature with TrustEngine (no metadata supplied).");
349                 }
350             }
351         }
352         else {
353             // Build a resolver to supply a credential.
354             auto_ptr<CredentialResolver> cr(
355                 cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(key_param, cert_param)
356                 );
357             Locker locker(cr.get());
358             CredentialCriteria cc;
359             cc.setUsage(Credential::SIGNING_CREDENTIAL);
360             const Credential* cred = cr->resolve(&cc);
361             if (!cred)
362                 throw XMLSecurityException("Unable to resolve a signing credential.");
363
364             // Attach new signature.
365             Signature* sig = SignatureBuilder::buildSignature();
366             signable->setSignature(sig);
367             auto_ptr_XMLCh alg(alg_param);
368             if (alg.get()) {
369                 sig->setSignatureAlgorithm(alg.get());
370             }
371             auto_ptr_XMLCh dig(dig_param);
372             if (dig.get()) {
373                 dynamic_cast<opensaml::ContentReference*>(sig->getContentReference())->setDigestAlgorithm(dig.get());
374             }
375
376             // Sign response while re-marshalling.
377             vector<Signature*> sigs(1,sig);
378             XMLHelper::serialize(signable->marshall((DOMDocument*)nullptr,&sigs,cred), cout);
379         }
380     }
381     catch(exception& e) {
382         log.errorStream() << "caught an exception: " << e.what() << logging::eol;
383         ret=-10;
384     }
385
386     conf.term();
387     return ret;
388 }