Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-opensaml.git] / samlsign / samlsign.cpp
1 /*
2  *  Copyright 2001-2009 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/XMLHelper.h>
47
48 #include <fstream>
49 #include <xercesc/framework/LocalFileInputSource.hpp>
50 #include <xercesc/framework/StdInInputSource.hpp>
51 #include <xercesc/framework/Wrapper4InputSource.hpp>
52
53 using namespace xmlsignature;
54 using namespace xmlconstants;
55 using namespace xmltooling::logging;
56 using namespace xmltooling;
57 using namespace samlconstants;
58 using namespace opensaml::saml2md;
59 using namespace opensaml;
60 using namespace xercesc;
61 using namespace std;
62
63 template<class T> T* buildPlugin(const char* path, PluginManager<T,string,const DOMElement*>& mgr)
64 {
65     ifstream in(path);
66     DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(in);
67     XercesJanitor<DOMDocument> janitor(doc);
68
69     static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
70     auto_ptr_char type(doc->getDocumentElement()->getAttributeNS(NULL,_type));
71     if (type.get() && *type.get())
72         return mgr.newPlugin(type.get(), doc->getDocumentElement());
73     throw XMLToolingException("Missing type in plugin configuration.");
74 }
75
76 CredentialResolver* buildSimpleResolver(const char* key, const char* cert)
77 {
78     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);
79     static const XMLCh _certificate[] =     UNICODE_LITERAL_11(c,e,r,t,i,f,i,c,a,t,e);
80     static const XMLCh _key[] =             UNICODE_LITERAL_3(k,e,y);
81
82     DOMDocument* doc = XMLToolingConfig::getConfig().getParser().newDocument();
83     XercesJanitor<DOMDocument> janitor(doc);
84     DOMElement* root = doc->createElementNS(NULL, _CredentialResolver);
85     if (key) {
86         auto_ptr_XMLCh widenit(key);
87         root->setAttributeNS(NULL, _key, widenit.get());
88     }
89     if (cert) {
90         auto_ptr_XMLCh widenit(cert);
91         root->setAttributeNS(NULL, _certificate, widenit.get());
92     }
93
94     return XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(FILESYSTEM_CREDENTIAL_RESOLVER, root);
95 }
96
97 class DummyCredentialResolver : public CredentialResolver
98 {
99 public:
100     DummyCredentialResolver() {}
101     ~DummyCredentialResolver() {}
102
103     Lockable* lock() {return this;}
104     void unlock() {}
105
106     const Credential* resolve(const CredentialCriteria* criteria=NULL) const {return NULL;}
107     vector<const Credential*>::size_type resolve(
108         vector<const Credential*>& results, const CredentialCriteria* criteria=NULL
109         ) const {return 0;}
110 };
111
112 int main(int argc,char* argv[])
113 {
114     bool verify=true;
115     char* url_param=NULL;
116     char* path_param=NULL;
117     char* key_param=NULL;
118     char* cert_param=NULL;
119     char* cr_param=NULL;
120     char* t_param=NULL;
121     char* id_param=NULL;
122
123     // metadata lookup options
124     char* m_param=NULL;
125     char* issuer=NULL;
126     char* prot = NULL;
127     const XMLCh* protocol = NULL;
128     char* rname = NULL;
129     char* rns = NULL;
130
131     for (int i=1; i<argc; i++) {
132         if (!strcmp(argv[i],"-u") && i+1<argc)
133             url_param=argv[++i];
134         else if (!strcmp(argv[i],"-f") && i+1<argc)
135             path_param=argv[++i];
136         else if (!strcmp(argv[i],"-id") && i+1<argc)
137             id_param=argv[++i];
138         else if (!strcmp(argv[i],"-s"))
139             verify=false;
140         else if (!strcmp(argv[i],"-k") && i+1<argc)
141             key_param=argv[++i];
142         else if (!strcmp(argv[i],"-c") && i+1<argc)
143             cert_param=argv[++i];
144         else if (!strcmp(argv[i],"-R") && i+1<argc)
145             cr_param=argv[++i];
146         else if (!strcmp(argv[i],"-T") && i+1<argc)
147             t_param=argv[++i];
148         else if (!strcmp(argv[i],"-M") && i+1<argc)
149             m_param=argv[++i];
150         else if (!strcmp(argv[i],"-i") && i+1<argc)
151             issuer=argv[++i];
152         else if (!strcmp(argv[i],"-p") && i+1<argc)
153             prot=argv[++i];
154         else if (!strcmp(argv[i],"-r") && i+1<argc)
155             rname=argv[++i];
156         else if (!strcmp(argv[i],"-ns") && i+1<argc)
157             rns=argv[++i];
158         else if (!strcmp(argv[i],"-saml10"))
159             protocol=samlconstants::SAML10_PROTOCOL_ENUM;
160         else if (!strcmp(argv[i],"-saml11"))
161             protocol=samlconstants::SAML11_PROTOCOL_ENUM;
162         else if (!strcmp(argv[i],"-saml2"))
163             protocol=samlconstants::SAML20P_NS;
164         else if (!strcmp(argv[i],"-idp"))
165             rname="IDPSSODescriptor";
166         else if (!strcmp(argv[i],"-aa"))
167             rname="AttributeAuthorityDescriptor";
168         else if (!strcmp(argv[i],"-pdp"))
169             rname="PDPDescriptor";
170         else if (!strcmp(argv[i],"-sp"))
171             rname="SPSSODescriptor";
172     }
173
174     if (verify && !cert_param && !cr_param && !t_param) {
175         cerr << "either -c or -R or -T option required when verifiying, see documentation for usage" << endl;
176         return -1;
177     }
178     else if (!verify && !key_param && !cr_param) {
179         cerr << "either -k or -R option required when signing, see documentation for usage" << endl;
180         return -1;
181     }
182
183     XMLToolingConfig& xmlconf = XMLToolingConfig::getConfig();
184     xmlconf.log_config();
185     SAMLConfig& conf=SAMLConfig::getConfig();
186     if (!conf.init())
187         return -2;
188     Category& log = Category::getInstance("OpenSAML.Utility.SAMLSign");
189
190     int ret = 0;
191
192     try {
193         // Parse the specified document.
194         DOMDocument* doc=NULL;
195         if (url_param) {
196             auto_ptr_XMLCh wideurl(url_param);
197             URLInputSource src(wideurl.get());
198             Wrapper4InputSource dsrc(&src,false);
199             doc=xmlconf.getParser().parse(dsrc);
200         }
201         else if (path_param) {
202             auto_ptr_XMLCh widenit(path_param);
203             LocalFileInputSource src(widenit.get());
204             Wrapper4InputSource dsrc(&src,false);
205             doc=xmlconf.getParser().parse(dsrc);
206         }
207         else {
208             StdInInputSource src;
209             Wrapper4InputSource dsrc(&src,false);
210             doc=xmlconf.getParser().parse(dsrc);
211         }
212
213         // Unmarshall it.
214         XercesJanitor<DOMDocument> jan(doc);
215         auto_ptr<XMLObject> sourcewrapper(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
216         jan.release();
217
218         // Navigate to the selected node, or use the root if no ID specified.
219         // Then make sure it's a SignableSAMLObject.
220         XMLObject* source = sourcewrapper.get();
221         if (id_param) {
222             auto_ptr_XMLCh widenit(id_param);
223             source = XMLHelper::getXMLObjectById(*source, widenit.get());
224             if (!source)
225                 throw XMLToolingException("Element with ID ($1) not found.", params(1,id_param));
226         }
227         SignableObject* signable = dynamic_cast<SignableObject*>(source);
228         if (!signable)
229             throw XMLToolingException("Input is not a signable SAML object.");
230
231         if (verify) {
232             if (!signable->getSignature())
233                 throw SignatureException("Cannot verify unsigned object.");
234
235             // Check the profile.
236             SignatureProfileValidator sigval;
237             sigval.validate(signable->getSignature());
238
239             if (cert_param || cr_param) {
240                 // Build a resolver to supply trusted credentials.
241                 auto_ptr<CredentialResolver> cr(
242                     cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(NULL, cert_param)
243                     );
244                 Locker locker(cr.get());
245
246                 // Set up criteria.
247                 CredentialCriteria cc;
248                 cc.setUsage(Credential::SIGNING_CREDENTIAL);
249                 cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
250                 if (issuer)
251                     cc.setPeerName(issuer);
252
253                 // Try every credential we can find.
254                 vector<const Credential*> creds;
255                 if (cr->resolve(creds, &cc)) {
256                     bool good=false;
257                     SignatureValidator sigValidator;
258                     for (vector<const Credential*>::const_iterator i = creds.begin(); i != creds.end(); ++i) {
259                         try {
260                             sigValidator.setCredential(*i);
261                             sigValidator.validate(signable->getSignature());
262                             log.info("successful signature verification");
263                             good = true;
264                             break;
265                         }
266                         catch (exception& e) {
267                             log.info("error trying verification key: %s", e.what());
268                         }
269                     }
270                     if (!good)
271                         throw SignatureException("CredentialResolver did not supply a successful verification key.");
272                 }
273                 else {
274                     throw SignatureException("CredentialResolver did not supply any verification keys.");
275                 }
276             }
277             else {
278                 // TrustEngine-based verification, so try and build the plugins.
279                 auto_ptr<TrustEngine> trust(buildPlugin(t_param, xmlconf.TrustEngineManager));
280                 SignatureTrustEngine* sigtrust = dynamic_cast<SignatureTrustEngine*>(trust.get());
281                 if (m_param && rname && issuer) {
282                     if (!protocol) {
283                         if (prot)
284                             protocol = XMLString::transcode(prot);
285                     }
286                     if (!protocol) {
287                         conf.term();
288                         cerr << "use of metadata option requires a protocol option" << endl;
289                         return -1;
290                     }
291                     auto_ptr<MetadataProvider> metadata(buildPlugin(m_param, conf.MetadataProviderManager));
292                     metadata->init();
293
294                     const XMLCh* ns = rns ? XMLString::transcode(rns) : samlconstants::SAML20MD_NS;
295                     auto_ptr_XMLCh n(rname);
296                     xmltooling::QName q(ns, n.get());
297
298                     Locker locker(metadata.get());
299                     MetadataProvider::Criteria mc(issuer, &q, protocol);
300                     pair<const EntityDescriptor*,const RoleDescriptor*> entity = metadata->getEntityDescriptor(mc);
301                     if (!entity.first)
302                         throw MetadataException("no metadata found for ($1)", params(1, issuer));
303                     else if (!entity.second)
304                         throw MetadataException("compatible role $1 not found for ($2)", params(2, q.toString().c_str(), issuer));
305
306                     MetadataCredentialCriteria mcc(*entity.second);
307                     if (sigtrust->validate(*signable->getSignature(), *metadata.get(), &mcc))
308                         log.info("successful signature verification");
309                     else
310                         throw SignatureException("Unable to verify signature with TrustEngine and supplied metadata.");
311                 }
312                 else {
313                     // Set up criteria.
314                     CredentialCriteria cc;
315                     cc.setUsage(Credential::SIGNING_CREDENTIAL);
316                     cc.setSignature(*(signable->getSignature()), CredentialCriteria::KEYINFO_EXTRACTION_KEY);
317                     if (issuer)
318                         cc.setPeerName(issuer);
319                     DummyCredentialResolver dummy;
320                     if (sigtrust->validate(*signable->getSignature(), dummy, &cc))
321                         log.info("successful signature verification");
322                     else
323                         throw SignatureException("Unable to verify signature with TrustEngine (no metadata supplied).");
324                 }
325             }
326         }
327         else {
328             // Build a resolver to supply a credential.
329             auto_ptr<CredentialResolver> cr(
330                 cr_param ? buildPlugin(cr_param, xmlconf.CredentialResolverManager) : buildSimpleResolver(key_param, cert_param)
331                 );
332             Locker locker(cr.get());
333             CredentialCriteria cc;
334             cc.setUsage(Credential::SIGNING_CREDENTIAL);
335             const Credential* cred = cr->resolve(&cc);
336             if (!cred)
337                 throw XMLSecurityException("Unable to resolve a signing credential.");
338
339             // Attach new signature.
340             Signature* sig = SignatureBuilder::buildSignature();
341             signable->setSignature(sig);
342
343             // Sign response while re-marshalling.
344             vector<Signature*> sigs(1,sig);
345             XMLHelper::serialize(signable->marshall((DOMDocument*)NULL,&sigs,cred), cout);
346         }
347     }
348     catch(exception& e) {
349         log.errorStream() << "caught an exception: " << e.what() << logging::eol;
350         ret=-10;
351     }
352
353     conf.term();
354     return ret;
355 }