Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / common / ceph_crypto_cms.cc
1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3  *
4  * The contents of this file are subject to the Mozilla Public License Version
5  * 1.1 (the "License"); you may not use this file except in compliance with
6  * the License. You may obtain a copy of the License at
7  * http://www.mozilla.org/MPL/
8  *
9  * Software distributed under the License is distributed on an "AS IS" basis,
10  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11  * for the specific language governing rights and limitations under the
12  * License.
13  *
14  * The Original Code is the Netscape security libraries.
15  *
16  * The Initial Developer of the Original Code is
17  * Netscape Communications Corporation.
18  * Portions created by the Initial Developer are Copyright (C) 1994-2000
19  * the Initial Developer. All Rights Reserved.
20  *
21  * Contributor(s):
22  *
23  * Alternatively, the contents of this file may be used under the terms of
24  * either the GNU General Public License Version 2 or later (the "GPL"), or
25  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
26  * in which case the provisions of the GPL or the LGPL are applicable instead
27  * of those above. If you wish to allow use of your version of this file only
28  * under the terms of either the GPL or the LGPL, and not to allow others to
29  * use your version of this file under the terms of the MPL, indicate your
30  * decision by deleting the provisions above and replace them with the notice
31  * and other provisions required by the GPL or the LGPL. If you do not delete
32  * the provisions above, a recipient may use your version of this file under
33  * the terms of any one of the MPL, the GPL or the LGPL.
34  *
35  * ***** END LICENSE BLOCK ***** */
36
37
38 #include "common/config.h"
39 #include "common/debug.h"
40
41 #ifdef USE_NSS
42 #include <nspr.h>
43 #include <cert.h>
44 #include <nss.h>
45 #include <smime.h>
46 #endif
47
48 #define dout_subsys ceph_subsys_crypto
49
50 #ifndef USE_NSS
51 int ceph_decode_cms(CephContext *cct, bufferlist& cms_bl, bufferlist& decoded_bl)
52 {
53   return -ENOTSUP;
54 }
55
56 #else
57
58 static int cms_verbose = 0;
59
60 static SECStatus
61 DigestFile(PLArenaPool *poolp, SECItem ***digests, SECItem *input,
62            SECAlgorithmID **algids)
63 {
64     NSSCMSDigestContext *digcx;
65     SECStatus rv;
66
67     digcx = NSS_CMSDigestContext_StartMultiple(algids);
68     if (digcx == NULL)
69         return SECFailure;
70
71     NSS_CMSDigestContext_Update(digcx, input->data, input->len);
72
73     rv = NSS_CMSDigestContext_FinishMultiple(digcx, poolp, digests);
74     return rv;
75 }
76
77
78 struct optionsStr {
79     SECCertUsage certUsage;
80     CERTCertDBHandle *certHandle;
81 };
82
83 struct decodeOptionsStr {
84     struct optionsStr *options;
85     SECItem            content;
86     int headerLevel;
87     PRBool suppressContent;
88     NSSCMSGetDecryptKeyCallback dkcb;
89     PK11SymKey *bulkkey;
90     PRBool      keepCerts;
91 };
92
93 static NSSCMSMessage *
94 decode(CephContext *cct, SECItem *input, const struct decodeOptionsStr *decodeOptions, bufferlist& out)
95 {
96     NSSCMSDecoderContext *dcx;
97     SECStatus rv;
98     NSSCMSMessage *cmsg;
99     int nlevels, i;
100     SECItem sitem;
101     bufferptr bp;
102     SECItem *item;
103
104     memset(&sitem, 0, sizeof(sitem));
105
106     PORT_SetError(0);
107     dcx = NSS_CMSDecoder_Start(NULL, 
108                                NULL, NULL,         /* content callback     */
109                                NULL, NULL,         /* password callback    */
110                                decodeOptions->dkcb, /* decrypt key callback */
111                                decodeOptions->bulkkey);
112     if (dcx == NULL) {
113         ldout(cct, 0) << "ERROR: failed to set up message decoder" << dendl;
114         return NULL;
115     }
116     rv = NSS_CMSDecoder_Update(dcx, (char *)input->data, input->len);
117     if (rv != SECSuccess) {
118         ldout(cct, 0) << "ERROR: failed to decode message" << dendl;
119         NSS_CMSDecoder_Cancel(dcx);
120         return NULL;
121     }
122     cmsg = NSS_CMSDecoder_Finish(dcx);
123     if (cmsg == NULL) {
124         ldout(cct, 0) << "ERROR: failed to decode message" << dendl;
125         return NULL;
126     }
127
128     if (decodeOptions->headerLevel >= 0) {
129         ldout(cct, 20) << "SMIME: " << dendl;
130     }
131
132     nlevels = NSS_CMSMessage_ContentLevelCount(cmsg);
133     for (i = 0; i < nlevels; i++) {
134         NSSCMSContentInfo *cinfo;
135         SECOidTag typetag;
136
137         cinfo = NSS_CMSMessage_ContentLevel(cmsg, i);
138         typetag = NSS_CMSContentInfo_GetContentTypeTag(cinfo);
139
140         ldout(cct, 20) << "level=" << decodeOptions->headerLevel << "." << nlevels - i << dendl;
141
142         switch (typetag) {
143         case SEC_OID_PKCS7_SIGNED_DATA:
144           {
145             NSSCMSSignedData *sigd = NULL;
146             SECItem **digests;
147             int nsigners;
148             int j;
149
150             if (decodeOptions->headerLevel >= 0)
151                 ldout(cct, 20) << "type=signedData; " << dendl;
152             sigd = (NSSCMSSignedData *)NSS_CMSContentInfo_GetContent(cinfo);
153             if (sigd == NULL) {
154                 ldout(cct, 0) << "ERROR: signedData component missing" << dendl;
155                 goto loser;
156             }
157
158             /* if we have a content file, but no digests for this signedData */
159             if (decodeOptions->content.data != NULL && 
160                 !NSS_CMSSignedData_HasDigests(sigd)) {
161                 PLArenaPool     *poolp;
162                 SECAlgorithmID **digestalgs;
163
164                 /* detached content: grab content file */
165                 sitem = decodeOptions->content;
166
167                 if ((poolp = PORT_NewArena(1024)) == NULL) {
168                     ldout(cct, 0) << "ERROR: Out of memory" << dendl;
169                     goto loser;
170                 }
171                 digestalgs = NSS_CMSSignedData_GetDigestAlgs(sigd);
172                 if (DigestFile (poolp, &digests, &sitem, digestalgs) 
173                       != SECSuccess) {
174                     ldout(cct, 0) << "ERROR: problem computing message digest" << dendl;
175                     PORT_FreeArena(poolp, PR_FALSE);
176                     goto loser;
177                 }
178                 if (NSS_CMSSignedData_SetDigests(sigd, digestalgs, digests) 
179                     != SECSuccess) {
180                     ldout(cct, 0) << "ERROR: problem setting message digests" << dendl;
181                     PORT_FreeArena(poolp, PR_FALSE);
182                     goto loser;
183                 }
184                 PORT_FreeArena(poolp, PR_FALSE);
185             }
186
187             /* import the certificates */
188             if (NSS_CMSSignedData_ImportCerts(sigd, 
189                                            decodeOptions->options->certHandle, 
190                                            decodeOptions->options->certUsage, 
191                                            decodeOptions->keepCerts) 
192                   != SECSuccess) {
193                 ldout(cct, 0) << "ERROR: cert import failed" << dendl;
194                 goto loser;
195             }
196
197             /* find out about signers */
198             nsigners = NSS_CMSSignedData_SignerInfoCount(sigd);
199             if (decodeOptions->headerLevel >= 0)
200                 ldout(cct, 20) << "nsigners=" << nsigners << dendl;
201             if (nsigners == 0) {
202                 /* Might be a cert transport message
203                 ** or might be an invalid message, such as a QA test message
204                 ** or a message from an attacker.
205                 */
206                 SECStatus rv;
207                 rv = NSS_CMSSignedData_VerifyCertsOnly(sigd, 
208                                             decodeOptions->options->certHandle, 
209                                             decodeOptions->options->certUsage);
210                 if (rv != SECSuccess) {
211                     ldout(cct, 0) << "ERROR: Verify certs-only failed!" << dendl;
212                     goto loser;
213                 }
214                 return cmsg;
215             }
216
217             /* still no digests? */
218             if (!NSS_CMSSignedData_HasDigests(sigd)) {
219                 ldout(cct, 0) << "ERROR: no message digests" << dendl;
220                 goto loser;
221             }
222
223             for (j = 0; j < nsigners; j++) {
224                 const char * svs;
225                 NSSCMSSignerInfo *si;
226                 NSSCMSVerificationStatus vs;
227                 SECStatus bad;
228
229                 si = NSS_CMSSignedData_GetSignerInfo(sigd, j);
230                 if (decodeOptions->headerLevel >= 0) {
231                     char *signercn;
232                     static char empty[] = { "" };
233
234                     signercn = NSS_CMSSignerInfo_GetSignerCommonName(si);
235                     if (signercn == NULL)
236                         signercn = empty;
237                     ldout(cct, 20) << "\t\tsigner" << j << ".id=" << signercn << dendl;
238                     if (signercn != empty)
239                         PORT_Free(signercn);
240                 }
241                 bad = NSS_CMSSignedData_VerifySignerInfo(sigd, j, 
242                                            decodeOptions->options->certHandle, 
243                                            decodeOptions->options->certUsage);
244                 vs  = NSS_CMSSignerInfo_GetVerificationStatus(si);
245                 svs = NSS_CMSUtil_VerificationStatusToString(vs);
246                 if (decodeOptions->headerLevel >= 0) {
247                     ldout(cct, 20) << "signer" << j << "status=" << svs << dendl;
248                     /* goto loser ? */
249                 } else if (bad) {
250                     ldout(cct, 0) << "ERROR: signer " << j << " status = " << svs << dendl;
251                     goto loser;
252                 }
253             }
254           }
255           break;
256         case SEC_OID_PKCS7_ENVELOPED_DATA:
257           {
258             NSSCMSEnvelopedData *envd;
259             if (decodeOptions->headerLevel >= 0)
260                 ldout(cct, 20) << "type=envelopedData; " << dendl;
261             envd = (NSSCMSEnvelopedData *)NSS_CMSContentInfo_GetContent(cinfo);
262             if (envd == NULL) {
263                 ldout(cct, 0) << "ERROR: envelopedData component missing" << dendl;
264                 goto loser;
265             }
266           }
267           break;
268         case SEC_OID_PKCS7_ENCRYPTED_DATA:
269           {
270             NSSCMSEncryptedData *encd;
271             if (decodeOptions->headerLevel >= 0)
272                 ldout(cct, 20) << "type=encryptedData; " << dendl;
273             encd = (NSSCMSEncryptedData *)NSS_CMSContentInfo_GetContent(cinfo);
274             if (encd == NULL) {
275                 ldout(cct, 0) << "ERROR: encryptedData component missing" << dendl;
276                 goto loser;
277             }
278           }
279           break;
280         case SEC_OID_PKCS7_DATA:
281             if (decodeOptions->headerLevel >= 0)
282                 ldout(cct, 20) << "type=data; " << dendl;
283             break;
284         default:
285             break;
286         }
287     }
288
289     item = (sitem.data ? &sitem : NSS_CMSMessage_GetContent(cmsg));
290     out.append((char *)item->data, item->len);
291     return cmsg;
292
293 loser:
294     if (cmsg)
295         NSS_CMSMessage_Destroy(cmsg);
296     return NULL;
297 }
298
299 int ceph_decode_cms(CephContext *cct, bufferlist& cms_bl, bufferlist& decoded_bl)
300 {
301     NSSCMSMessage *cmsg = NULL;
302     struct decodeOptionsStr decodeOptions = { };
303     struct optionsStr options;
304     SECItem input;
305
306     memset(&options, 0, sizeof(options));
307     memset(&input, 0, sizeof(input));
308
309     input.data = (unsigned char *)cms_bl.c_str();
310     input.len = cms_bl.length();
311
312     decodeOptions.content.data = NULL;
313     decodeOptions.content.len  = 0;
314     decodeOptions.suppressContent = PR_FALSE;
315     decodeOptions.headerLevel = -1;
316     decodeOptions.keepCerts = PR_FALSE;
317     options.certUsage = certUsageEmailSigner;
318
319     options.certHandle = CERT_GetDefaultCertDB();
320     if (!options.certHandle) {
321         ldout(cct, 0) << "ERROR: No default cert DB" << dendl;
322         return -EIO;
323     }
324     if (cms_verbose) {
325         fprintf(stderr, "Got default certdb\n");
326     }
327
328     decodeOptions.options = &options;
329
330     int ret = 0;
331
332     cmsg = decode(cct, &input, &decodeOptions, decoded_bl);
333     if (!cmsg) {
334         ldout(cct, 0) << "ERROR: problem decoding" << dendl;
335         ret = -EINVAL;
336     }
337
338     if (cmsg)
339         NSS_CMSMessage_Destroy(cmsg);
340
341     SECITEM_FreeItem(&decodeOptions.content, PR_FALSE);
342
343     return ret;
344 }
345 #endif