]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/rsa/rsa_ssl.c
rsa/*: switch to BN_bn2binpad.
[thirdparty/openssl.git] / crypto / rsa / rsa_ssl.c
1 /*
2 * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/bn.h>
13 #include <openssl/rsa.h>
14 #include <openssl/rand.h>
15
16 int RSA_padding_add_SSLv23(unsigned char *to, int tlen,
17 const unsigned char *from, int flen)
18 {
19 int i, j;
20 unsigned char *p;
21
22 if (flen > (tlen - 11)) {
23 RSAerr(RSA_F_RSA_PADDING_ADD_SSLV23,
24 RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
25 return 0;
26 }
27
28 p = (unsigned char *)to;
29
30 *(p++) = 0;
31 *(p++) = 2; /* Public Key BT (Block Type) */
32
33 /* pad out with non-zero random data */
34 j = tlen - 3 - 8 - flen;
35
36 if (RAND_bytes(p, j) <= 0)
37 return 0;
38 for (i = 0; i < j; i++) {
39 if (*p == '\0')
40 do {
41 if (RAND_bytes(p, 1) <= 0)
42 return 0;
43 } while (*p == '\0');
44 p++;
45 }
46
47 memset(p, 3, 8);
48 p += 8;
49 *(p++) = '\0';
50
51 memcpy(p, from, (unsigned int)flen);
52 return 1;
53 }
54
55 int RSA_padding_check_SSLv23(unsigned char *to, int tlen,
56 const unsigned char *from, int flen, int num)
57 {
58 int i, j, k;
59 const unsigned char *p;
60
61 p = from;
62 if (flen < 10) {
63 RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_DATA_TOO_SMALL);
64 return -1;
65 }
66 /* Accept even zero-padded input */
67 if (flen == num) {
68 if (*(p++) != 0) {
69 RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_BLOCK_TYPE_IS_NOT_02);
70 return -1;
71 }
72 flen--;
73 }
74 if ((num != (flen + 1)) || (*(p++) != 02)) {
75 RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_BLOCK_TYPE_IS_NOT_02);
76 return -1;
77 }
78
79 /* scan over padding data */
80 j = flen - 1; /* one for type */
81 for (i = 0; i < j; i++)
82 if (*(p++) == 0)
83 break;
84
85 if ((i == j) || (i < 8)) {
86 RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23,
87 RSA_R_NULL_BEFORE_BLOCK_MISSING);
88 return -1;
89 }
90 for (k = -9; k < -1; k++) {
91 if (p[k] != 0x03)
92 break;
93 }
94 if (k == -1) {
95 RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_SSLV3_ROLLBACK_ATTACK);
96 return -1;
97 }
98
99 i++; /* Skip over the '\0' */
100 j -= i;
101 if (j > tlen) {
102 RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_DATA_TOO_LARGE);
103 return -1;
104 }
105 memcpy(to, p, (unsigned int)j);
106
107 return j;
108 }