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[])
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],"-ns") && i+1<argc)
166 else if (!strcmp(argv[i],"-alg") && i+1<argc)
168 else if (!strcmp(argv[i],"-dig") && i+1<argc)
170 else if (!strcmp(argv[i],"-saml10"))
171 protocol=samlconstants::SAML10_PROTOCOL_ENUM;
172 else if (!strcmp(argv[i],"-saml11"))
173 protocol=samlconstants::SAML11_PROTOCOL_ENUM;
174 else if (!strcmp(argv[i],"-saml2"))
175 protocol=samlconstants::SAML20P_NS;
176 else if (!strcmp(argv[i],"-idp"))
177 rname="IDPSSODescriptor";
178 else if (!strcmp(argv[i],"-aa"))
179 rname="AttributeAuthorityDescriptor";
180 else if (!strcmp(argv[i],"-pdp"))
181 rname="PDPDescriptor";
182 else if (!strcmp(argv[i],"-sp"))
183 rname="SPSSODescriptor";
186 if (verify && !cert_param && !cr_param && !t_param) {
187 cerr << "either -c or -R or -T option required when verifiying, see documentation for usage" << endl;
190 else if (!verify && !key_param && !cr_param) {
191 cerr << "either -k or -R option required when signing, see documentation for usage" << endl;
195 XMLToolingConfig& xmlconf = XMLToolingConfig::getConfig();
196 xmlconf.log_config(getenv("OPENSAML_LOG_CONFIG"));
197 SAMLConfig& conf=SAMLConfig::getConfig();
200 Category& log = Category::getInstance("OpenSAML.Utility.SAMLSign");
205 // Parse the specified document.
206 DOMDocument* doc=nullptr;
208 auto_ptr_XMLCh wideurl(url_param);
209 URLInputSource src(wideurl.get());
210 Wrapper4InputSource dsrc(&src,false);
211 doc=xmlconf.getParser().parse(dsrc);
213 else if (path_param) {
214 auto_ptr_XMLCh widenit(path_param);
215 LocalFileInputSource src(widenit.get());
216 Wrapper4InputSource dsrc(&src,false);
217 doc=xmlconf.getParser().parse(dsrc);
220 StdInInputSource src;
221 Wrapper4InputSource dsrc(&src,false);
222 doc=xmlconf.getParser().parse(dsrc);
226 XercesJanitor<DOMDocument> jan(doc);
227 auto_ptr<XMLObject> sourcewrapper(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
230 // Navigate to the selected node, or use the root if no ID specified.
231 // Then make sure it's a SignableSAMLObject.
232 XMLObject* source = sourcewrapper.get();
234 auto_ptr_XMLCh widenit(id_param);
235 source = XMLHelper::getXMLObjectById(*source, widenit.get());
237 throw XMLToolingException("Element with ID ($1) not found.", params(1,id_param));
239 SignableObject* signable = dynamic_cast<SignableObject*>(source);
241 throw XMLToolingException("Input is not a signable SAML object.");
244 if (!signable->getSignature())
245 throw SignatureException("Cannot verify unsigned object.");
247 // Check the profile.
248 SignatureProfileValidator sigval;
249 sigval.validate(signable->getSignature());
251 if (cert_param || cr_param) {
252 // Build a resolver to supply trusted credentials.
253 auto_ptr<CredentialResolver> cr(
254 cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(nullptr, cert_param)
256 Locker locker(cr.get());
259 CredentialCriteria cc;
260 cc.setUsage(Credential::SIGNING_CREDENTIAL);
261 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
263 cc.setPeerName(issuer);
265 // Try every credential we can find.
266 vector<const Credential*> creds;
267 if (cr->resolve(creds, &cc)) {
269 SignatureValidator sigValidator;
270 for (vector<const Credential*>::const_iterator i = creds.begin(); i != creds.end(); ++i) {
272 sigValidator.setCredential(*i);
273 sigValidator.validate(signable->getSignature());
274 log.info("successful signature verification");
278 catch (exception& e) {
279 log.info("error trying verification key: %s", e.what());
283 throw SignatureException("CredentialResolver did not supply a successful verification key.");
286 throw SignatureException("CredentialResolver did not supply any verification keys.");
290 // TrustEngine-based verification, so try and build the plugins.
291 auto_ptr<TrustEngine> trust(buildPlugin(t_param, xmlconf.TrustEngineManager));
292 SignatureTrustEngine* sigtrust = dynamic_cast<SignatureTrustEngine*>(trust.get());
293 if (m_param && rname && issuer) {
296 protocol = XMLString::transcode(prot);
300 cerr << "use of metadata option requires a protocol option" << endl;
303 auto_ptr<MetadataProvider> metadata(buildPlugin(m_param, conf.MetadataProviderManager));
306 const XMLCh* ns = rns ? XMLString::transcode(rns) : samlconstants::SAML20MD_NS;
307 auto_ptr_XMLCh n(rname);
308 xmltooling::QName q(ns, n.get());
310 Locker locker(metadata.get());
311 MetadataProvider::Criteria mc(issuer, &q, protocol);
312 pair<const EntityDescriptor*,const RoleDescriptor*> entity = metadata->getEntityDescriptor(mc);
314 throw MetadataException("no metadata found for ($1)", params(1, issuer));
315 else if (!entity.second)
316 throw MetadataException("compatible role $1 not found for ($2)", params(2, q.toString().c_str(), issuer));
318 MetadataCredentialCriteria mcc(*entity.second);
319 if (sigtrust->validate(*signable->getSignature(), *metadata.get(), &mcc))
320 log.info("successful signature verification");
322 throw SignatureException("Unable to verify signature with TrustEngine and supplied metadata.");
326 CredentialCriteria cc;
327 cc.setUsage(Credential::SIGNING_CREDENTIAL);
328 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
330 cc.setPeerName(issuer);
331 DummyCredentialResolver dummy;
332 if (sigtrust->validate(*signable->getSignature(), dummy, &cc))
333 log.info("successful signature verification");
335 throw SignatureException("Unable to verify signature with TrustEngine (no metadata supplied).");
340 // Build a resolver to supply a credential.
341 auto_ptr<CredentialResolver> cr(
342 cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(key_param, cert_param)
344 Locker locker(cr.get());
345 CredentialCriteria cc;
346 cc.setUsage(Credential::SIGNING_CREDENTIAL);
347 const Credential* cred = cr->resolve(&cc);
349 throw XMLSecurityException("Unable to resolve a signing credential.");
351 // Attach new signature.
352 Signature* sig = SignatureBuilder::buildSignature();
354 auto_ptr_XMLCh alg(alg_param);
355 sig->setSignatureAlgorithm(alg.get());
358 auto_ptr_XMLCh dig(dig_param);
359 dynamic_cast<opensaml::ContentReference*>(sig->getContentReference())->setDigestAlgorithm(dig.get());
361 signable->setSignature(sig);
363 // Sign response while re-marshalling.
364 vector<Signature*> sigs(1,sig);
365 XMLHelper::serialize(signable->marshall((DOMDocument*)nullptr,&sigs,cred), cout);
368 catch(exception& e) {
369 log.errorStream() << "caught an exception: " << e.what() << logging::eol;