最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

security - Should I worry about SQL injection when using REST API?

programmeradmin1浏览0评论

Should I worry about SQL injection when using REST API and sql queries via $wpdb?
For example, is the bellow vulnerable to sql injection?

public static function get_post( WP_REST_Request $request ) {
        global $wpdb;
        $post_slug = $request->get_param( 'slug' );
        $sql_post_by_slug = "select * from wp_posts 
                                where post_name='{$post_slug}' and post_status='publish'
                                limit 1;";
        $post = $wpdb->get_results($sql_post_by_slug);

        return $post[0];
    }

register_rest_route(
        'reactapi/v1',
        '/post/(?P<slug>[\w\W]+)',
        array(
            'methods'             => 'GET',
            'callback'            => array('ReactApi','get_post'),
        ) );

I tried to pass ' char in url and I see that it does't work:
...reactapi/v1/post/slug'additional-text turns to ...post_name='slug\\'additional-text'...

Should I worry about SQL injection when using REST API and sql queries via $wpdb?
For example, is the bellow vulnerable to sql injection?

public static function get_post( WP_REST_Request $request ) {
        global $wpdb;
        $post_slug = $request->get_param( 'slug' );
        $sql_post_by_slug = "select * from wp_posts 
                                where post_name='{$post_slug}' and post_status='publish'
                                limit 1;";
        $post = $wpdb->get_results($sql_post_by_slug);

        return $post[0];
    }

register_rest_route(
        'reactapi/v1',
        '/post/(?P<slug>[\w\W]+)',
        array(
            'methods'             => 'GET',
            'callback'            => array('ReactApi','get_post'),
        ) );

I tried to pass ' char in url and I see that it does't work:
...reactapi/v1/post/slug'additional-text turns to ...post_name='slug\\'additional-text'...

Share Improve this question edited Sep 19, 2019 at 12:30 Shimon S asked Sep 19, 2019 at 12:24 Shimon SShimon S 8875 gold badges11 silver badges17 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Yes. This is not secure at all. You're putting user input directly into a database query. You need to use $wpdb->prepare() if you're inserting user input into SQL:

$post_slug = $request->get_param( 'slug' );

$query = $wpdb->prepare(
    "select * from wp_posts where post_name=%s and post_status='publish' limit 1;",
    $post_slug
);

$results = $wpdb->get_results( $query );
发布评论

评论列表(0)

  1. 暂无评论