rsa_ssl.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. #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. if ((num != (flen + 1)) || (*(p++) != 02)) {
  56. RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_BLOCK_TYPE_IS_NOT_02);
  57. return -1;
  58. }
  59. /* scan over padding data */
  60. j = flen - 1; /* one for type */
  61. for (i = 0; i < j; i++)
  62. if (*(p++) == 0)
  63. break;
  64. if ((i == j) || (i < 8)) {
  65. RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23,
  66. RSA_R_NULL_BEFORE_BLOCK_MISSING);
  67. return -1;
  68. }
  69. for (k = -9; k < -1; k++) {
  70. if (p[k] != 0x03)
  71. break;
  72. }
  73. if (k == -1) {
  74. RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_SSLV3_ROLLBACK_ATTACK);
  75. return -1;
  76. }
  77. i++; /* Skip over the '\0' */
  78. j -= i;
  79. if (j > tlen) {
  80. RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_DATA_TOO_LARGE);
  81. return -1;
  82. }
  83. memcpy(to, p, (unsigned int)j);
  84. return j;
  85. }