@@ -9893,12 +9893,35 @@ int wolfSSL_X509_REQ_verify(WOLFSSL_X509* x509, WOLFSSL_EVP_PKEY* pkey)
98939893#endif /* WOLFSSL_CERT_REQ */
98949894
98959895#if !defined(NO_FILESYSTEM)
9896+ /* Size of the DER SEQUENCE at the file's current position, or 0 when it can't
9897+ * be determined or exceeds avail. The file position is unchanged. */
9898+ static long d2i_fp_der_sz(XFILE file, long avail)
9899+ {
9900+ byte hdr[6];
9901+ word32 idx = 0;
9902+ int len = 0;
9903+ long start = XFTELL(file);
9904+ long hdrSz = (avail < (long)sizeof(hdr)) ? avail : (long)sizeof(hdr);
9905+ long rdSz;
9906+
9907+ if (start < 0) {
9908+ return 0;
9909+ }
9910+ rdSz = (long)XFREAD(hdr, 1, (size_t)hdrSz, file);
9911+ if (XFSEEK(file, start, XSEEK_SET) != 0 || rdSz != hdrSz ||
9912+ GetSequence_ex(hdr, &idx, &len, (word32)hdrSz, 0) < 0 ||
9913+ len == 0 || (long)idx + len > avail) {
9914+ return 0;
9915+ }
9916+ return (long)idx + len;
9917+ }
9918+
98969919static void *wolfSSL_d2i_X509_fp_ex(XFILE file, void **x509, int type)
98979920{
98989921 void *newx509 = NULL;
98999922 byte *fileBuffer = NULL;
99009923 long sz = 0;
9901- long start = 0 ;
9924+ long derSz ;
99029925
99039926 /* init variable */
99049927 if (x509)
@@ -9910,31 +9933,30 @@ static void *wolfSSL_d2i_X509_fp_ex(XFILE file, void **x509, int type)
99109933 }
99119934
99129935 /* Read from the current position. */
9913- if (wolfssl_file_len(file, &sz) == 0) {
9914- start = XFTELL(file);
9915- }
9916- if (sz <= 0 || start < 0) {
9936+ if (wolfssl_file_len(file, &sz) != 0) {
99179937 WOLFSSL_MSG("d2i_X509_fp_ex file size error");
99189938 return NULL;
99199939 }
99209940
9941+ /* Read only the first object, leaving the file after it. */
9942+ derSz = d2i_fp_der_sz(file, sz);
9943+ if (derSz > 0) {
9944+ sz = derSz;
9945+ }
9946+ /* BER PKCS#12 may use an indefinite length, so read it all. */
9947+ else if (type != PKCS12_TYPE) {
9948+ WOLFSSL_MSG("d2i_X509_fp_ex bad DER header");
9949+ return NULL;
9950+ }
9951+
99219952 fileBuffer = (byte *)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE);
99229953 if (fileBuffer != NULL) {
99239954 if ((long)XFREAD(fileBuffer, 1, (size_t)sz, file) != sz) {
99249955 WOLFSSL_MSG("File read failed");
99259956 goto err_exit;
99269957 }
99279958 if (type == CERT_TYPE) {
9928- const byte* p = fileBuffer;
9929-
9930- /* Decode one certificate and leave the file after it. */
9931- newx509 = (void *)wolfSSL_d2i_X509(NULL, &p, (int)sz);
9932- if (newx509 != NULL &&
9933- XFSEEK(file, start + (long)(p - fileBuffer), XSEEK_SET)
9934- != 0) {
9935- wolfSSL_X509_free((WOLFSSL_X509*)newx509);
9936- newx509 = NULL;
9937- }
9959+ newx509 = (void *)wolfSSL_X509_d2i(NULL, fileBuffer, (int)sz);
99389960 }
99399961 #ifdef HAVE_CRL
99409962 else if (type == CRL_TYPE) {
0 commit comments