rsa_ssl.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*
  2. * Copyright 1995-2018 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. #include <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include <openssl/bn.h>
  12. #include <openssl/rsa.h>
  13. #include <openssl/rand.h>
  14. int RSA_padding_add_SSLv23(unsigned char *to, int tlen,
  15. const unsigned char *from, int flen)
  16. {
  17. int i, j;
  18. unsigned char *p;
  19. if (flen > (tlen - 11)) {
  20. RSAerr(RSA_F_RSA_PADDING_ADD_SSLV23,
  21. RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
  22. return 0;
  23. }
  24. p = (unsigned char *)to;
  25. *(p++) = 0;
  26. *(p++) = 2; /* Public Key BT (Block Type) */
  27. /* pad out with non-zero random data */
  28. j = tlen - 3 - 8 - flen;
  29. if (RAND_bytes(p, j) <= 0)
  30. return 0;
  31. for (i = 0; i < j; i++) {
  32. if (*p == '\0')
  33. do {
  34. if (RAND_bytes(p, 1) <= 0)
  35. return 0;
  36. } while (*p == '\0');
  37. p++;
  38. }
  39. memset(p, 3, 8);
  40. p += 8;
  41. *(p++) = '\0';
  42. memcpy(p, from, (unsigned int)flen);
  43. return 1;
  44. }
  45. int RSA_padding_check_SSLv23(unsigned char *to, int tlen,
  46. const unsigned char *from, int flen, int num)
  47. {
  48. int i, j, k;
  49. const unsigned char *p;
  50. p = from;
  51. if (flen < 10) {
  52. RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_DATA_TOO_SMALL);
  53. return -1;
  54. }
  55. /* Accept even zero-padded input */
  56. if (flen == num) {
  57. if (*(p++) != 0) {
  58. RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_BLOCK_TYPE_IS_NOT_02);
  59. return -1;
  60. }
  61. flen--;
  62. }
  63. if ((num != (flen + 1)) || (*(p++) != 02)) {
  64. RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_BLOCK_TYPE_IS_NOT_02);
  65. return -1;
  66. }
  67. /* scan over padding data */
  68. j = flen - 1; /* one for type */
  69. for (i = 0; i < j; i++)
  70. if (*(p++) == 0)
  71. break;
  72. if ((i == j) || (i < 8)) {
  73. RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23,
  74. RSA_R_NULL_BEFORE_BLOCK_MISSING);
  75. return -1;
  76. }
  77. for (k = -9; k < -1; k++) {
  78. if (p[k] != 0x03)
  79. break;
  80. }
  81. if (k == -1) {
  82. RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_SSLV3_ROLLBACK_ATTACK);
  83. return -1;
  84. }
  85. i++; /* Skip over the '\0' */
  86. j -= i;
  87. if (j > tlen) {
  88. RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_DATA_TOO_LARGE);
  89. return -1;
  90. }
  91. memcpy(to, p, (unsigned int)j);
  92. return j;
  93. }