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/SignatureProfileValidator.h>
39 #include <saml/util/SAMLConstants.h>
40 #include <xmltooling/logging.h>
41 #include <xmltooling/XMLToolingConfig.h>
42 #include <xmltooling/security/Credential.h>
43 #include <xmltooling/security/SignatureTrustEngine.h>
44 #include <xmltooling/signature/Signature.h>
45 #include <xmltooling/signature/SignatureValidator.h>
46 #include <xmltooling/util/ParserPool.h>
47 #include <xmltooling/util/XMLHelper.h>
50 #include <xercesc/framework/LocalFileInputSource.hpp>
51 #include <xercesc/framework/StdInInputSource.hpp>
52 #include <xercesc/framework/Wrapper4InputSource.hpp>
54 using namespace xmlsignature;
55 using namespace xmlconstants;
56 using namespace xmltooling::logging;
57 using namespace xmltooling;
58 using namespace samlconstants;
59 using namespace opensaml::saml2md;
60 using namespace opensaml;
61 using namespace xercesc;
64 template<class T> T* buildPlugin(const char* path, PluginManager<T,string,const DOMElement*>& mgr)
67 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(in);
68 XercesJanitor<DOMDocument> janitor(doc);
70 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
71 auto_ptr_char type(doc->getDocumentElement()->getAttributeNS(nullptr,_type));
72 if (type.get() && *type.get())
73 return mgr.newPlugin(type.get(), doc->getDocumentElement());
74 throw XMLToolingException("Missing type in plugin configuration.");
77 CredentialResolver* buildSimpleResolver(const char* key, const char* cert)
79 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);
80 static const XMLCh _certificate[] = UNICODE_LITERAL_11(c,e,r,t,i,f,i,c,a,t,e);
81 static const XMLCh _key[] = UNICODE_LITERAL_3(k,e,y);
83 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().newDocument();
84 XercesJanitor<DOMDocument> janitor(doc);
85 DOMElement* root = doc->createElementNS(nullptr, _CredentialResolver);
87 auto_ptr_XMLCh widenit(key);
88 root->setAttributeNS(nullptr, _key, widenit.get());
91 auto_ptr_XMLCh widenit(cert);
92 root->setAttributeNS(nullptr, _certificate, widenit.get());
95 return XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(FILESYSTEM_CREDENTIAL_RESOLVER, root);
98 class DummyCredentialResolver : public CredentialResolver
101 DummyCredentialResolver() {}
102 ~DummyCredentialResolver() {}
104 Lockable* lock() {return this;}
107 const Credential* resolve(const CredentialCriteria* criteria=nullptr) const {return nullptr;}
108 vector<const Credential*>::size_type resolve(
109 vector<const Credential*>& results, const CredentialCriteria* criteria=nullptr
113 int main(int argc,char* argv[])
116 char* url_param=nullptr;
117 char* path_param=nullptr;
118 char* key_param=nullptr;
119 char* cert_param=nullptr;
120 char* cr_param=nullptr;
121 char* t_param=nullptr;
122 char* id_param=nullptr;
124 // metadata lookup options
125 char* m_param=nullptr;
126 char* issuer=nullptr;
127 char* prot = nullptr;
128 const XMLCh* protocol = nullptr;
129 char* rname = nullptr;
132 for (int i=1; i<argc; i++) {
133 if (!strcmp(argv[i],"-u") && i+1<argc)
135 else if (!strcmp(argv[i],"-f") && i+1<argc)
136 path_param=argv[++i];
137 else if (!strcmp(argv[i],"-id") && i+1<argc)
139 else if (!strcmp(argv[i],"-s"))
141 else if (!strcmp(argv[i],"-k") && i+1<argc)
143 else if (!strcmp(argv[i],"-c") && i+1<argc)
144 cert_param=argv[++i];
145 else if (!strcmp(argv[i],"-R") && i+1<argc)
147 else if (!strcmp(argv[i],"-T") && i+1<argc)
149 else if (!strcmp(argv[i],"-M") && i+1<argc)
151 else if (!strcmp(argv[i],"-i") && i+1<argc)
153 else if (!strcmp(argv[i],"-p") && i+1<argc)
155 else if (!strcmp(argv[i],"-r") && i+1<argc)
157 else if (!strcmp(argv[i],"-ns") && i+1<argc)
159 else if (!strcmp(argv[i],"-saml10"))
160 protocol=samlconstants::SAML10_PROTOCOL_ENUM;
161 else if (!strcmp(argv[i],"-saml11"))
162 protocol=samlconstants::SAML11_PROTOCOL_ENUM;
163 else if (!strcmp(argv[i],"-saml2"))
164 protocol=samlconstants::SAML20P_NS;
165 else if (!strcmp(argv[i],"-idp"))
166 rname="IDPSSODescriptor";
167 else if (!strcmp(argv[i],"-aa"))
168 rname="AttributeAuthorityDescriptor";
169 else if (!strcmp(argv[i],"-pdp"))
170 rname="PDPDescriptor";
171 else if (!strcmp(argv[i],"-sp"))
172 rname="SPSSODescriptor";
175 if (verify && !cert_param && !cr_param && !t_param) {
176 cerr << "either -c or -R or -T option required when verifiying, see documentation for usage" << endl;
179 else if (!verify && !key_param && !cr_param) {
180 cerr << "either -k or -R option required when signing, see documentation for usage" << endl;
184 XMLToolingConfig& xmlconf = XMLToolingConfig::getConfig();
185 xmlconf.log_config(getenv("OPENSAML_LOG_CONFIG"));
186 SAMLConfig& conf=SAMLConfig::getConfig();
189 Category& log = Category::getInstance("OpenSAML.Utility.SAMLSign");
194 // Parse the specified document.
195 DOMDocument* doc=nullptr;
197 auto_ptr_XMLCh wideurl(url_param);
198 URLInputSource src(wideurl.get());
199 Wrapper4InputSource dsrc(&src,false);
200 doc=xmlconf.getParser().parse(dsrc);
202 else if (path_param) {
203 auto_ptr_XMLCh widenit(path_param);
204 LocalFileInputSource src(widenit.get());
205 Wrapper4InputSource dsrc(&src,false);
206 doc=xmlconf.getParser().parse(dsrc);
209 StdInInputSource src;
210 Wrapper4InputSource dsrc(&src,false);
211 doc=xmlconf.getParser().parse(dsrc);
215 XercesJanitor<DOMDocument> jan(doc);
216 auto_ptr<XMLObject> sourcewrapper(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
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();
223 auto_ptr_XMLCh widenit(id_param);
224 source = XMLHelper::getXMLObjectById(*source, widenit.get());
226 throw XMLToolingException("Element with ID ($1) not found.", params(1,id_param));
228 SignableObject* signable = dynamic_cast<SignableObject*>(source);
230 throw XMLToolingException("Input is not a signable SAML object.");
233 if (!signable->getSignature())
234 throw SignatureException("Cannot verify unsigned object.");
236 // Check the profile.
237 SignatureProfileValidator sigval;
238 sigval.validate(signable->getSignature());
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(nullptr, cert_param)
245 Locker locker(cr.get());
248 CredentialCriteria cc;
249 cc.setUsage(Credential::SIGNING_CREDENTIAL);
250 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
252 cc.setPeerName(issuer);
254 // Try every credential we can find.
255 vector<const Credential*> creds;
256 if (cr->resolve(creds, &cc)) {
258 SignatureValidator sigValidator;
259 for (vector<const Credential*>::const_iterator i = creds.begin(); i != creds.end(); ++i) {
261 sigValidator.setCredential(*i);
262 sigValidator.validate(signable->getSignature());
263 log.info("successful signature verification");
267 catch (exception& e) {
268 log.info("error trying verification key: %s", e.what());
272 throw SignatureException("CredentialResolver did not supply a successful verification key.");
275 throw SignatureException("CredentialResolver did not supply any verification keys.");
279 // TrustEngine-based verification, so try and build the plugins.
280 auto_ptr<TrustEngine> trust(buildPlugin(t_param, xmlconf.TrustEngineManager));
281 SignatureTrustEngine* sigtrust = dynamic_cast<SignatureTrustEngine*>(trust.get());
282 if (m_param && rname && issuer) {
285 protocol = XMLString::transcode(prot);
289 cerr << "use of metadata option requires a protocol option" << endl;
292 auto_ptr<MetadataProvider> metadata(buildPlugin(m_param, conf.MetadataProviderManager));
295 const XMLCh* ns = rns ? XMLString::transcode(rns) : samlconstants::SAML20MD_NS;
296 auto_ptr_XMLCh n(rname);
297 xmltooling::QName q(ns, n.get());
299 Locker locker(metadata.get());
300 MetadataProvider::Criteria mc(issuer, &q, protocol);
301 pair<const EntityDescriptor*,const RoleDescriptor*> entity = metadata->getEntityDescriptor(mc);
303 throw MetadataException("no metadata found for ($1)", params(1, issuer));
304 else if (!entity.second)
305 throw MetadataException("compatible role $1 not found for ($2)", params(2, q.toString().c_str(), issuer));
307 MetadataCredentialCriteria mcc(*entity.second);
308 if (sigtrust->validate(*signable->getSignature(), *metadata.get(), &mcc))
309 log.info("successful signature verification");
311 throw SignatureException("Unable to verify signature with TrustEngine and supplied metadata.");
315 CredentialCriteria cc;
316 cc.setUsage(Credential::SIGNING_CREDENTIAL);
317 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
319 cc.setPeerName(issuer);
320 DummyCredentialResolver dummy;
321 if (sigtrust->validate(*signable->getSignature(), dummy, &cc))
322 log.info("successful signature verification");
324 throw SignatureException("Unable to verify signature with TrustEngine (no metadata supplied).");
329 // Build a resolver to supply a credential.
330 auto_ptr<CredentialResolver> cr(
331 cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(key_param, cert_param)
333 Locker locker(cr.get());
334 CredentialCriteria cc;
335 cc.setUsage(Credential::SIGNING_CREDENTIAL);
336 const Credential* cred = cr->resolve(&cc);
338 throw XMLSecurityException("Unable to resolve a signing credential.");
340 // Attach new signature.
341 Signature* sig = SignatureBuilder::buildSignature();
342 signable->setSignature(sig);
344 // Sign response while re-marshalling.
345 vector<Signature*> sigs(1,sig);
346 XMLHelper::serialize(signable->marshall((DOMDocument*)nullptr,&sigs,cred), cout);
349 catch(exception& e) {
350 log.errorStream() << "caught an exception: " << e.what() << logging::eol;