2 * Copyright 2001-2010 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * Command-line tool to sign and verify objects.
23 #if defined (_MSC_VER) || defined(__BORLANDC__)
24 # include "config_win32.h"
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
34 #include <saml/SAMLConfig.h>
35 #include <saml/saml2/metadata/Metadata.h>
36 #include <saml/saml2/metadata/MetadataProvider.h>
37 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
38 #include <saml/signature/ContentReference.h>
39 #include <saml/signature/SignatureProfileValidator.h>
40 #include <saml/util/SAMLConstants.h>
41 #include <xmltooling/logging.h>
42 #include <xmltooling/XMLToolingConfig.h>
43 #include <xmltooling/security/Credential.h>
44 #include <xmltooling/security/SignatureTrustEngine.h>
45 #include <xmltooling/signature/Signature.h>
46 #include <xmltooling/signature/SignatureValidator.h>
47 #include <xmltooling/util/ParserPool.h>
48 #include <xmltooling/util/XMLHelper.h>
51 #include <xercesc/framework/LocalFileInputSource.hpp>
52 #include <xercesc/framework/StdInInputSource.hpp>
53 #include <xercesc/framework/Wrapper4InputSource.hpp>
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;
65 template<class T> T* buildPlugin(const char* path, PluginManager<T,string,const DOMElement*>& mgr)
68 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(in);
69 XercesJanitor<DOMDocument> janitor(doc);
71 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
72 auto_ptr_char type(doc->getDocumentElement()->getAttributeNS(nullptr,_type));
73 if (type.get() && *type.get())
74 return mgr.newPlugin(type.get(), doc->getDocumentElement());
75 throw XMLToolingException("Missing type in plugin configuration.");
78 CredentialResolver* buildSimpleResolver(const char* key, const char* cert)
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);
84 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().newDocument();
85 XercesJanitor<DOMDocument> janitor(doc);
86 DOMElement* root = doc->createElementNS(nullptr, _CredentialResolver);
88 auto_ptr_XMLCh widenit(key);
89 root->setAttributeNS(nullptr, _key, widenit.get());
92 auto_ptr_XMLCh widenit(cert);
93 root->setAttributeNS(nullptr, _certificate, widenit.get());
96 return XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(FILESYSTEM_CREDENTIAL_RESOLVER, root);
99 class DummyCredentialResolver : public CredentialResolver
102 DummyCredentialResolver() {}
103 ~DummyCredentialResolver() {}
105 Lockable* lock() {return this;}
108 const Credential* resolve(const CredentialCriteria* criteria=nullptr) const {return nullptr;}
109 vector<const Credential*>::size_type resolve(
110 vector<const Credential*>& results, const CredentialCriteria* criteria=nullptr
114 int main(int argc,char* argv[])
117 char* url_param=nullptr;
118 char* path_param=nullptr;
119 char* key_param=nullptr;
120 char* cert_param=nullptr;
121 char* cr_param=nullptr;
122 char* t_param=nullptr;
123 char* id_param=nullptr;
124 char* alg_param=nullptr;
125 char* dig_param=nullptr;
127 // metadata lookup options
128 char* m_param=nullptr;
129 char* issuer=nullptr;
130 char* prot = nullptr;
131 const XMLCh* protocol = nullptr;
132 const char* rname = nullptr;
135 for (int i=1; i<argc; i++) {
136 if (!strcmp(argv[i],"-u") && i+1<argc)
138 else if (!strcmp(argv[i],"-f") && i+1<argc)
139 path_param=argv[++i];
140 else if (!strcmp(argv[i],"-id") && i+1<argc)
142 else if (!strcmp(argv[i],"-s"))
144 else if (!strcmp(argv[i],"-k") && i+1<argc)
146 else if (!strcmp(argv[i],"-c") && i+1<argc)
147 cert_param=argv[++i];
148 else if (!strcmp(argv[i],"-R") && i+1<argc)
150 else if (!strcmp(argv[i],"-T") && i+1<argc)
152 else if (!strcmp(argv[i],"-M") && i+1<argc)
154 else if (!strcmp(argv[i],"-i") && i+1<argc)
156 else if (!strcmp(argv[i],"-p") && i+1<argc)
158 else if (!strcmp(argv[i],"-r") && i+1<argc)
160 else if (!strcmp(argv[i],"-ns") && i+1<argc)
162 else if (!strcmp(argv[i],"-alg") && i+1<argc)
164 else if (!strcmp(argv[i],"-dig") && i+1<argc)
166 else if (!strcmp(argv[i],"-saml10"))
167 protocol=samlconstants::SAML10_PROTOCOL_ENUM;
168 else if (!strcmp(argv[i],"-saml11"))
169 protocol=samlconstants::SAML11_PROTOCOL_ENUM;
170 else if (!strcmp(argv[i],"-saml2"))
171 protocol=samlconstants::SAML20P_NS;
172 else if (!strcmp(argv[i],"-idp"))
173 rname="IDPSSODescriptor";
174 else if (!strcmp(argv[i],"-aa"))
175 rname="AttributeAuthorityDescriptor";
176 else if (!strcmp(argv[i],"-pdp"))
177 rname="PDPDescriptor";
178 else if (!strcmp(argv[i],"-sp"))
179 rname="SPSSODescriptor";
182 if (verify && !cert_param && !cr_param && !t_param) {
183 cerr << "either -c or -R or -T option required when verifiying, see documentation for usage" << endl;
186 else if (!verify && !key_param && !cr_param) {
187 cerr << "either -k or -R option required when signing, see documentation for usage" << endl;
191 XMLToolingConfig& xmlconf = XMLToolingConfig::getConfig();
192 xmlconf.log_config(getenv("OPENSAML_LOG_CONFIG"));
193 SAMLConfig& conf=SAMLConfig::getConfig();
196 Category& log = Category::getInstance("OpenSAML.Utility.SAMLSign");
201 // Parse the specified document.
202 DOMDocument* doc=nullptr;
204 auto_ptr_XMLCh wideurl(url_param);
205 URLInputSource src(wideurl.get());
206 Wrapper4InputSource dsrc(&src,false);
207 doc=xmlconf.getParser().parse(dsrc);
209 else if (path_param) {
210 auto_ptr_XMLCh widenit(path_param);
211 LocalFileInputSource src(widenit.get());
212 Wrapper4InputSource dsrc(&src,false);
213 doc=xmlconf.getParser().parse(dsrc);
216 StdInInputSource src;
217 Wrapper4InputSource dsrc(&src,false);
218 doc=xmlconf.getParser().parse(dsrc);
222 XercesJanitor<DOMDocument> jan(doc);
223 auto_ptr<XMLObject> sourcewrapper(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
226 // Navigate to the selected node, or use the root if no ID specified.
227 // Then make sure it's a SignableSAMLObject.
228 XMLObject* source = sourcewrapper.get();
230 auto_ptr_XMLCh widenit(id_param);
231 source = XMLHelper::getXMLObjectById(*source, widenit.get());
233 throw XMLToolingException("Element with ID ($1) not found.", params(1,id_param));
235 SignableObject* signable = dynamic_cast<SignableObject*>(source);
237 throw XMLToolingException("Input is not a signable SAML object.");
240 if (!signable->getSignature())
241 throw SignatureException("Cannot verify unsigned object.");
243 // Check the profile.
244 SignatureProfileValidator sigval;
245 sigval.validate(signable->getSignature());
247 if (cert_param || cr_param) {
248 // Build a resolver to supply trusted credentials.
249 auto_ptr<CredentialResolver> cr(
250 cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(nullptr, cert_param)
252 Locker locker(cr.get());
255 CredentialCriteria cc;
256 cc.setUsage(Credential::SIGNING_CREDENTIAL);
257 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
259 cc.setPeerName(issuer);
261 // Try every credential we can find.
262 vector<const Credential*> creds;
263 if (cr->resolve(creds, &cc)) {
265 SignatureValidator sigValidator;
266 for (vector<const Credential*>::const_iterator i = creds.begin(); i != creds.end(); ++i) {
268 sigValidator.setCredential(*i);
269 sigValidator.validate(signable->getSignature());
270 log.info("successful signature verification");
274 catch (exception& e) {
275 log.info("error trying verification key: %s", e.what());
279 throw SignatureException("CredentialResolver did not supply a successful verification key.");
282 throw SignatureException("CredentialResolver did not supply any verification keys.");
286 // TrustEngine-based verification, so try and build the plugins.
287 auto_ptr<TrustEngine> trust(buildPlugin(t_param, xmlconf.TrustEngineManager));
288 SignatureTrustEngine* sigtrust = dynamic_cast<SignatureTrustEngine*>(trust.get());
289 if (m_param && rname && issuer) {
292 protocol = XMLString::transcode(prot);
296 cerr << "use of metadata option requires a protocol option" << endl;
299 auto_ptr<MetadataProvider> metadata(buildPlugin(m_param, conf.MetadataProviderManager));
302 const XMLCh* ns = rns ? XMLString::transcode(rns) : samlconstants::SAML20MD_NS;
303 auto_ptr_XMLCh n(rname);
304 xmltooling::QName q(ns, n.get());
306 Locker locker(metadata.get());
307 MetadataProvider::Criteria mc(issuer, &q, protocol);
308 pair<const EntityDescriptor*,const RoleDescriptor*> entity = metadata->getEntityDescriptor(mc);
310 throw MetadataException("no metadata found for ($1)", params(1, issuer));
311 else if (!entity.second)
312 throw MetadataException("compatible role $1 not found for ($2)", params(2, q.toString().c_str(), issuer));
314 MetadataCredentialCriteria mcc(*entity.second);
315 if (sigtrust->validate(*signable->getSignature(), *metadata.get(), &mcc))
316 log.info("successful signature verification");
318 throw SignatureException("Unable to verify signature with TrustEngine and supplied metadata.");
322 CredentialCriteria cc;
323 cc.setUsage(Credential::SIGNING_CREDENTIAL);
324 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
326 cc.setPeerName(issuer);
327 DummyCredentialResolver dummy;
328 if (sigtrust->validate(*signable->getSignature(), dummy, &cc))
329 log.info("successful signature verification");
331 throw SignatureException("Unable to verify signature with TrustEngine (no metadata supplied).");
336 // Build a resolver to supply a credential.
337 auto_ptr<CredentialResolver> cr(
338 cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(key_param, cert_param)
340 Locker locker(cr.get());
341 CredentialCriteria cc;
342 cc.setUsage(Credential::SIGNING_CREDENTIAL);
343 const Credential* cred = cr->resolve(&cc);
345 throw XMLSecurityException("Unable to resolve a signing credential.");
347 // Attach new signature.
348 Signature* sig = SignatureBuilder::buildSignature();
350 auto_ptr_XMLCh alg(alg_param);
351 sig->setSignatureAlgorithm(alg.get());
354 auto_ptr_XMLCh dig(dig_param);
355 dynamic_cast<opensaml::ContentReference*>(sig->getContentReference())->setDigestAlgorithm(dig.get());
357 signable->setSignature(sig);
359 // Sign response while re-marshalling.
360 vector<Signature*> sigs(1,sig);
361 XMLHelper::serialize(signable->marshall((DOMDocument*)nullptr,&sigs,cred), cout);
364 catch(exception& e) {
365 log.errorStream() << "caught an exception: " << e.what() << logging::eol;