xref: /openbsd/lib/libcrypto/rsa/rsa_sign.c (revision 76d0caae)
1 /* $OpenBSD: rsa_sign.c,v 1.33 2021/11/01 20:53:08 tb Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <stdio.h>
60 #include <string.h>
61 
62 #include <openssl/bn.h>
63 #include <openssl/err.h>
64 #include <openssl/objects.h>
65 #include <openssl/rsa.h>
66 #include <openssl/x509.h>
67 
68 #include "rsa_locl.h"
69 #include "x509_lcl.h"
70 
71 /* Size of an SSL signature: MD5+SHA1 */
72 #define SSL_SIG_LENGTH	36
73 
74 static int encode_pkcs1(unsigned char **, int *, int , const unsigned char *,
75     unsigned int);
76 
77 /*
78  * encode_pkcs1 encodes a DigestInfo prefix of hash `type' and digest `m', as
79  * described in EMSA-PKCS-v1_5-ENCODE, RFC 8017 section 9. step 2. This
80  * encodes the DigestInfo (T and tLen) but does not add the padding.
81  *
82  * On success, it returns one and sets `*out' to a newly allocated buffer
83  * containing the result and `*out_len' to its length.  Freeing `*out' is
84  * the caller's responsibility. Failure is indicated by zero.
85  */
86 static int
87 encode_pkcs1(unsigned char **out, int *out_len, int type,
88     const unsigned char *m, unsigned int m_len)
89 {
90 	X509_SIG sig;
91 	X509_ALGOR algor;
92 	ASN1_TYPE parameter;
93 	ASN1_OCTET_STRING digest;
94 	uint8_t *der = NULL;
95 	int len;
96 
97 	sig.algor = &algor;
98 	if ((sig.algor->algorithm = OBJ_nid2obj(type)) == NULL) {
99 		RSAerror(RSA_R_UNKNOWN_ALGORITHM_TYPE);
100 		return 0;
101 	}
102 	if (sig.algor->algorithm->length == 0) {
103 		RSAerror(
104 		    RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD);
105 		return 0;
106 	}
107 	parameter.type = V_ASN1_NULL;
108 	parameter.value.ptr = NULL;
109 	sig.algor->parameter = &parameter;
110 
111 	sig.digest = &digest;
112 	sig.digest->data = (unsigned char *)m; /* TMP UGLY CAST */
113 	sig.digest->length = m_len;
114 
115 	if ((len = i2d_X509_SIG(&sig, &der)) < 0)
116 		return 0;
117 
118 	*out = der;
119 	*out_len = len;
120 
121 	return 1;
122 }
123 
124 int
125 RSA_sign(int type, const unsigned char *m, unsigned int m_len,
126     unsigned char *sigret, unsigned int *siglen, RSA *rsa)
127 {
128 	const unsigned char *encoded = NULL;
129 	unsigned char *tmps = NULL;
130 	int encrypt_len, encoded_len = 0, ret = 0;
131 
132 	if ((rsa->flags & RSA_FLAG_SIGN_VER) && rsa->meth->rsa_sign != NULL)
133 		return rsa->meth->rsa_sign(type, m, m_len, sigret, siglen, rsa);
134 
135 	/* Compute the encoded digest. */
136 	if (type == NID_md5_sha1) {
137 		/*
138 		 * NID_md5_sha1 corresponds to the MD5/SHA1 combination in
139 		 * TLS 1.1 and earlier. It has no DigestInfo wrapper but
140 		 * otherwise is RSASSA-PKCS-v1.5.
141 		 */
142 		if (m_len != SSL_SIG_LENGTH) {
143 			RSAerror(RSA_R_INVALID_DIGEST_LENGTH);
144 			return 0;
145 		}
146 		encoded_len = SSL_SIG_LENGTH;
147 		encoded = m;
148 	} else {
149 		if (!encode_pkcs1(&tmps, &encoded_len, type, m, m_len))
150 			goto err;
151 		encoded = tmps;
152 	}
153 	if (encoded_len > RSA_size(rsa) - RSA_PKCS1_PADDING_SIZE) {
154 		RSAerror(RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY);
155 		goto err;
156 	}
157 	if ((encrypt_len = RSA_private_encrypt(encoded_len, encoded, sigret,
158 	    rsa, RSA_PKCS1_PADDING)) <= 0)
159 		goto err;
160 
161 	*siglen = encrypt_len;
162 	ret = 1;
163 
164  err:
165 	freezero(tmps, (size_t)encoded_len);
166 	return (ret);
167 }
168 
169 /*
170  * int_rsa_verify verifies an RSA signature in `sigbuf' using `rsa'. It may be
171  * called in two modes. If `rm' is NULL, it verifies the signature for the
172  * digest `m'. Otherwise, it recovers the digest from the signature, writing the
173  * digest to `rm' and the length to `*prm_len'. `type' is the NID of the digest
174  * algorithm to use. It returns one on successful verification and zero
175  * otherwise.
176  */
177 int
178 int_rsa_verify(int type, const unsigned char *m, unsigned int m_len,
179     unsigned char *rm, size_t *prm_len, const unsigned char *sigbuf,
180     size_t siglen, RSA *rsa)
181 {
182 	unsigned char *decrypt_buf, *encoded = NULL;
183 	int decrypt_len, encoded_len = 0, ret = 0;
184 
185 	if (siglen != (size_t)RSA_size(rsa)) {
186 		RSAerror(RSA_R_WRONG_SIGNATURE_LENGTH);
187 		return 0;
188 	}
189 
190 	/* Recover the encoded digest. */
191 	if ((decrypt_buf = malloc(siglen)) == NULL) {
192 		RSAerror(ERR_R_MALLOC_FAILURE);
193 		goto err;
194 	}
195 	if ((decrypt_len = RSA_public_decrypt((int)siglen, sigbuf, decrypt_buf,
196 	    rsa, RSA_PKCS1_PADDING)) <= 0)
197 		goto err;
198 
199 	if (type == NID_md5_sha1) {
200 		/*
201 		 * NID_md5_sha1 corresponds to the MD5/SHA1 combination in
202 		 * TLS 1.1 and earlier. It has no DigestInfo wrapper but
203 		 * otherwise is RSASSA-PKCS1-v1_5.
204 		 */
205 		if (decrypt_len != SSL_SIG_LENGTH) {
206 			RSAerror(RSA_R_INVALID_DIGEST_LENGTH);
207 			goto err;
208 		}
209 
210 		if (rm != NULL) {
211 			memcpy(rm, decrypt_buf, SSL_SIG_LENGTH);
212 			*prm_len = SSL_SIG_LENGTH;
213 		} else {
214 			if (m_len != SSL_SIG_LENGTH) {
215 				RSAerror(RSA_R_INVALID_MESSAGE_LENGTH);
216 				goto err;
217 			}
218 			if (timingsafe_bcmp(decrypt_buf,
219 			    m, SSL_SIG_LENGTH) != 0) {
220 				RSAerror(RSA_R_BAD_SIGNATURE);
221 				goto err;
222 			}
223 		}
224 	} else {
225 		/*
226 		 * If recovering the digest, extract a digest-sized output from
227 		 * the end of `decrypt_buf' for `encode_pkcs1', then compare the
228 		 * decryption output as in a standard verification.
229 		 */
230 		if (rm != NULL) {
231 			const EVP_MD *md;
232 
233 			if ((md = EVP_get_digestbynid(type)) == NULL) {
234 				RSAerror(RSA_R_UNKNOWN_ALGORITHM_TYPE);
235 				goto err;
236 			}
237 			if ((m_len = EVP_MD_size(md)) > (size_t)decrypt_len) {
238 				RSAerror(RSA_R_INVALID_DIGEST_LENGTH);
239 				goto err;
240 			}
241 			m = decrypt_buf + decrypt_len - m_len;
242 		}
243 
244 		/* Construct the encoded digest and ensure it matches */
245 		if (!encode_pkcs1(&encoded, &encoded_len, type, m, m_len))
246 			goto err;
247 
248 		if (encoded_len != decrypt_len ||
249 		    timingsafe_bcmp(encoded, decrypt_buf, encoded_len) != 0) {
250 			RSAerror(RSA_R_BAD_SIGNATURE);
251 			goto err;
252 		}
253 
254 		/* Output the recovered digest. */
255 		if (rm != NULL) {
256 			memcpy(rm, m, m_len);
257 			*prm_len = m_len;
258 		}
259 	}
260 
261 	ret = 1;
262  err:
263 	freezero(encoded, (size_t)encoded_len);
264 	freezero(decrypt_buf, siglen);
265 	return ret;
266 }
267 
268 int
269 RSA_verify(int dtype, const unsigned char *m, unsigned int m_len,
270     const unsigned char *sigbuf, unsigned int siglen, RSA *rsa)
271 {
272 	if ((rsa->flags & RSA_FLAG_SIGN_VER) && rsa->meth->rsa_verify)
273 		return rsa->meth->rsa_verify(dtype, m, m_len, sigbuf, siglen,
274 		    rsa);
275 
276 	return int_rsa_verify(dtype, m, m_len, NULL, NULL, sigbuf, siglen, rsa);
277 }
278