Add check for validity of date in x509_get_time()
diff --git a/library/x509.c b/library/x509.c
index bc3bfe0..a79562b 100644
--- a/library/x509.c
+++ b/library/x509.c
@@ -80,6 +80,7 @@
 #endif
 
 #define CHECK(code) if( ( ret = code ) != 0 ){ return( ret ); }
+#define CHECK_RANGE(min, max, val) if( val < min || val > max ){ return( ret ); }
 
 /*
  *  CertificateSerialNumber  ::=  INTEGER
@@ -489,6 +490,33 @@
     return 0;
 }
 
+static int x509_date_is_valid(const mbedtls_x509_time *time)
+{
+    int ret = MBEDTLS_ERR_X509_INVALID_DATE;
+
+    CHECK_RANGE( 0, 9999, time->year );
+    CHECK_RANGE( 0, 23,   time->hour );
+    CHECK_RANGE( 0, 59,   time->min  );
+    CHECK_RANGE( 0, 59,   time->sec  );
+
+    switch( time->mon )
+    {
+        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
+            CHECK_RANGE( 1, 31, time->day );
+            break;
+        case 4: case 6: case 9: case 11:
+            CHECK_RANGE( 1, 30, time->day );
+            break;
+        case 2:
+            CHECK_RANGE( 1, 28 + (time->year % 4 == 0), time->day );
+            break;
+        default:
+            return( ret );
+    }
+
+    return( 0 );
+}
+
 /*
  *  Time ::= CHOICE {
  *       utcTime        UTCTime,
@@ -528,6 +556,8 @@
         time->year +=  100 * ( time->year < 50 );
         time->year += 1900;
 
+        CHECK( x509_date_is_valid( time ) );
+
         return( 0 );
     }
     else if( tag == MBEDTLS_ASN1_GENERALIZED_TIME )
@@ -548,6 +578,8 @@
         if( len > 14 && *(*p)++ != 'Z' )
             return( MBEDTLS_ERR_X509_INVALID_DATE );
 
+        CHECK( x509_date_is_valid( time ) );
+
         return( 0 );
     }
     else