Make WordPress Core

Changeset 25541


Ignore:
Timestamp:
09/21/2013 06:53:50 AM (13 years ago)
Author:
dd32
Message:

When using download_url(), if the resource supplies a Content-MD5 header, verify the downloaded file against it. Fixes #20074

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-admin/includes/file.php

    r25540 r25541  
    486486        }
    487487
     488        $content_md5 = wp_remote_retrieve_header( $response, 'content-md5' );
     489        if ( $content_md5 ) {
     490                $md5_check = verify_file_md5( $tmpfname, $content_md5 );
     491                if ( is_wp_error( $md5_check ) ) {
     492                        unlink( $tmpfname );
     493                        return $md5_check;
     494                }
     495        }
     496
    488497        return $tmpfname;
     498}
     499
     500/**
     501 * Calculates and compares the MD5 of a file to it's expected value.
     502 *
     503 * @since 3.7.0
     504 *
     505 * @param string $filename The filename to check the MD5 of.
     506 * @param string $expected_md5 The expected MD5 of the file, either a base64 encoded raw md5, or a hex-encoded md5
     507 * @return bool|object WP_Error on failure, true on success, false when the MD5 format is unknown/unexpected
     508 */
     509function verify_file_md5( $filename, $expected_md5 ) {
     510        if ( 32 == strlen( $expected_md5 ) )
     511                $expected_raw_md5 = pack( 'H*', $expected_md5 );
     512        elseif ( 24 == strlen( $expected_md5 ) )
     513                $expected_raw_md5 = base64_decode( $expected_md5 );
     514        else
     515                return false; // unknown format
     516
     517        $file_md5 = md5_file( $filename, true );
     518
     519        if ( $file_md5 === $expected_raw_md5 )
     520                return true;
     521
     522        return new WP_Error( 'md5_mismatch', sprintf( __( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ), bin2hex( $file_md5 ), bin2hex( $expected_raw_md5 ) ) );
    489523}
    490524
Note: See TracChangeset for help on using the changeset viewer.