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.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 * Command-line tool to sign and verify objects.
27 #if defined (_MSC_VER) || defined(__BORLANDC__)
28 # include "config_win32.h"
34 # define _CRT_NONSTDC_NO_DEPRECATE 1
35 # define _CRT_SECURE_NO_DEPRECATE 1
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>
55 #include <xercesc/framework/LocalFileInputSource.hpp>
56 #include <xercesc/framework/StdInInputSource.hpp>
57 #include <xercesc/framework/Wrapper4InputSource.hpp>
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;
69 template<class T> T* buildPlugin(const char* path, PluginManager<T,string,const DOMElement*>& mgr)
72 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(in);
73 XercesJanitor<DOMDocument> janitor(doc);
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.");
82 CredentialResolver* buildSimpleResolver(const char* key, const char* cert)
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);
88 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().newDocument();
89 XercesJanitor<DOMDocument> janitor(doc);
90 DOMElement* root = doc->createElementNS(nullptr, _CredentialResolver);
92 auto_ptr_XMLCh widenit(key);
93 root->setAttributeNS(nullptr, _key, widenit.get());
96 auto_ptr_XMLCh widenit(cert);
97 root->setAttributeNS(nullptr, _certificate, widenit.get());
100 return XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(FILESYSTEM_CREDENTIAL_RESOLVER, root);
103 class DummyCredentialResolver : public CredentialResolver
106 DummyCredentialResolver() {}
107 ~DummyCredentialResolver() {}
109 Lockable* lock() {return this;}
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
118 int main(int argc,char* argv[])
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;
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;
139 for (int i=1; i<argc; i++) {
140 if (!strcmp(argv[i],"-u") && i+1<argc)
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)
146 else if (!strcmp(argv[i],"-s"))
148 else if (!strcmp(argv[i],"-k") && i+1<argc)
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)
154 else if (!strcmp(argv[i],"-T") && i+1<argc)
156 else if (!strcmp(argv[i],"-M") && i+1<argc)
158 else if (!strcmp(argv[i],"-i") && i+1<argc)
160 else if (!strcmp(argv[i],"-p") && i+1<argc)
162 else if (!strcmp(argv[i],"-r") && i+1<argc)
164 else if (!strcmp(argv[i],"-V"))
166 else if (!strcmp(argv[i],"-ns") && i+1<argc)
168 else if (!strcmp(argv[i],"-alg") && i+1<argc)
170 else if (!strcmp(argv[i],"-dig") && i+1<argc)
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";
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;
192 else if (!verify && !key_param && !cr_param) {
193 cerr << "either -k or -R option required when signing, see documentation for usage" << endl;
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();
204 Category& log = Category::getInstance("OpenSAML.Utility.SAMLSign");
209 // Parse the specified document.
210 DOMDocument* doc=nullptr;
212 auto_ptr_XMLCh wideurl(url_param);
213 URLInputSource src(wideurl.get());
214 Wrapper4InputSource dsrc(&src,false);
216 doc = xmlconf.getValidatingParser().parse(dsrc);
218 doc = xmlconf.getParser().parse(dsrc);
220 else if (path_param) {
221 auto_ptr_XMLCh widenit(path_param);
222 LocalFileInputSource src(widenit.get());
223 Wrapper4InputSource dsrc(&src,false);
225 doc = xmlconf.getValidatingParser().parse(dsrc);
227 doc = xmlconf.getParser().parse(dsrc);
230 StdInInputSource src;
231 Wrapper4InputSource dsrc(&src,false);
233 doc = xmlconf.getValidatingParser().parse(dsrc);
235 doc = xmlconf.getParser().parse(dsrc);
239 XercesJanitor<DOMDocument> jan(doc);
240 auto_ptr<XMLObject> sourcewrapper(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
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();
247 auto_ptr_XMLCh widenit(id_param);
248 source = XMLHelper::getXMLObjectById(*source, widenit.get());
250 throw XMLToolingException("Element with ID ($1) not found.", params(1,id_param));
252 SignableObject* signable = dynamic_cast<SignableObject*>(source);
254 throw XMLToolingException("Input is not a signable SAML object.");
257 if (!signable->getSignature())
258 throw SignatureException("Cannot verify unsigned object.");
260 // Check the profile.
261 SignatureProfileValidator sigval;
262 sigval.validate(signable->getSignature());
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)
269 Locker locker(cr.get());
272 CredentialCriteria cc;
273 cc.setUsage(Credential::SIGNING_CREDENTIAL);
274 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
276 cc.setPeerName(issuer);
278 // Try every credential we can find.
279 vector<const Credential*> creds;
280 if (cr->resolve(creds, &cc)) {
282 SignatureValidator sigValidator;
283 for (vector<const Credential*>::const_iterator i = creds.begin(); i != creds.end(); ++i) {
285 sigValidator.setCredential(*i);
286 sigValidator.validate(signable->getSignature());
287 log.info("successful signature verification");
291 catch (exception& e) {
292 log.info("error trying verification key: %s", e.what());
296 throw SignatureException("CredentialResolver did not supply a successful verification key.");
299 throw SignatureException("CredentialResolver did not supply any verification keys.");
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) {
309 protocol = XMLString::transcode(prot);
313 cerr << "use of metadata option requires a protocol option" << endl;
316 auto_ptr<MetadataProvider> metadata(buildPlugin(m_param, conf.MetadataProviderManager));
319 const XMLCh* ns = rns ? XMLString::transcode(rns) : samlconstants::SAML20MD_NS;
320 auto_ptr_XMLCh n(rname);
321 xmltooling::QName q(ns, n.get());
323 Locker locker(metadata.get());
324 MetadataProvider::Criteria mc(issuer, &q, protocol);
325 pair<const EntityDescriptor*,const RoleDescriptor*> entity = metadata->getEntityDescriptor(mc);
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));
331 MetadataCredentialCriteria mcc(*entity.second);
332 if (sigtrust->validate(*signable->getSignature(), *metadata.get(), &mcc))
333 log.info("successful signature verification");
335 throw SignatureException("Unable to verify signature with TrustEngine and supplied metadata.");
339 CredentialCriteria cc;
340 cc.setUsage(Credential::SIGNING_CREDENTIAL);
341 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
343 cc.setPeerName(issuer);
344 DummyCredentialResolver dummy;
345 if (sigtrust->validate(*signable->getSignature(), dummy, &cc))
346 log.info("successful signature verification");
348 throw SignatureException("Unable to verify signature with TrustEngine (no metadata supplied).");
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)
357 Locker locker(cr.get());
358 CredentialCriteria cc;
359 cc.setUsage(Credential::SIGNING_CREDENTIAL);
360 const Credential* cred = cr->resolve(&cc);
362 throw XMLSecurityException("Unable to resolve a signing credential.");
364 // Attach new signature.
365 Signature* sig = SignatureBuilder::buildSignature();
366 signable->setSignature(sig);
367 auto_ptr_XMLCh alg(alg_param);
369 sig->setSignatureAlgorithm(alg.get());
371 auto_ptr_XMLCh dig(dig_param);
373 dynamic_cast<opensaml::ContentReference*>(sig->getContentReference())->setDigestAlgorithm(dig.get());
376 // Sign response while re-marshalling.
377 vector<Signature*> sigs(1,sig);
378 XMLHelper::serialize(signable->marshall((DOMDocument*)nullptr,&sigs,cred), cout);
381 catch(exception& e) {
382 log.errorStream() << "caught an exception: " << e.what() << logging::eol;