Fix deprecation warning.
[shibboleth/cpp-opensaml.git] / samlsign / samlsign.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * samlsign.cpp
19  *
20  * Command-line tool to sign and verify objects.
21  */
22
23 #if defined (_MSC_VER) || defined(__BORLANDC__)
24 # include "config_win32.h"
25 #else
26 # include "config.h"
27 #endif
28
29 #ifdef WIN32
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
32 #endif
33
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>
48
49 #include <fstream>
50 #include <xercesc/framework/LocalFileInputSource.hpp>
51 #include <xercesc/framework/StdInInputSource.hpp>
52 #include <xercesc/framework/Wrapper4InputSource.hpp>
53
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;
62 using namespace std;
63
64 template<class T> T* buildPlugin(const char* path, PluginManager<T,string,const DOMElement*>& mgr)
65 {
66     ifstream in(path);
67     DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(in);
68     XercesJanitor<DOMDocument> janitor(doc);
69
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.");
75 }
76
77 CredentialResolver* buildSimpleResolver(const char* key, const char* cert)
78 {
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);
82
83     DOMDocument* doc = XMLToolingConfig::getConfig().getParser().newDocument();
84     XercesJanitor<DOMDocument> janitor(doc);
85     DOMElement* root = doc->createElementNS(nullptr, _CredentialResolver);
86     if (key) {
87         auto_ptr_XMLCh widenit(key);
88         root->setAttributeNS(nullptr, _key, widenit.get());
89     }
90     if (cert) {
91         auto_ptr_XMLCh widenit(cert);
92         root->setAttributeNS(nullptr, _certificate, widenit.get());
93     }
94
95     return XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(FILESYSTEM_CREDENTIAL_RESOLVER, root);
96 }
97
98 class DummyCredentialResolver : public CredentialResolver
99 {
100 public:
101     DummyCredentialResolver() {}
102     ~DummyCredentialResolver() {}
103
104     Lockable* lock() {return this;}
105     void unlock() {}
106
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
110         ) const {return 0;}
111 };
112
113 int main(int argc,char* argv[])
114 {
115     bool verify=true;
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;
123
124     // metadata lookup options
125     char* m_param=nullptr;
126     char* issuer=nullptr;
127     char* prot = nullptr;
128     const XMLCh* protocol = nullptr;
129     const char* rname = nullptr;
130     char* rns = nullptr;
131
132     for (int i=1; i<argc; i++) {
133         if (!strcmp(argv[i],"-u") && i+1<argc)
134             url_param=argv[++i];
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)
138             id_param=argv[++i];
139         else if (!strcmp(argv[i],"-s"))
140             verify=false;
141         else if (!strcmp(argv[i],"-k") && i+1<argc)
142             key_param=argv[++i];
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)
146             cr_param=argv[++i];
147         else if (!strcmp(argv[i],"-T") && i+1<argc)
148             t_param=argv[++i];
149         else if (!strcmp(argv[i],"-M") && i+1<argc)
150             m_param=argv[++i];
151         else if (!strcmp(argv[i],"-i") && i+1<argc)
152             issuer=argv[++i];
153         else if (!strcmp(argv[i],"-p") && i+1<argc)
154             prot=argv[++i];
155         else if (!strcmp(argv[i],"-r") && i+1<argc)
156             rname=argv[++i];
157         else if (!strcmp(argv[i],"-ns") && i+1<argc)
158             rns=argv[++i];
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";
173     }
174
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;
177         return -1;
178     }
179     else if (!verify && !key_param && !cr_param) {
180         cerr << "either -k or -R option required when signing, see documentation for usage" << endl;
181         return -1;
182     }
183
184     XMLToolingConfig& xmlconf = XMLToolingConfig::getConfig();
185     xmlconf.log_config(getenv("OPENSAML_LOG_CONFIG"));
186     SAMLConfig& conf=SAMLConfig::getConfig();
187     if (!conf.init())
188         return -2;
189     Category& log = Category::getInstance("OpenSAML.Utility.SAMLSign");
190
191     int ret = 0;
192
193     try {
194         // Parse the specified document.
195         DOMDocument* doc=nullptr;
196         if (url_param) {
197             auto_ptr_XMLCh wideurl(url_param);
198             URLInputSource src(wideurl.get());
199             Wrapper4InputSource dsrc(&src,false);
200             doc=xmlconf.getParser().parse(dsrc);
201         }
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);
207         }
208         else {
209             StdInInputSource src;
210             Wrapper4InputSource dsrc(&src,false);
211             doc=xmlconf.getParser().parse(dsrc);
212         }
213
214         // Unmarshall it.
215         XercesJanitor<DOMDocument> jan(doc);
216         auto_ptr<XMLObject> sourcewrapper(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
217         jan.release();
218
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();
222         if (id_param) {
223             auto_ptr_XMLCh widenit(id_param);
224             source = XMLHelper::getXMLObjectById(*source, widenit.get());
225             if (!source)
226                 throw XMLToolingException("Element with ID ($1) not found.", params(1,id_param));
227         }
228         SignableObject* signable = dynamic_cast<SignableObject*>(source);
229         if (!signable)
230             throw XMLToolingException("Input is not a signable SAML object.");
231
232         if (verify) {
233             if (!signable->getSignature())
234                 throw SignatureException("Cannot verify unsigned object.");
235
236             // Check the profile.
237             SignatureProfileValidator sigval;
238             sigval.validate(signable->getSignature());
239
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)
244                     );
245                 Locker locker(cr.get());
246
247                 // Set up criteria.
248                 CredentialCriteria cc;
249                 cc.setUsage(Credential::SIGNING_CREDENTIAL);
250                 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
251                 if (issuer)
252                     cc.setPeerName(issuer);
253
254                 // Try every credential we can find.
255                 vector<const Credential*> creds;
256                 if (cr->resolve(creds, &cc)) {
257                     bool good=false;
258                     SignatureValidator sigValidator;
259                     for (vector<const Credential*>::const_iterator i = creds.begin(); i != creds.end(); ++i) {
260                         try {
261                             sigValidator.setCredential(*i);
262                             sigValidator.validate(signable->getSignature());
263                             log.info("successful signature verification");
264                             good = true;
265                             break;
266                         }
267                         catch (exception& e) {
268                             log.info("error trying verification key: %s", e.what());
269                         }
270                     }
271                     if (!good)
272                         throw SignatureException("CredentialResolver did not supply a successful verification key.");
273                 }
274                 else {
275                     throw SignatureException("CredentialResolver did not supply any verification keys.");
276                 }
277             }
278             else {
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) {
283                     if (!protocol) {
284                         if (prot)
285                             protocol = XMLString::transcode(prot);
286                     }
287                     if (!protocol) {
288                         conf.term();
289                         cerr << "use of metadata option requires a protocol option" << endl;
290                         return -1;
291                     }
292                     auto_ptr<MetadataProvider> metadata(buildPlugin(m_param, conf.MetadataProviderManager));
293                     metadata->init();
294
295                     const XMLCh* ns = rns ? XMLString::transcode(rns) : samlconstants::SAML20MD_NS;
296                     auto_ptr_XMLCh n(rname);
297                     xmltooling::QName q(ns, n.get());
298
299                     Locker locker(metadata.get());
300                     MetadataProvider::Criteria mc(issuer, &q, protocol);
301                     pair<const EntityDescriptor*,const RoleDescriptor*> entity = metadata->getEntityDescriptor(mc);
302                     if (!entity.first)
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));
306
307                     MetadataCredentialCriteria mcc(*entity.second);
308                     if (sigtrust->validate(*signable->getSignature(), *metadata.get(), &mcc))
309                         log.info("successful signature verification");
310                     else
311                         throw SignatureException("Unable to verify signature with TrustEngine and supplied metadata.");
312                 }
313                 else {
314                     // Set up criteria.
315                     CredentialCriteria cc;
316                     cc.setUsage(Credential::SIGNING_CREDENTIAL);
317                     cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
318                     if (issuer)
319                         cc.setPeerName(issuer);
320                     DummyCredentialResolver dummy;
321                     if (sigtrust->validate(*signable->getSignature(), dummy, &cc))
322                         log.info("successful signature verification");
323                     else
324                         throw SignatureException("Unable to verify signature with TrustEngine (no metadata supplied).");
325                 }
326             }
327         }
328         else {
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)
332                 );
333             Locker locker(cr.get());
334             CredentialCriteria cc;
335             cc.setUsage(Credential::SIGNING_CREDENTIAL);
336             const Credential* cred = cr->resolve(&cc);
337             if (!cred)
338                 throw XMLSecurityException("Unable to resolve a signing credential.");
339
340             // Attach new signature.
341             Signature* sig = SignatureBuilder::buildSignature();
342             signable->setSignature(sig);
343
344             // Sign response while re-marshalling.
345             vector<Signature*> sigs(1,sig);
346             XMLHelper::serialize(signable->marshall((DOMDocument*)nullptr,&sigs,cred), cout);
347         }
348     }
349     catch(exception& e) {
350         log.errorStream() << "caught an exception: " << e.what() << logging::eol;
351         ret=-10;
352     }
353
354     conf.term();
355     return ret;
356 }