platform_util.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Common and shared functions used by multiple modules in the Mbed TLS
  3. * library.
  4. *
  5. * Copyright (C) 2018, Arm Limited, All Rights Reserved
  6. * SPDX-License-Identifier: Apache-2.0
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  9. * not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  16. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. *
  20. * This file is part of Mbed TLS (https://tls.mbed.org)
  21. */
  22. #if !defined(MBEDTLS_CONFIG_FILE)
  23. #include "mbedtls/config.h"
  24. #else
  25. #include MBEDTLS_CONFIG_FILE
  26. #endif
  27. #include "mbedtls/platform_util.h"
  28. #include <stddef.h>
  29. #include <string.h>
  30. #if !defined(MBEDTLS_PLATFORM_ZEROIZE_ALT)
  31. /*
  32. * This implementation should never be optimized out by the compiler
  33. *
  34. * This implementation for mbedtls_platform_zeroize() was inspired from Colin
  35. * Percival's blog article at:
  36. *
  37. * http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buffer.html
  38. *
  39. * It uses a volatile function pointer to the standard memset(). Because the
  40. * pointer is volatile the compiler expects it to change at
  41. * any time and will not optimize out the call that could potentially perform
  42. * other operations on the input buffer instead of just setting it to 0.
  43. * Nevertheless, as pointed out by davidtgoldblatt on Hacker News
  44. * (refer to http://www.daemonology.net/blog/2014-09-05-erratum.html for
  45. * details), optimizations of the following form are still possible:
  46. *
  47. * if( memset_func != memset )
  48. * memset_func( buf, 0, len );
  49. *
  50. * Note that it is extremely difficult to guarantee that
  51. * mbedtls_platform_zeroize() will not be optimized out by aggressive compilers
  52. * in a portable way. For this reason, Mbed TLS also provides the configuration
  53. * option MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure
  54. * mbedtls_platform_zeroize() to use a suitable implementation for their
  55. * platform and needs.
  56. */
  57. static void * (* const volatile memset_func)( void *, int, size_t ) = memset;
  58. void mbedtls_platform_zeroize( void *buf, size_t len )
  59. {
  60. memset_func( buf, 0, len );
  61. }
  62. #endif /* MBEDTLS_PLATFORM_ZEROIZE_ALT */