2e67ddf0248c3f51748dd41e101049f9b5c7f14e
[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;
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],"-ns") && i+1<argc)
165             rns=argv[++i];
166         else if (!strcmp(argv[i],"-alg") && i+1<argc)
167             alg_param=argv[++i];
168         else if (!strcmp(argv[i],"-dig") && i+1<argc)
169             dig_param=argv[++i];
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";
184     }
185
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;
188         return -1;
189     }
190     else if (!verify && !key_param && !cr_param) {
191         cerr << "either -k or -R option required when signing, see documentation for usage" << endl;
192         return -1;
193     }
194
195     XMLToolingConfig& xmlconf = XMLToolingConfig::getConfig();
196     xmlconf.log_config(getenv("OPENSAML_LOG_CONFIG"));
197     SAMLConfig& conf=SAMLConfig::getConfig();
198     if (!conf.init())
199         return -2;
200     Category& log = Category::getInstance("OpenSAML.Utility.SAMLSign");
201
202     int ret = 0;
203
204     try {
205         // Parse the specified document.
206         DOMDocument* doc=nullptr;
207         if (url_param) {
208             auto_ptr_XMLCh wideurl(url_param);
209             URLInputSource src(wideurl.get());
210             Wrapper4InputSource dsrc(&src,false);
211             doc=xmlconf.getParser().parse(dsrc);
212         }
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);
218         }
219         else {
220             StdInInputSource src;
221             Wrapper4InputSource dsrc(&src,false);
222             doc=xmlconf.getParser().parse(dsrc);
223         }
224
225         // Unmarshall it.
226         XercesJanitor<DOMDocument> jan(doc);
227         auto_ptr<XMLObject> sourcewrapper(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
228         jan.release();
229
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();
233         if (id_param) {
234             auto_ptr_XMLCh widenit(id_param);
235             source = XMLHelper::getXMLObjectById(*source, widenit.get());
236             if (!source)
237                 throw XMLToolingException("Element with ID ($1) not found.", params(1,id_param));
238         }
239         SignableObject* signable = dynamic_cast<SignableObject*>(source);
240         if (!signable)
241             throw XMLToolingException("Input is not a signable SAML object.");
242
243         if (verify) {
244             if (!signable->getSignature())
245                 throw SignatureException("Cannot verify unsigned object.");
246
247             // Check the profile.
248             SignatureProfileValidator sigval;
249             sigval.validate(signable->getSignature());
250
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)
255                     );
256                 Locker locker(cr.get());
257
258                 // Set up criteria.
259                 CredentialCriteria cc;
260                 cc.setUsage(Credential::SIGNING_CREDENTIAL);
261                 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
262                 if (issuer)
263                     cc.setPeerName(issuer);
264
265                 // Try every credential we can find.
266                 vector<const Credential*> creds;
267                 if (cr->resolve(creds, &cc)) {
268                     bool good=false;
269                     SignatureValidator sigValidator;
270                     for (vector<const Credential*>::const_iterator i = creds.begin(); i != creds.end(); ++i) {
271                         try {
272                             sigValidator.setCredential(*i);
273                             sigValidator.validate(signable->getSignature());
274                             log.info("successful signature verification");
275                             good = true;
276                             break;
277                         }
278                         catch (exception& e) {
279                             log.info("error trying verification key: %s", e.what());
280                         }
281                     }
282                     if (!good)
283                         throw SignatureException("CredentialResolver did not supply a successful verification key.");
284                 }
285                 else {
286                     throw SignatureException("CredentialResolver did not supply any verification keys.");
287                 }
288             }
289             else {
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) {
294                     if (!protocol) {
295                         if (prot)
296                             protocol = XMLString::transcode(prot);
297                     }
298                     if (!protocol) {
299                         conf.term();
300                         cerr << "use of metadata option requires a protocol option" << endl;
301                         return -1;
302                     }
303                     auto_ptr<MetadataProvider> metadata(buildPlugin(m_param, conf.MetadataProviderManager));
304                     metadata->init();
305
306                     const XMLCh* ns = rns ? XMLString::transcode(rns) : samlconstants::SAML20MD_NS;
307                     auto_ptr_XMLCh n(rname);
308                     xmltooling::QName q(ns, n.get());
309
310                     Locker locker(metadata.get());
311                     MetadataProvider::Criteria mc(issuer, &q, protocol);
312                     pair<const EntityDescriptor*,const RoleDescriptor*> entity = metadata->getEntityDescriptor(mc);
313                     if (!entity.first)
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));
317
318                     MetadataCredentialCriteria mcc(*entity.second);
319                     if (sigtrust->validate(*signable->getSignature(), *metadata.get(), &mcc))
320                         log.info("successful signature verification");
321                     else
322                         throw SignatureException("Unable to verify signature with TrustEngine and supplied metadata.");
323                 }
324                 else {
325                     // Set up criteria.
326                     CredentialCriteria cc;
327                     cc.setUsage(Credential::SIGNING_CREDENTIAL);
328                     cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
329                     if (issuer)
330                         cc.setPeerName(issuer);
331                     DummyCredentialResolver dummy;
332                     if (sigtrust->validate(*signable->getSignature(), dummy, &cc))
333                         log.info("successful signature verification");
334                     else
335                         throw SignatureException("Unable to verify signature with TrustEngine (no metadata supplied).");
336                 }
337             }
338         }
339         else {
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)
343                 );
344             Locker locker(cr.get());
345             CredentialCriteria cc;
346             cc.setUsage(Credential::SIGNING_CREDENTIAL);
347             const Credential* cred = cr->resolve(&cc);
348             if (!cred)
349                 throw XMLSecurityException("Unable to resolve a signing credential.");
350
351             // Attach new signature.
352             Signature* sig = SignatureBuilder::buildSignature();
353             if (alg_param) {
354                 auto_ptr_XMLCh alg(alg_param);
355                 sig->setSignatureAlgorithm(alg.get());
356             }
357             if (dig_param) {
358                 auto_ptr_XMLCh dig(dig_param);
359                 dynamic_cast<opensaml::ContentReference*>(sig->getContentReference())->setDigestAlgorithm(dig.get());
360             }
361             signable->setSignature(sig);
362
363             // Sign response while re-marshalling.
364             vector<Signature*> sigs(1,sig);
365             XMLHelper::serialize(signable->marshall((DOMDocument*)nullptr,&sigs,cred), cout);
366         }
367     }
368     catch(exception& e) {
369         log.errorStream() << "caught an exception: " << e.what() << logging::eol;
370         ret=-10;
371     }
372
373     conf.term();
374     return ret;
375 }