diff --git a/app/main/controllers/api/RTMediaJsonApi.php b/app/main/controllers/api/RTMediaJsonApi.php index 769dd1453..44d2072bd 100644 --- a/app/main/controllers/api/RTMediaJsonApi.php +++ b/app/main/controllers/api/RTMediaJsonApi.php @@ -347,7 +347,7 @@ public function rtmedia_api_process_wp_login_request() { 'user_id' => intval( $user_login->ID ), 'ip' => $remote_addr, 'token' => sanitize_text_field( $access_token ), - 'token_time' => date( 'Y-m-d H:i:s' ), // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date + 'token_time' => time(), ); $rtmapilogin->insert( $login_details ); wp_send_json( $this->rtmedia_api_response_object( 'TRUE', $ec_login_success, $msg_login_success, $data ) ); diff --git a/app/main/controllers/api/RTMediaJsonApiFunctions.php b/app/main/controllers/api/RTMediaJsonApiFunctions.php index 14d683343..e88067f68 100644 --- a/app/main/controllers/api/RTMediaJsonApiFunctions.php +++ b/app/main/controllers/api/RTMediaJsonApiFunctions.php @@ -11,6 +11,13 @@ */ class RTMediaJsonApiFunctions { + /** + * Token lifetime in seconds. + * + * @var int + */ + public $token_lifetime = 2592000; // 30 days. + /** * RTMediaJsonApiFunctions constructor. */ @@ -28,9 +35,20 @@ public function rtmedia_api_get_user_token( $user_id, $user_login ) { if ( empty( $user_id ) || empty( $user_login ) ) { return false; } - $string = '08~' . $user_id . '~' . $user_login . '~kumar'; - return sha1( $string . current_time( 'timestamp' ) . wp_rand( 1, 9 ) ); + // Generate an opaque 64 character long token for user login. + return wp_generate_password( 64, false, false ); + } + + /** + * Get the absolute API token lifetime in seconds. + * + * @return int + */ + public function rtmedia_api_get_token_lifetime() { + $token_lifetime = (int) apply_filters( 'rtmedia_api_token_lifetime', $this->token_lifetime ); + + return max( MINUTE_IN_SECONDS, $token_lifetime ); } /** @@ -96,6 +114,11 @@ public function rtmedia_api_validate_token( $token ) { return false; } + // Revoke predictable 40-character SHA-1 tokens issued by affected versions. + if ( 1 !== preg_match( '/^[A-Za-z0-9]{64}$/D', $token ) ) { + return false; + } + if ( class_exists( 'RTMediaApiLogin' ) ) { $rtmediaapilogin = new RTMediaApiLogin(); $columns = array( @@ -106,6 +129,15 @@ public function rtmedia_api_validate_token( $token ) { return false; } + $issued_at = isset( $token_data[0]->token_time ) ? (int) $token_data[0]->token_time : 0; + $expires_at = $issued_at + $this->rtmedia_api_get_token_lifetime(); + + if ( $issued_at <= 0 || time() >= $expires_at ) { + $rtmediaapilogin->update( array( 'status' => 'FALSE' ), array( 'id' => $token_data[0]->id ) ); + + return false; + } + return $token_data; } else { return false; @@ -124,6 +156,9 @@ public function rtmedia_api_get_user_id_from_token( $token ) { return false; } $token_data = $this->rtmedia_api_validate_token( $token ); + if ( empty( $token_data ) ) { + return false; + } return $token_data[0]->user_id; }