Fix handling of long PSK identities

backport from c3b5d83

see #238
diff --git a/library/ssl_cli.c b/library/ssl_cli.c
index 0c62c34..7f46cbb 100644
--- a/library/ssl_cli.c
+++ b/library/ssl_cli.c
@@ -1578,6 +1578,12 @@
     size_t len_bytes = ssl->minor_ver == SSL_MINOR_VERSION_0 ? 0 : 2;
     unsigned char *p = ssl->handshake->premaster + pms_offset;
 
+    if( offset + len_bytes > SSL_MAX_CONTENT_LEN )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
+        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
+    }
+
     /*
      * Generate (part of) the pre-master as
      *  struct {
@@ -2349,6 +2355,14 @@
 
         i = 4;
         n = ssl->psk_identity_len;
+
+        if( i + 2 + n > SSL_MAX_CONTENT_LEN )
+        {
+            SSL_DEBUG_MSG( 1, ( "psk identity too long or "
+                                "SSL buffer too short" ) );
+            return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
+        }
+
         ssl->out_msg[i++] = (unsigned char)( n >> 8 );
         ssl->out_msg[i++] = (unsigned char)( n      );
 
@@ -2377,6 +2391,14 @@
              * ClientDiffieHellmanPublic public (DHM send G^X mod P)
              */
             n = ssl->handshake->dhm_ctx.len;
+
+            if( i + 2 + n > SSL_MAX_CONTENT_LEN )
+            {
+                SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long"
+                                    " or SSL buffer too short" ) );
+                return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
+            }
+
             ssl->out_msg[i++] = (unsigned char)( n >> 8 );
             ssl->out_msg[i++] = (unsigned char)( n      );