155714Skris/* crypto/pem/pem_lib.c */
255714Skris/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
355714Skris * All rights reserved.
455714Skris *
555714Skris * This package is an SSL implementation written
655714Skris * by Eric Young (eay@cryptsoft.com).
755714Skris * The implementation was written so as to conform with Netscapes SSL.
8296341Sdelphij *
955714Skris * This library is free for commercial and non-commercial use as long as
1055714Skris * the following conditions are aheared to.  The following conditions
1155714Skris * apply to all code found in this distribution, be it the RC4, RSA,
1255714Skris * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
1355714Skris * included with this distribution is covered by the same copyright terms
1455714Skris * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15296341Sdelphij *
1655714Skris * Copyright remains Eric Young's, and as such any Copyright notices in
1755714Skris * the code are not to be removed.
1855714Skris * If this package is used in a product, Eric Young should be given attribution
1955714Skris * as the author of the parts of the library used.
2055714Skris * This can be in the form of a textual message at program startup or
2155714Skris * in documentation (online or textual) provided with the package.
22296341Sdelphij *
2355714Skris * Redistribution and use in source and binary forms, with or without
2455714Skris * modification, are permitted provided that the following conditions
2555714Skris * are met:
2655714Skris * 1. Redistributions of source code must retain the copyright
2755714Skris *    notice, this list of conditions and the following disclaimer.
2855714Skris * 2. Redistributions in binary form must reproduce the above copyright
2955714Skris *    notice, this list of conditions and the following disclaimer in the
3055714Skris *    documentation and/or other materials provided with the distribution.
3155714Skris * 3. All advertising materials mentioning features or use of this software
3255714Skris *    must display the following acknowledgement:
3355714Skris *    "This product includes cryptographic software written by
3455714Skris *     Eric Young (eay@cryptsoft.com)"
3555714Skris *    The word 'cryptographic' can be left out if the rouines from the library
3655714Skris *    being used are not cryptographic related :-).
37296341Sdelphij * 4. If you include any Windows specific code (or a derivative thereof) from
3855714Skris *    the apps directory (application code) you must include an acknowledgement:
3955714Skris *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40296341Sdelphij *
4155714Skris * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
4255714Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4355714Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4455714Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4555714Skris * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4655714Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4755714Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4855714Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4955714Skris * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
5055714Skris * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
5155714Skris * SUCH DAMAGE.
52296341Sdelphij *
5355714Skris * The licence and distribution terms for any publically available version or
5455714Skris * derivative of this code cannot be changed.  i.e. this code cannot simply be
5555714Skris * copied and put under another distribution licence
5655714Skris * [including the GNU Public Licence.]
5755714Skris */
5855714Skris
5955714Skris#include <stdio.h>
60238405Sjkim#include <ctype.h>
6155714Skris#include "cryptlib.h"
6255714Skris#include <openssl/buffer.h>
6355714Skris#include <openssl/objects.h>
6455714Skris#include <openssl/evp.h>
6555714Skris#include <openssl/rand.h>
6655714Skris#include <openssl/x509.h>
6755714Skris#include <openssl/pem.h>
6855714Skris#include <openssl/pkcs12.h>
69238405Sjkim#include "asn1_locl.h"
70109998Smarkm#ifndef OPENSSL_NO_DES
71296341Sdelphij# include <openssl/des.h>
7255714Skris#endif
73238405Sjkim#ifndef OPENSSL_NO_ENGINE
74296341Sdelphij# include <openssl/engine.h>
75238405Sjkim#endif
7655714Skris
77296341Sdelphijconst char PEM_version[] = "PEM" OPENSSL_VERSION_PTEXT;
7855714Skris
79296341Sdelphij#define MIN_LENGTH      4
8055714Skris
81296341Sdelphijstatic int load_iv(char **fromp, unsigned char *to, int num);
8259191Skrisstatic int check_pem(const char *nm, const char *name);
83238405Sjkimint pem_check_suffix(const char *pem_str, const char *suffix);
8455714Skris
85109998Smarkmint PEM_def_callback(char *buf, int num, int w, void *key)
86296341Sdelphij{
87109998Smarkm#ifdef OPENSSL_NO_FP_API
88296341Sdelphij    /*
89296341Sdelphij     * We should not ever call the default callback routine from windows.
90296341Sdelphij     */
91296341Sdelphij    PEMerr(PEM_F_PEM_DEF_CALLBACK, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
92296341Sdelphij    return (-1);
9355714Skris#else
94296341Sdelphij    int i, j;
95296341Sdelphij    const char *prompt;
96296341Sdelphij    if (key) {
97296341Sdelphij        i = strlen(key);
98296341Sdelphij        i = (i > num) ? num : i;
99296341Sdelphij        memcpy(buf, key, i);
100296341Sdelphij        return (i);
101296341Sdelphij    }
10255714Skris
103296341Sdelphij    prompt = EVP_get_pw_prompt();
104296341Sdelphij    if (prompt == NULL)
105296341Sdelphij        prompt = "Enter PEM pass phrase:";
10655714Skris
107296341Sdelphij    for (;;) {
108296341Sdelphij        i = EVP_read_pw_string_min(buf, MIN_LENGTH, num, prompt, w);
109296341Sdelphij        if (i != 0) {
110296341Sdelphij            PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
111296341Sdelphij            memset(buf, 0, (unsigned int)num);
112296341Sdelphij            return (-1);
113296341Sdelphij        }
114296341Sdelphij        j = strlen(buf);
115296341Sdelphij        if (j < MIN_LENGTH) {
116296341Sdelphij            fprintf(stderr,
117296341Sdelphij                    "phrase is too short, needs to be at least %d chars\n",
118296341Sdelphij                    MIN_LENGTH);
119296341Sdelphij        } else
120296341Sdelphij            break;
121296341Sdelphij    }
122296341Sdelphij    return (j);
12355714Skris#endif
124296341Sdelphij}
12555714Skris
12655714Skrisvoid PEM_proc_type(char *buf, int type)
127296341Sdelphij{
128296341Sdelphij    const char *str;
12955714Skris
130296341Sdelphij    if (type == PEM_TYPE_ENCRYPTED)
131296341Sdelphij        str = "ENCRYPTED";
132296341Sdelphij    else if (type == PEM_TYPE_MIC_CLEAR)
133296341Sdelphij        str = "MIC-CLEAR";
134296341Sdelphij    else if (type == PEM_TYPE_MIC_ONLY)
135296341Sdelphij        str = "MIC-ONLY";
136296341Sdelphij    else
137296341Sdelphij        str = "BAD-TYPE";
13855714Skris
139296341Sdelphij    BUF_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE);
140296341Sdelphij    BUF_strlcat(buf, str, PEM_BUFSIZE);
141296341Sdelphij    BUF_strlcat(buf, "\n", PEM_BUFSIZE);
142296341Sdelphij}
143296341Sdelphij
14455714Skrisvoid PEM_dek_info(char *buf, const char *type, int len, char *str)
145296341Sdelphij{
146296341Sdelphij    static const unsigned char map[17] = "0123456789ABCDEF";
147296341Sdelphij    long i;
148296341Sdelphij    int j;
14955714Skris
150296341Sdelphij    BUF_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
151296341Sdelphij    BUF_strlcat(buf, type, PEM_BUFSIZE);
152296341Sdelphij    BUF_strlcat(buf, ",", PEM_BUFSIZE);
153296341Sdelphij    j = strlen(buf);
154296341Sdelphij    if (j + (len * 2) + 1 > PEM_BUFSIZE)
155296341Sdelphij        return;
156296341Sdelphij    for (i = 0; i < len; i++) {
157296341Sdelphij        buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
158296341Sdelphij        buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
159296341Sdelphij    }
160296341Sdelphij    buf[j + i * 2] = '\n';
161296341Sdelphij    buf[j + i * 2 + 1] = '\0';
162296341Sdelphij}
16355714Skris
164109998Smarkm#ifndef OPENSSL_NO_FP_API
165160814Ssimonvoid *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
166296341Sdelphij                    pem_password_cb *cb, void *u)
167296341Sdelphij{
168296341Sdelphij    BIO *b;
169296341Sdelphij    void *ret;
17055714Skris
171296341Sdelphij    if ((b = BIO_new(BIO_s_file())) == NULL) {
172296341Sdelphij        PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB);
173296341Sdelphij        return (0);
174296341Sdelphij    }
175296341Sdelphij    BIO_set_fp(b, fp, BIO_NOCLOSE);
176296341Sdelphij    ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
177296341Sdelphij    BIO_free(b);
178296341Sdelphij    return (ret);
179296341Sdelphij}
18055714Skris#endif
18155714Skris
18259191Skrisstatic int check_pem(const char *nm, const char *name)
18359191Skris{
184296341Sdelphij    /* Normal matching nm and name */
185296341Sdelphij    if (!strcmp(nm, name))
186296341Sdelphij        return 1;
18759191Skris
188296341Sdelphij    /* Make PEM_STRING_EVP_PKEY match any private key */
18959191Skris
190296341Sdelphij    if (!strcmp(name, PEM_STRING_EVP_PKEY)) {
191296341Sdelphij        int slen;
192296341Sdelphij        const EVP_PKEY_ASN1_METHOD *ameth;
193296341Sdelphij        if (!strcmp(nm, PEM_STRING_PKCS8))
194296341Sdelphij            return 1;
195296341Sdelphij        if (!strcmp(nm, PEM_STRING_PKCS8INF))
196296341Sdelphij            return 1;
197296341Sdelphij        slen = pem_check_suffix(nm, "PRIVATE KEY");
198296341Sdelphij        if (slen > 0) {
199296341Sdelphij            /*
200296341Sdelphij             * NB: ENGINE implementations wont contain a deprecated old
201296341Sdelphij             * private key decode function so don't look for them.
202296341Sdelphij             */
203296341Sdelphij            ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
204296341Sdelphij            if (ameth && ameth->old_priv_decode)
205296341Sdelphij                return 1;
206296341Sdelphij        }
207296341Sdelphij        return 0;
208296341Sdelphij    }
20959191Skris
210296341Sdelphij    if (!strcmp(name, PEM_STRING_PARAMETERS)) {
211296341Sdelphij        int slen;
212296341Sdelphij        const EVP_PKEY_ASN1_METHOD *ameth;
213296341Sdelphij        slen = pem_check_suffix(nm, "PARAMETERS");
214296341Sdelphij        if (slen > 0) {
215296341Sdelphij            ENGINE *e;
216296341Sdelphij            ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
217296341Sdelphij            if (ameth) {
218296341Sdelphij                int r;
219296341Sdelphij                if (ameth->param_decode)
220296341Sdelphij                    r = 1;
221296341Sdelphij                else
222296341Sdelphij                    r = 0;
223238405Sjkim#ifndef OPENSSL_NO_ENGINE
224296341Sdelphij                if (e)
225296341Sdelphij                    ENGINE_finish(e);
226238405Sjkim#endif
227296341Sdelphij                return r;
228296341Sdelphij            }
229296341Sdelphij        }
230296341Sdelphij        return 0;
231296341Sdelphij    }
23259191Skris
233296341Sdelphij    /* Permit older strings */
23459191Skris
235296341Sdelphij    if (!strcmp(nm, PEM_STRING_X509_OLD) && !strcmp(name, PEM_STRING_X509))
236296341Sdelphij        return 1;
23759191Skris
238296341Sdelphij    if (!strcmp(nm, PEM_STRING_X509_REQ_OLD) &&
239296341Sdelphij        !strcmp(name, PEM_STRING_X509_REQ))
240296341Sdelphij        return 1;
24159191Skris
242296341Sdelphij    /* Allow normal certs to be read as trusted certs */
243296341Sdelphij    if (!strcmp(nm, PEM_STRING_X509) &&
244296341Sdelphij        !strcmp(name, PEM_STRING_X509_TRUSTED))
245296341Sdelphij        return 1;
24659191Skris
247296341Sdelphij    if (!strcmp(nm, PEM_STRING_X509_OLD) &&
248296341Sdelphij        !strcmp(name, PEM_STRING_X509_TRUSTED))
249296341Sdelphij        return 1;
25059191Skris
251296341Sdelphij    /* Some CAs use PKCS#7 with CERTIFICATE headers */
252296341Sdelphij    if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_PKCS7))
253296341Sdelphij        return 1;
25459191Skris
255296341Sdelphij    if (!strcmp(nm, PEM_STRING_PKCS7_SIGNED) &&
256296341Sdelphij        !strcmp(name, PEM_STRING_PKCS7))
257296341Sdelphij        return 1;
258194206Ssimon
259238405Sjkim#ifndef OPENSSL_NO_CMS
260296341Sdelphij    if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_CMS))
261296341Sdelphij        return 1;
262296341Sdelphij    /* Allow CMS to be read from PKCS#7 headers */
263296341Sdelphij    if (!strcmp(nm, PEM_STRING_PKCS7) && !strcmp(name, PEM_STRING_CMS))
264296341Sdelphij        return 1;
265238405Sjkim#endif
266238405Sjkim
267296341Sdelphij    return 0;
26859191Skris}
26959191Skris
270296341Sdelphijint PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
271296341Sdelphij                       const char *name, BIO *bp, pem_password_cb *cb,
272296341Sdelphij                       void *u)
273296341Sdelphij{
274296341Sdelphij    EVP_CIPHER_INFO cipher;
275296341Sdelphij    char *nm = NULL, *header = NULL;
276296341Sdelphij    unsigned char *data = NULL;
277296341Sdelphij    long len;
278296341Sdelphij    int ret = 0;
27955714Skris
280296341Sdelphij    for (;;) {
281296341Sdelphij        if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
282296341Sdelphij            if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
283296341Sdelphij                ERR_add_error_data(2, "Expecting: ", name);
284296341Sdelphij            return 0;
285296341Sdelphij        }
286296341Sdelphij        if (check_pem(nm, name))
287296341Sdelphij            break;
288296341Sdelphij        OPENSSL_free(nm);
289296341Sdelphij        OPENSSL_free(header);
290296341Sdelphij        OPENSSL_free(data);
291296341Sdelphij    }
292296341Sdelphij    if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
293296341Sdelphij        goto err;
294296341Sdelphij    if (!PEM_do_header(&cipher, data, &len, cb, u))
295296341Sdelphij        goto err;
296109998Smarkm
297296341Sdelphij    *pdata = data;
298296341Sdelphij    *plen = len;
299109998Smarkm
300296341Sdelphij    if (pnm)
301296341Sdelphij        *pnm = nm;
302109998Smarkm
303296341Sdelphij    ret = 1;
304109998Smarkm
305296341Sdelphij err:
306296341Sdelphij    if (!ret || !pnm)
307296341Sdelphij        OPENSSL_free(nm);
308296341Sdelphij    OPENSSL_free(header);
309296341Sdelphij    if (!ret)
310296341Sdelphij        OPENSSL_free(data);
311296341Sdelphij    return ret;
312296341Sdelphij}
31355714Skris
314109998Smarkm#ifndef OPENSSL_NO_FP_API
315160814Ssimonint PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
316296341Sdelphij                   void *x, const EVP_CIPHER *enc, unsigned char *kstr,
317296341Sdelphij                   int klen, pem_password_cb *callback, void *u)
318296341Sdelphij{
319296341Sdelphij    BIO *b;
320296341Sdelphij    int ret;
32155714Skris
322296341Sdelphij    if ((b = BIO_new(BIO_s_file())) == NULL) {
323296341Sdelphij        PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
324296341Sdelphij        return (0);
325296341Sdelphij    }
326296341Sdelphij    BIO_set_fp(b, fp, BIO_NOCLOSE);
327296341Sdelphij    ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
328296341Sdelphij    BIO_free(b);
329296341Sdelphij    return (ret);
330296341Sdelphij}
33155714Skris#endif
33255714Skris
333160814Ssimonint PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
334296341Sdelphij                       void *x, const EVP_CIPHER *enc, unsigned char *kstr,
335296341Sdelphij                       int klen, pem_password_cb *callback, void *u)
336296341Sdelphij{
337296341Sdelphij    EVP_CIPHER_CTX ctx;
338296341Sdelphij    int dsize = 0, i, j, ret = 0;
339296341Sdelphij    unsigned char *p, *data = NULL;
340296341Sdelphij    const char *objstr = NULL;
341296341Sdelphij    char buf[PEM_BUFSIZE];
342296341Sdelphij    unsigned char key[EVP_MAX_KEY_LENGTH];
343296341Sdelphij    unsigned char iv[EVP_MAX_IV_LENGTH];
34455714Skris
345296341Sdelphij    if (enc != NULL) {
346296341Sdelphij        objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
347296341Sdelphij        if (objstr == NULL) {
348296341Sdelphij            PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
349296341Sdelphij            goto err;
350296341Sdelphij        }
351296341Sdelphij    }
35255714Skris
353296341Sdelphij    if ((dsize = i2d(x, NULL)) < 0) {
354296341Sdelphij        PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
355296341Sdelphij        dsize = 0;
356296341Sdelphij        goto err;
357296341Sdelphij    }
358296341Sdelphij    /* dzise + 8 bytes are needed */
359296341Sdelphij    /* actually it needs the cipher block size extra... */
360296341Sdelphij    data = (unsigned char *)OPENSSL_malloc((unsigned int)dsize + 20);
361296341Sdelphij    if (data == NULL) {
362296341Sdelphij        PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
363296341Sdelphij        goto err;
364296341Sdelphij    }
365296341Sdelphij    p = data;
366296341Sdelphij    i = i2d(x, &p);
367296341Sdelphij
368296341Sdelphij    if (enc != NULL) {
369296341Sdelphij        if (kstr == NULL) {
370296341Sdelphij            if (callback == NULL)
371296341Sdelphij                klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
372296341Sdelphij            else
373296341Sdelphij                klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
374296341Sdelphij            if (klen <= 0) {
375296341Sdelphij                PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY);
376296341Sdelphij                goto err;
377296341Sdelphij            }
37855714Skris#ifdef CHARSET_EBCDIC
379296341Sdelphij            /* Convert the pass phrase from EBCDIC */
380296341Sdelphij            ebcdic2ascii(buf, buf, klen);
38155714Skris#endif
382296341Sdelphij            kstr = (unsigned char *)buf;
383296341Sdelphij        }
384296341Sdelphij        RAND_add(data, i, 0);   /* put in the RSA key. */
385296341Sdelphij        OPENSSL_assert(enc->iv_len <= (int)sizeof(iv));
386296341Sdelphij        if (RAND_pseudo_bytes(iv, enc->iv_len) < 0) /* Generate a salt */
387296341Sdelphij            goto err;
388296341Sdelphij        /*
389296341Sdelphij         * The 'iv' is used as the iv and as a salt.  It is NOT taken from
390296341Sdelphij         * the BytesToKey function
391296341Sdelphij         */
392296341Sdelphij        if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
393296341Sdelphij            goto err;
39455714Skris
395296341Sdelphij        if (kstr == (unsigned char *)buf)
396296341Sdelphij            OPENSSL_cleanse(buf, PEM_BUFSIZE);
39755714Skris
398296341Sdelphij        OPENSSL_assert(strlen(objstr) + 23 + 2 * enc->iv_len + 13 <=
399296341Sdelphij                       sizeof buf);
400109998Smarkm
401296341Sdelphij        buf[0] = '\0';
402296341Sdelphij        PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
403296341Sdelphij        PEM_dek_info(buf, objstr, enc->iv_len, (char *)iv);
404296341Sdelphij        /* k=strlen(buf); */
405109998Smarkm
406296341Sdelphij        EVP_CIPHER_CTX_init(&ctx);
407296341Sdelphij        ret = 1;
408296341Sdelphij        if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv)
409296341Sdelphij            || !EVP_EncryptUpdate(&ctx, data, &j, data, i)
410296341Sdelphij            || !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i))
411296341Sdelphij            ret = 0;
412296341Sdelphij        EVP_CIPHER_CTX_cleanup(&ctx);
413296341Sdelphij        if (ret == 0)
414296341Sdelphij            goto err;
415296341Sdelphij        i += j;
416296341Sdelphij    } else {
417296341Sdelphij        ret = 1;
418296341Sdelphij        buf[0] = '\0';
419296341Sdelphij    }
420296341Sdelphij    i = PEM_write_bio(bp, name, buf, data, i);
421296341Sdelphij    if (i <= 0)
422296341Sdelphij        ret = 0;
423296341Sdelphij err:
424296341Sdelphij    OPENSSL_cleanse(key, sizeof(key));
425296341Sdelphij    OPENSSL_cleanse(iv, sizeof(iv));
426296341Sdelphij    OPENSSL_cleanse((char *)&ctx, sizeof(ctx));
427296341Sdelphij    OPENSSL_cleanse(buf, PEM_BUFSIZE);
428296341Sdelphij    if (data != NULL) {
429296341Sdelphij        OPENSSL_cleanse(data, (unsigned int)dsize);
430296341Sdelphij        OPENSSL_free(data);
431296341Sdelphij    }
432296341Sdelphij    return (ret);
433296341Sdelphij}
43455714Skris
43555714Skrisint PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
436296341Sdelphij                  pem_password_cb *callback, void *u)
437296341Sdelphij{
438296341Sdelphij    int i = 0, j, o, klen;
439296341Sdelphij    long len;
440296341Sdelphij    EVP_CIPHER_CTX ctx;
441296341Sdelphij    unsigned char key[EVP_MAX_KEY_LENGTH];
442296341Sdelphij    char buf[PEM_BUFSIZE];
44355714Skris
444296341Sdelphij    len = *plen;
44555714Skris
446296341Sdelphij    if (cipher->cipher == NULL)
447296341Sdelphij        return (1);
448296341Sdelphij    if (callback == NULL)
449296341Sdelphij        klen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
450296341Sdelphij    else
451296341Sdelphij        klen = callback(buf, PEM_BUFSIZE, 0, u);
452296341Sdelphij    if (klen <= 0) {
453296341Sdelphij        PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
454296341Sdelphij        return (0);
455296341Sdelphij    }
45655714Skris#ifdef CHARSET_EBCDIC
457296341Sdelphij    /* Convert the pass phrase from EBCDIC */
458296341Sdelphij    ebcdic2ascii(buf, buf, klen);
45955714Skris#endif
46055714Skris
461296341Sdelphij    if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
462296341Sdelphij                        (unsigned char *)buf, klen, 1, key, NULL))
463296341Sdelphij        return 0;
46455714Skris
465296341Sdelphij    j = (int)len;
466296341Sdelphij    EVP_CIPHER_CTX_init(&ctx);
467296341Sdelphij    o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
468296341Sdelphij    if (o)
469296341Sdelphij        o = EVP_DecryptUpdate(&ctx, data, &i, data, j);
470296341Sdelphij    if (o)
471296341Sdelphij        o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j);
472296341Sdelphij    EVP_CIPHER_CTX_cleanup(&ctx);
473296341Sdelphij    OPENSSL_cleanse((char *)buf, sizeof(buf));
474296341Sdelphij    OPENSSL_cleanse((char *)key, sizeof(key));
475296341Sdelphij    j += i;
476296341Sdelphij    if (!o) {
477296341Sdelphij        PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
478296341Sdelphij        return (0);
479296341Sdelphij    }
480296341Sdelphij    *plen = j;
481296341Sdelphij    return (1);
482296341Sdelphij}
48355714Skris
48455714Skrisint PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
485296341Sdelphij{
486296341Sdelphij    const EVP_CIPHER *enc = NULL;
487296341Sdelphij    char *p, c;
488296341Sdelphij    char **header_pp = &header;
48955714Skris
490296341Sdelphij    cipher->cipher = NULL;
491296341Sdelphij    if ((header == NULL) || (*header == '\0') || (*header == '\n'))
492296341Sdelphij        return (1);
493296341Sdelphij    if (strncmp(header, "Proc-Type: ", 11) != 0) {
494296341Sdelphij        PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
495296341Sdelphij        return (0);
496296341Sdelphij    }
497296341Sdelphij    header += 11;
498296341Sdelphij    if (*header != '4')
499296341Sdelphij        return (0);
500296341Sdelphij    header++;
501296341Sdelphij    if (*header != ',')
502296341Sdelphij        return (0);
503296341Sdelphij    header++;
504296341Sdelphij    if (strncmp(header, "ENCRYPTED", 9) != 0) {
505296341Sdelphij        PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
506296341Sdelphij        return (0);
507296341Sdelphij    }
508296341Sdelphij    for (; (*header != '\n') && (*header != '\0'); header++) ;
509296341Sdelphij    if (*header == '\0') {
510296341Sdelphij        PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
511296341Sdelphij        return (0);
512296341Sdelphij    }
513296341Sdelphij    header++;
514296341Sdelphij    if (strncmp(header, "DEK-Info: ", 10) != 0) {
515296341Sdelphij        PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
516296341Sdelphij        return (0);
517296341Sdelphij    }
518296341Sdelphij    header += 10;
51955714Skris
520296341Sdelphij    p = header;
521296341Sdelphij    for (;;) {
522296341Sdelphij        c = *header;
52355714Skris#ifndef CHARSET_EBCDIC
524296341Sdelphij        if (!(((c >= 'A') && (c <= 'Z')) || (c == '-') ||
525296341Sdelphij              ((c >= '0') && (c <= '9'))))
526296341Sdelphij            break;
52755714Skris#else
528296341Sdelphij        if (!(isupper(c) || (c == '-') || isdigit(c)))
529296341Sdelphij            break;
53055714Skris#endif
531296341Sdelphij        header++;
532296341Sdelphij    }
533296341Sdelphij    *header = '\0';
534296341Sdelphij    cipher->cipher = enc = EVP_get_cipherbyname(p);
535296341Sdelphij    *header = c;
536296341Sdelphij    header++;
53755714Skris
538296341Sdelphij    if (enc == NULL) {
539296341Sdelphij        PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION);
540296341Sdelphij        return (0);
541296341Sdelphij    }
542296341Sdelphij    if (!load_iv(header_pp, &(cipher->iv[0]), enc->iv_len))
543296341Sdelphij        return (0);
54455714Skris
545296341Sdelphij    return (1);
546296341Sdelphij}
54755714Skris
548160814Ssimonstatic int load_iv(char **fromp, unsigned char *to, int num)
549296341Sdelphij{
550296341Sdelphij    int v, i;
551296341Sdelphij    char *from;
55255714Skris
553296341Sdelphij    from = *fromp;
554296341Sdelphij    for (i = 0; i < num; i++)
555296341Sdelphij        to[i] = 0;
556296341Sdelphij    num *= 2;
557296341Sdelphij    for (i = 0; i < num; i++) {
558296341Sdelphij        if ((*from >= '0') && (*from <= '9'))
559296341Sdelphij            v = *from - '0';
560296341Sdelphij        else if ((*from >= 'A') && (*from <= 'F'))
561296341Sdelphij            v = *from - 'A' + 10;
562296341Sdelphij        else if ((*from >= 'a') && (*from <= 'f'))
563296341Sdelphij            v = *from - 'a' + 10;
564296341Sdelphij        else {
565296341Sdelphij            PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
566296341Sdelphij            return (0);
567296341Sdelphij        }
568296341Sdelphij        from++;
569296341Sdelphij        to[i / 2] |= v << (long)((!(i & 1)) * 4);
570296341Sdelphij    }
57155714Skris
572296341Sdelphij    *fromp = from;
573296341Sdelphij    return (1);
574296341Sdelphij}
57555714Skris
576109998Smarkm#ifndef OPENSSL_NO_FP_API
57755714Skrisint PEM_write(FILE *fp, char *name, char *header, unsigned char *data,
578296341Sdelphij              long len)
579296341Sdelphij{
580296341Sdelphij    BIO *b;
581296341Sdelphij    int ret;
58255714Skris
583296341Sdelphij    if ((b = BIO_new(BIO_s_file())) == NULL) {
584296341Sdelphij        PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
585296341Sdelphij        return (0);
586296341Sdelphij    }
587296341Sdelphij    BIO_set_fp(b, fp, BIO_NOCLOSE);
588296341Sdelphij    ret = PEM_write_bio(b, name, header, data, len);
589296341Sdelphij    BIO_free(b);
590296341Sdelphij    return (ret);
591296341Sdelphij}
59255714Skris#endif
59355714Skris
594296341Sdelphijint PEM_write_bio(BIO *bp, const char *name, char *header,
595296341Sdelphij                  unsigned char *data, long len)
596296341Sdelphij{
597296341Sdelphij    int nlen, n, i, j, outl;
598296341Sdelphij    unsigned char *buf = NULL;
599296341Sdelphij    EVP_ENCODE_CTX ctx;
600296341Sdelphij    int reason = ERR_R_BUF_LIB;
60155714Skris
602296341Sdelphij    EVP_EncodeInit(&ctx);
603296341Sdelphij    nlen = strlen(name);
60455714Skris
605296341Sdelphij    if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
606296341Sdelphij        (BIO_write(bp, name, nlen) != nlen) ||
607296341Sdelphij        (BIO_write(bp, "-----\n", 6) != 6))
608296341Sdelphij        goto err;
60955714Skris
610296341Sdelphij    i = strlen(header);
611296341Sdelphij    if (i > 0) {
612296341Sdelphij        if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
613296341Sdelphij            goto err;
614296341Sdelphij    }
61555714Skris
616296341Sdelphij    buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
617296341Sdelphij    if (buf == NULL) {
618296341Sdelphij        reason = ERR_R_MALLOC_FAILURE;
619296341Sdelphij        goto err;
620296341Sdelphij    }
621296341Sdelphij
622296341Sdelphij    i = j = 0;
623296341Sdelphij    while (len > 0) {
624296341Sdelphij        n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
625296341Sdelphij        EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n);
626296341Sdelphij        if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
627296341Sdelphij            goto err;
628296341Sdelphij        i += outl;
629296341Sdelphij        len -= n;
630296341Sdelphij        j += n;
631296341Sdelphij    }
632296341Sdelphij    EVP_EncodeFinal(&ctx, buf, &outl);
633296341Sdelphij    if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
634296341Sdelphij        goto err;
635296341Sdelphij    OPENSSL_cleanse(buf, PEM_BUFSIZE * 8);
636296341Sdelphij    OPENSSL_free(buf);
637296341Sdelphij    buf = NULL;
638296341Sdelphij    if ((BIO_write(bp, "-----END ", 9) != 9) ||
639296341Sdelphij        (BIO_write(bp, name, nlen) != nlen) ||
640296341Sdelphij        (BIO_write(bp, "-----\n", 6) != 6))
641296341Sdelphij        goto err;
642296341Sdelphij    return (i + outl);
643296341Sdelphij err:
644296341Sdelphij    if (buf) {
645296341Sdelphij        OPENSSL_cleanse(buf, PEM_BUFSIZE * 8);
646296341Sdelphij        OPENSSL_free(buf);
647296341Sdelphij    }
648296341Sdelphij    PEMerr(PEM_F_PEM_WRITE_BIO, reason);
649296341Sdelphij    return (0);
650296341Sdelphij}
651296341Sdelphij
652109998Smarkm#ifndef OPENSSL_NO_FP_API
65355714Skrisint PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
654296341Sdelphij             long *len)
655296341Sdelphij{
656296341Sdelphij    BIO *b;
657296341Sdelphij    int ret;
65855714Skris
659296341Sdelphij    if ((b = BIO_new(BIO_s_file())) == NULL) {
660296341Sdelphij        PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
661296341Sdelphij        return (0);
662296341Sdelphij    }
663296341Sdelphij    BIO_set_fp(b, fp, BIO_NOCLOSE);
664296341Sdelphij    ret = PEM_read_bio(b, name, header, data, len);
665296341Sdelphij    BIO_free(b);
666296341Sdelphij    return (ret);
667296341Sdelphij}
66855714Skris#endif
66955714Skris
67055714Skrisint PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
671296341Sdelphij                 long *len)
672296341Sdelphij{
673296341Sdelphij    EVP_ENCODE_CTX ctx;
674296341Sdelphij    int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
675296341Sdelphij    char buf[256];
676296341Sdelphij    BUF_MEM *nameB;
677296341Sdelphij    BUF_MEM *headerB;
678296341Sdelphij    BUF_MEM *dataB, *tmpB;
67955714Skris
680296341Sdelphij    nameB = BUF_MEM_new();
681296341Sdelphij    headerB = BUF_MEM_new();
682296341Sdelphij    dataB = BUF_MEM_new();
683296341Sdelphij    if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
684296341Sdelphij        BUF_MEM_free(nameB);
685296341Sdelphij        BUF_MEM_free(headerB);
686296341Sdelphij        BUF_MEM_free(dataB);
687296341Sdelphij        PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
688296341Sdelphij        return (0);
689296341Sdelphij    }
69055714Skris
691296341Sdelphij    buf[254] = '\0';
692296341Sdelphij    for (;;) {
693296341Sdelphij        i = BIO_gets(bp, buf, 254);
69455714Skris
695296341Sdelphij        if (i <= 0) {
696296341Sdelphij            PEMerr(PEM_F_PEM_READ_BIO, PEM_R_NO_START_LINE);
697296341Sdelphij            goto err;
698296341Sdelphij        }
69955714Skris
700296341Sdelphij        while ((i >= 0) && (buf[i] <= ' '))
701296341Sdelphij            i--;
702296341Sdelphij        buf[++i] = '\n';
703296341Sdelphij        buf[++i] = '\0';
70455714Skris
705296341Sdelphij        if (strncmp(buf, "-----BEGIN ", 11) == 0) {
706296341Sdelphij            i = strlen(&(buf[11]));
70755714Skris
708296341Sdelphij            if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0)
709296341Sdelphij                continue;
710296341Sdelphij            if (!BUF_MEM_grow(nameB, i + 9)) {
711296341Sdelphij                PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
712296341Sdelphij                goto err;
713296341Sdelphij            }
714296341Sdelphij            memcpy(nameB->data, &(buf[11]), i - 6);
715296341Sdelphij            nameB->data[i - 6] = '\0';
716296341Sdelphij            break;
717296341Sdelphij        }
718296341Sdelphij    }
719296341Sdelphij    hl = 0;
720296341Sdelphij    if (!BUF_MEM_grow(headerB, 256)) {
721296341Sdelphij        PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
722296341Sdelphij        goto err;
723296341Sdelphij    }
724296341Sdelphij    headerB->data[0] = '\0';
725296341Sdelphij    for (;;) {
726296341Sdelphij        i = BIO_gets(bp, buf, 254);
727296341Sdelphij        if (i <= 0)
728296341Sdelphij            break;
72955714Skris
730296341Sdelphij        while ((i >= 0) && (buf[i] <= ' '))
731296341Sdelphij            i--;
732296341Sdelphij        buf[++i] = '\n';
733296341Sdelphij        buf[++i] = '\0';
73455714Skris
735296341Sdelphij        if (buf[0] == '\n')
736296341Sdelphij            break;
737296341Sdelphij        if (!BUF_MEM_grow(headerB, hl + i + 9)) {
738296341Sdelphij            PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
739296341Sdelphij            goto err;
740296341Sdelphij        }
741296341Sdelphij        if (strncmp(buf, "-----END ", 9) == 0) {
742296341Sdelphij            nohead = 1;
743296341Sdelphij            break;
744296341Sdelphij        }
745296341Sdelphij        memcpy(&(headerB->data[hl]), buf, i);
746296341Sdelphij        headerB->data[hl + i] = '\0';
747296341Sdelphij        hl += i;
748296341Sdelphij    }
74955714Skris
750296341Sdelphij    bl = 0;
751296341Sdelphij    if (!BUF_MEM_grow(dataB, 1024)) {
752296341Sdelphij        PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
753296341Sdelphij        goto err;
754296341Sdelphij    }
755296341Sdelphij    dataB->data[0] = '\0';
756296341Sdelphij    if (!nohead) {
757296341Sdelphij        for (;;) {
758296341Sdelphij            i = BIO_gets(bp, buf, 254);
759296341Sdelphij            if (i <= 0)
760296341Sdelphij                break;
76155714Skris
762296341Sdelphij            while ((i >= 0) && (buf[i] <= ' '))
763296341Sdelphij                i--;
764296341Sdelphij            buf[++i] = '\n';
765296341Sdelphij            buf[++i] = '\0';
76655714Skris
767296341Sdelphij            if (i != 65)
768296341Sdelphij                end = 1;
769296341Sdelphij            if (strncmp(buf, "-----END ", 9) == 0)
770296341Sdelphij                break;
771296341Sdelphij            if (i > 65)
772296341Sdelphij                break;
773296341Sdelphij            if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
774296341Sdelphij                PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
775296341Sdelphij                goto err;
776296341Sdelphij            }
777296341Sdelphij            memcpy(&(dataB->data[bl]), buf, i);
778296341Sdelphij            dataB->data[bl + i] = '\0';
779296341Sdelphij            bl += i;
780296341Sdelphij            if (end) {
781296341Sdelphij                buf[0] = '\0';
782296341Sdelphij                i = BIO_gets(bp, buf, 254);
783296341Sdelphij                if (i <= 0)
784296341Sdelphij                    break;
78555714Skris
786296341Sdelphij                while ((i >= 0) && (buf[i] <= ' '))
787296341Sdelphij                    i--;
788296341Sdelphij                buf[++i] = '\n';
789296341Sdelphij                buf[++i] = '\0';
79055714Skris
791296341Sdelphij                break;
792296341Sdelphij            }
793296341Sdelphij        }
794296341Sdelphij    } else {
795296341Sdelphij        tmpB = headerB;
796296341Sdelphij        headerB = dataB;
797296341Sdelphij        dataB = tmpB;
798296341Sdelphij        bl = hl;
799296341Sdelphij    }
800296341Sdelphij    i = strlen(nameB->data);
801296341Sdelphij    if ((strncmp(buf, "-----END ", 9) != 0) ||
802296341Sdelphij        (strncmp(nameB->data, &(buf[9]), i) != 0) ||
803296341Sdelphij        (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
804296341Sdelphij        PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_END_LINE);
805296341Sdelphij        goto err;
806296341Sdelphij    }
80755714Skris
808296341Sdelphij    EVP_DecodeInit(&ctx);
809296341Sdelphij    i = EVP_DecodeUpdate(&ctx,
810296341Sdelphij                         (unsigned char *)dataB->data, &bl,
811296341Sdelphij                         (unsigned char *)dataB->data, bl);
812296341Sdelphij    if (i < 0) {
813296341Sdelphij        PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
814296341Sdelphij        goto err;
815296341Sdelphij    }
816296341Sdelphij    i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k);
817296341Sdelphij    if (i < 0) {
818296341Sdelphij        PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
819296341Sdelphij        goto err;
820296341Sdelphij    }
821296341Sdelphij    bl += k;
822238405Sjkim
823296341Sdelphij    if (bl == 0)
824296341Sdelphij        goto err;
825296341Sdelphij    *name = nameB->data;
826296341Sdelphij    *header = headerB->data;
827296341Sdelphij    *data = (unsigned char *)dataB->data;
828296341Sdelphij    *len = bl;
829296341Sdelphij    OPENSSL_free(nameB);
830296341Sdelphij    OPENSSL_free(headerB);
831296341Sdelphij    OPENSSL_free(dataB);
832296341Sdelphij    return (1);
833296341Sdelphij err:
834296341Sdelphij    BUF_MEM_free(nameB);
835296341Sdelphij    BUF_MEM_free(headerB);
836296341Sdelphij    BUF_MEM_free(dataB);
837296341Sdelphij    return (0);
838296341Sdelphij}
839296341Sdelphij
840296341Sdelphij/*
841296341Sdelphij * Check pem string and return prefix length. If for example the pem_str ==
842296341Sdelphij * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
843296341Sdelphij * string "RSA".
844238405Sjkim */
845238405Sjkim
846238405Sjkimint pem_check_suffix(const char *pem_str, const char *suffix)
847296341Sdelphij{
848296341Sdelphij    int pem_len = strlen(pem_str);
849296341Sdelphij    int suffix_len = strlen(suffix);
850296341Sdelphij    const char *p;
851296341Sdelphij    if (suffix_len + 1 >= pem_len)
852296341Sdelphij        return 0;
853296341Sdelphij    p = pem_str + pem_len - suffix_len;
854296341Sdelphij    if (strcmp(p, suffix))
855296341Sdelphij        return 0;
856296341Sdelphij    p--;
857296341Sdelphij    if (*p != ' ')
858296341Sdelphij        return 0;
859296341Sdelphij    return p - pem_str;
860296341Sdelphij}
861