Add macro for bounds checking
This commit adds a macro for buffer bounds checks in the SSL
module. It takes the buffer's current and end position as the
first argument(s), followed by the needed space; if the
available space is too small, it returns an SSL_BUFFER_TOO_SMALL
error.
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
diff --git a/include/mbedtls/ssl_internal.h b/include/mbedtls/ssl_internal.h
index e92381c..d655813 100644
--- a/include/mbedtls/ssl_internal.h
+++ b/include/mbedtls/ssl_internal.h
@@ -299,6 +299,41 @@
#define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT (1 << 0)
#define MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK (1 << 1)
+/**
+ * \brief This function checks if the remaining size in a buffer is
+ * greater or equal than a needed space.
+ *
+ * \param cur Pointer to the current position in the buffer.
+ * \param end Pointer to one past the end of the buffer.
+ * \param need Needed space in bytes.
+ *
+ * \return Non-zero if the needed space is available in the buffer, 0
+ * otherwise.
+ */
+static inline int mbedtls_ssl_chk_buf_ptr( const uint8_t *cur,
+ const uint8_t *end, size_t need )
+{
+ return( cur <= end && need <= (size_t)( end - cur ) );
+}
+
+/**
+ * \brief This macro checks if the remaining size in a buffer is
+ * greater or equal than a needed space. If it is not the case,
+ * it returns an SSL_BUFFER_TOO_SMALL error.
+ *
+ * \param cur Pointer to the current position in the buffer.
+ * \param end Pointer to one past the end of the buffer.
+ * \param need Needed space in bytes.
+ *
+ */
+#define MBEDTLS_SSL_CHK_BUF_PTR( cur, end, need ) \
+ do { \
+ if( mbedtls_ssl_chk_buf_ptr( ( cur ), ( end ), ( need ) ) == 0 ) \
+ { \
+ return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); \
+ } \
+ } while( 0 )
+
#ifdef __cplusplus
extern "C" {
#endif