Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.59% covered (success)
94.59%
210 / 222
50.00% covered (danger)
50.00%
5 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
Scan_Status
95.00% covered (success)
95.00%
209 / 220
50.00% covered (danger)
50.00%
5 / 10
66
0.00% covered (danger)
0.00%
0 / 1
 get_status
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
6.05
 refresh_expired_status
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 get_status_stored_since_load
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 acquire_refresh_lock
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
4.03
 release_refresh_lock
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 get_cached_status
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_api_url
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 fetch_from_api
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
5.00
 normalize_api_data
96.27% covered (success)
96.27%
129 / 134
0.00% covered (danger)
0.00%
0 / 1
28
 sort_threats
87.50% covered (warning)
87.50%
14 / 16
0.00% covered (danger)
0.00%
0 / 1
8.12
1<?php
2/**
3 * Class to handle the Scan Status of Jetpack Protect
4 *
5 * @phan-suppress PhanDeprecatedFunction -- Maintaining backwards compatibility.
6 *
7 * @package automattic/jetpack-protect-status
8 */
9
10namespace Automattic\Jetpack\Protect_Status;
11
12use Automattic\Jetpack\Connection\Client;
13use Automattic\Jetpack\Connection\Manager as Connection_Manager;
14use Automattic\Jetpack\Plugins_Installer;
15use Automattic\Jetpack\Protect_Models\Extension_Model;
16use Automattic\Jetpack\Protect_Models\Status_Model;
17use Automattic\Jetpack\Protect_Models\Threat_Model;
18use Automattic\Jetpack\Sync\Functions as Sync_Functions;
19use Jetpack_Options;
20use WP_Error;
21
22if ( ! defined( 'ABSPATH' ) ) {
23    exit( 0 );
24}
25
26/**
27 * Class that handles fetching of threats from the Scan API
28 */
29class Scan_Status extends Status {
30
31    /**
32     * Scan endpoint
33     *
34     * @var string
35     */
36    const SCAN_API_BASE = '/sites/%d/scan';
37
38    /**
39     * Name of the option where status is stored
40     *
41     * @var string
42     */
43    const OPTION_NAME = 'jetpack_scan_status';
44
45    /**
46     * Name of the option where the timestamp of the status is stored
47     *
48     * @var string
49     */
50    const OPTION_TIMESTAMP_NAME = 'jetpack_scan_status_timestamp';
51
52    /**
53     * Time in seconds that the cache should last
54     *
55     * @var int
56     */
57    const OPTION_EXPIRES_AFTER = 300; // 5 minutes.
58
59    /**
60     * Name of the option row held by the one request refreshing an expired status.
61     *
62     * @var string
63     */
64    const REFRESH_LOCK_NAME = 'jetpack_scan_status_refresh_lock';
65
66    /**
67     * Seconds before a lock that was never released can be taken over. Longer than the fetch timeout.
68     *
69     * @var int
70     */
71    const REFRESH_LOCK_EXPIRES_AFTER = 60;
72
73    /**
74     * Where a threat with no severity sorts: just above Low (below 3), as sortThreatSeverity does in js-packages/scan.
75     *
76     * @var float
77     */
78    private const UNRATED_SEVERITY_SORT_VALUE = 2.5;
79
80    /**
81     * Gets the current status of the Jetpack Protect checks
82     *
83     * @param bool $refresh_from_wpcom Refresh the local plan and status cache from wpcom.
84     * @return Status_Model
85     */
86    public static function get_status( $refresh_from_wpcom = false ) {
87        if ( self::$status !== null ) {
88            return self::$status;
89        }
90
91        if ( $refresh_from_wpcom || ! self::should_use_cache() ) {
92            $status = self::fetch_from_api();
93        } elseif ( self::is_cache_expired() ) {
94            $status = self::refresh_expired_status();
95        } else {
96            $status = self::get_from_options();
97        }
98
99        if ( is_wp_error( $status ) ) {
100            $status = new Status_Model(
101                array(
102                    'error'         => true,
103                    'error_code'    => $status->get_error_code(),
104                    'error_message' => $status->get_error_message(),
105                )
106            );
107        } else {
108            $status = self::normalize_api_data( $status );
109        }
110
111        self::$status = $status;
112        return $status;
113    }
114
115    /**
116     * Fetches the expired status, or serves the stored one while another request is fetching it or just has.
117     *
118     * @return WP_Error|object
119     */
120    private static function refresh_expired_status() {
121        $lock = self::acquire_refresh_lock();
122
123        try {
124            $stored = null === $lock ? self::get_from_options() : self::get_status_stored_since_load();
125            return is_object( $stored ) ? $stored : self::fetch_from_api();
126        } finally {
127            if ( null !== $lock ) {
128                self::release_refresh_lock( $lock );
129            }
130        }
131    }
132
133    /**
134     * Gets a fresh status that another request stored after this one loaded its options.
135     *
136     * @return object|null Null when the stored status is still expired or missing.
137     */
138    private static function get_status_stored_since_load() {
139        global $wpdb;
140
141        // Read the rows themselves: get_option() still holds what this request loaded at boot.
142        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- See above.
143        $rows = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name IN (%s, %s)", self::OPTION_NAME, self::OPTION_TIMESTAMP_NAME ), OBJECT_K );
144
145        if ( ! isset( $rows[ self::OPTION_NAME ] ) || ! isset( $rows[ self::OPTION_TIMESTAMP_NAME ] ) || time() > (int) $rows[ self::OPTION_TIMESTAMP_NAME ]->option_value ) {
146            return null;
147        }
148
149        // Stored serialized twice: update_option() serializes what update_status_option() already did.
150        $status = maybe_unserialize( maybe_unserialize( $rows[ self::OPTION_NAME ]->option_value ) );
151        return is_object( $status ) ? $status : null;
152    }
153
154    /**
155     * Take the lock for refreshing an expired status.
156     *
157     * @return string|null The lock's value, to release it with, or null when another request holds it.
158     */
159    private static function acquire_refresh_lock() {
160        global $wpdb;
161
162        $now = time();
163        // The time it was taken, then digits that tell this request's lock from any other.
164        $value = sprintf( '%d.%09d', $now, wp_rand( 0, 999999999 ) );
165
166        // INSERT IGNORE adds the row only when there is none, as WP_Upgrader::create_lock() does.
167        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The Options API cannot add a row only when it is missing.
168        $taken = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'off')", self::REFRESH_LOCK_NAME, $value ) );
169
170        if ( false === $taken ) {
171            // A database error, not a lock held elsewhere: fetch rather than serve the expired status indefinitely.
172            return $value;
173        }
174
175        if ( ! $taken ) {
176            // Take over a lock that a request left behind without releasing it.
177            // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- See above.
178            $taken = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value + 0 < %d", $value, self::REFRESH_LOCK_NAME, $now - self::REFRESH_LOCK_EXPIRES_AFTER ) );
179        }
180
181        return $taken ? $value : null;
182    }
183
184    /**
185     * Release the lock for refreshing an expired status.
186     *
187     * @param string $lock The value acquire_refresh_lock() returned.
188     * @return void
189     */
190    private static function release_refresh_lock( $lock ) {
191        global $wpdb;
192
193        // Matching the value leaves the row alone when another request has since taken the lock over.
194        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The lock row is not written through the Options API.
195        $wpdb->delete(
196            $wpdb->options,
197            array(
198                'option_name'  => self::REFRESH_LOCK_NAME,
199                'option_value' => $lock,
200            )
201        );
202    }
203
204    /**
205     * Gets the last Scan status stored on the site, even if it has expired, without asking WordPress.com.
206     *
207     * @since 0.9.0
208     *
209     * @return Status_Model|null Null when no status has been stored yet.
210     */
211    public static function get_cached_status() {
212        $scan_data = self::get_from_options();
213        return is_object( $scan_data ) ? self::normalize_api_data( $scan_data ) : null;
214    }
215
216    /**
217     * Gets the Scan API endpoint
218     *
219     * @return WP_Error|string
220     */
221    public static function get_api_url() {
222        $blog_id      = Jetpack_Options::get_option( 'id' );
223        $is_connected = ( new Connection_Manager() )->is_connected();
224
225        if ( ! $blog_id || ! $is_connected ) {
226            return new WP_Error( 'site_not_connected' );
227        }
228
229        $api_url = sprintf( self::SCAN_API_BASE, $blog_id );
230
231        return $api_url;
232    }
233
234    /**
235     * Fetches the status data from the Scan API
236     *
237     * @return WP_Error|array
238     */
239    public static function fetch_from_api() {
240        $api_url = self::get_api_url();
241        if ( is_wp_error( $api_url ) ) {
242            return $api_url;
243        }
244
245        $response = Client::wpcom_json_api_request_as_blog(
246            self::get_api_url(),
247            '2',
248            array(
249                'method'  => 'GET',
250                'timeout' => 30,
251            ),
252            null,
253            'wpcom'
254        );
255
256        $response_code = wp_remote_retrieve_response_code( $response );
257
258        if ( is_wp_error( $response ) || 200 !== $response_code || empty( $response['body'] ) ) {
259            return new WP_Error( 'failed_fetching_status', 'Failed to fetch Scan data from the server', array( 'status' => $response_code ) );
260        }
261
262        $body = json_decode( wp_remote_retrieve_body( $response ) );
263        self::update_status_option( $body );
264        return $body;
265    }
266
267    /**
268     * Normalize API Data
269     *
270     * Formats the payload from the Scan API into an instance of Status_Model.
271     *
272     * @phan-suppress PhanDeprecatedProperty -- Maintaining backwards compatibility.
273     *
274     * @param object $scan_data The data returned by the scan API.
275     *
276     * @return Status_Model
277     */
278    private static function normalize_api_data( $scan_data ) {
279        global $wp_version;
280
281        $installed_plugins = Plugins_Installer::get_plugins();
282        $installed_themes  = Sync_Functions::get_themes();
283
284        $plugins  = array();
285        $themes   = array();
286        $core     = new Extension_Model(
287            array(
288                'name'    => 'WordPress',
289                'slug'    => 'wordpress',
290                'version' => $wp_version,
291                'type'    => 'core',
292                'checked' => true, // to do: default to false once Scan API has manifest
293            )
294        );
295        $files    = array();
296        $database = array();
297
298        $status = new Status_Model(
299            array(
300                'data_source'         => 'scan_api',
301                'status'              => $scan_data->state ?? null,
302                'num_threats'         => 0,
303                'num_themes_threats'  => 0,
304                'num_plugins_threats' => 0,
305                'has_unchecked_items' => false,
306                'current_progress'    => $scan_data->current->progress ?? null,
307                'last_scan_failed'    => ! empty( $scan_data->most_recent->error ),
308            )
309        );
310
311        // Format the "last checked" timestamp.
312        if ( ! empty( $scan_data->most_recent->timestamp ) ) {
313            $date                 = new \DateTime( $scan_data->most_recent->timestamp );
314            $status->last_checked = $date->format( 'Y-m-d H:i:s' );
315        }
316
317        // Ensure all installed plugins and themes are represented in the status.
318        foreach ( $installed_plugins as $path => $installed_plugin ) {
319            $slug   = str_replace( '.php', '', explode( '/', $path )[0] );
320            $plugin = new Extension_Model(
321                array(
322                    'name'    => $installed_plugin['Name'],
323                    'version' => $installed_plugin['Version'],
324                    'slug'    => $slug,
325                    'type'    => 'plugins',
326                    'checked' => true, // to do: default to false once Scan API has manifest
327                )
328            );
329
330            $plugins[ $slug ] = $plugin;
331        }
332        foreach ( $installed_themes as $path => $installed_theme ) {
333            $slug  = str_replace( '.php', '', explode( '/', $path )[0] );
334            $theme = new Extension_Model(
335                array(
336                    'name'    => $installed_theme['Name'],
337                    'version' => $installed_theme['Version'],
338                    'slug'    => $slug,
339                    'type'    => 'themes',
340                    'checked' => true, // to do: default to false once Scan API has manifest
341                )
342            );
343
344            $themes[ $slug ] = $theme;
345        }
346
347        // Merge the threats into the status model.
348        if ( isset( $scan_data->threats ) && is_array( $scan_data->threats ) ) {
349            foreach ( $scan_data->threats as $scan_threat ) {
350                if ( isset( $scan_threat->fixable ) && $scan_threat->fixable ) {
351                    $status->fixable_threat_ids[] = $scan_threat->id;
352                }
353
354                $db_details = null;
355                if ( ! empty( $scan_threat->table ) ) {
356                    $db_details = (object) array_merge(
357                        array(
358                            'table'     => $scan_threat->table,
359                            'pk_column' => $scan_threat->pk_column ?? null,
360                            'pk_value'  => $scan_threat->value ?? null,
361                        ),
362                        ! empty( $scan_threat->details ) ? array( 'details' => $scan_threat->details ) : array()
363                    );
364                }
365
366                $threat = new Threat_Model(
367                    array(
368                        'id'                        => $scan_threat->id ?? null,
369                        'signature'                 => $scan_threat->signature ?? null,
370                        'title'                     => $scan_threat->title ?? null,
371                        'description'               => $scan_threat->description ?? null,
372                        'vulnerability_description' => $scan_threat->vulnerability_description ?? null,
373                        'extension'                 => $scan_threat->extension ?? null,
374                        'fix_description'           => $scan_threat->fix_description ?? null,
375                        'payload_subtitle'          => $scan_threat->payload_subtitle ?? null,
376                        'payload_description'       => $scan_threat->payload_description ?? null,
377                        'first_detected'            => $scan_threat->first_detected ?? null,
378                        'fixed_in'                  => isset( $scan_threat->fixer->fixer ) && 'update' === $scan_threat->fixer->fixer ? $scan_threat->fixer->target : null,
379                        'severity'                  => $scan_threat->severity ?? null,
380                        'fixable'                   => $scan_threat->fixer ?? null,
381                        'status'                    => $scan_threat->status ?? null,
382                        'filename'                  => $scan_threat->filename ?? null,
383                        'context'                   => $scan_threat->context ?? null,
384                        'source'                    => $scan_threat->source ?? null,
385                        'table'                     => $scan_threat->table ?? null,
386                        'details'                   => $db_details,
387                    )
388                );
389
390                // Theme and Plugin Threats
391                if ( ! empty( $scan_threat->extension ) && in_array( $scan_threat->extension->type, array( 'plugin', 'theme' ), true ) ) {
392                    $installed_extension = 'plugin' === $scan_threat->extension->type ? ( $plugins[ $scan_threat->extension->slug ] ?? null ) : ( $themes[ $scan_threat->extension->slug ] ?? null );
393
394                    // If the extension is no longer installed, skip this threat.
395                    // todo: use version_compare()
396                    if ( ! $installed_extension ) {
397                        continue;
398                    }
399
400                    // Updated to the fixed version, the vulnerability is gone, though Scan's report shows it until the next scan.
401                    if ( 'Vulnerable.WP.Extension' === $threat->signature && ! empty( $threat->fixed_in ) && version_compare( (string) $installed_extension->version, (string) $threat->fixed_in, '>=' ) ) {
402                        $installed_extension->checked = false;
403                        continue;
404                    }
405
406                    // Push the threat to the appropriate extension.
407                    switch ( $scan_threat->extension->type ) {
408                        case 'plugin':
409                            $plugins[ $scan_threat->extension->slug ]->threats[] = clone $threat;
410                            ++$status->num_plugins_threats;
411                            break;
412                        case 'theme':
413                            $themes[ $scan_threat->extension->slug ]->threats[] = clone $threat;
414                            ++$status->num_themes_threats;
415                            break;
416                        default:
417                            break;
418                    }
419
420                    $threat->extension = new Extension_Model(
421                        array(
422                            'name'    => $scan_threat->extension->name ?? null,
423                            'slug'    => $scan_threat->extension->slug ?? null,
424                            'version' => $scan_threat->extension->version ?? null,
425                            'type'    => $scan_threat->extension->type . 's',
426                            'checked' => $installed_extension->version === $scan_threat->extension->version,
427                        )
428                    );
429                } elseif ( isset( $threat->signature ) && 'Vulnerable.WP.Core' === $threat->signature ) {
430                    // Vulnerable WordPress Core Version Threats
431
432                    // If the core version has changed, skip this threat.
433                    // todo: use version_compare()
434                    if ( $scan_threat->version !== $wp_version ) {
435                        continue;
436                    }
437
438                    $core->threats[] = $threat;
439                } elseif ( ! empty( $threat->filename ) ) {
440                    // File Threats
441                    $files[] = $threat;
442                } elseif ( ! empty( $scan_threat->table ) ) {
443                    // Database Threats
444                    $database[] = $threat;
445                }
446
447                $status->threats[] = $threat;
448                ++$status->num_threats;
449            }
450        }
451
452        $status->threats = static::sort_threats( $status->threats );
453
454        // maintain deprecated properties for backwards compatibility
455        $status->plugins  = array_values( $plugins );
456        $status->themes   = array_values( $themes );
457        $status->core     = $core;
458        $status->files    = $files;
459        $status->database = $database;
460
461        return $status;
462    }
463
464    /**
465     * Sort By Threats
466     *
467     * @param array<Threat_Model> $threats Array of threats to sort.
468     *
469     * @return array<Threat_Model> The sorted $threats array.
470     */
471    protected static function sort_threats( $threats ) {
472        usort(
473            $threats,
474            function ( $a, $b ) {
475                // Order by active status first...
476                if ( $a->status !== $b->status ) {
477                    return 'active' === $a->status ? -1 : 1;
478                }
479
480                // ...then by severity...
481                $a_severity  = is_numeric( $a->severity ) ? $a->severity : self::UNRATED_SEVERITY_SORT_VALUE;
482                $b_severity  = is_numeric( $b->severity ) ? $b->severity : self::UNRATED_SEVERITY_SORT_VALUE;
483                $by_severity = $b_severity <=> $a_severity;
484                if ( 0 !== $by_severity ) {
485                    return $by_severity;
486                }
487
488                // ...then date added.
489                if ( $a->first_detected !== $b->first_detected ) {
490                    return strtotime( $a->first_detected ) < strtotime( $b->first_detected ) ? -1 : 1;
491                }
492
493                return 0;
494            }
495        );
496
497        return $threats;
498    }
499}