Client submitted jQuery selectors, is it safe?

213 Views Asked by At

Is it XSS safe to allow clients to submit jQuery selectors?

I would run a selector string submitted potentially by trolls and put it into $('') to select elements on the page.

1

There are 1 best solutions below

0
user2182349 On BEST ANSWER

Ref: https://html.spec.whatwg.org/multipage/dom.html#the-id-attribute

When specified on HTML elements, the id attribute value must be unique amongst all the IDs in the element's tree and must contain at least one character. The value must not contain any ASCII whitespace.

Most of the time, ids are letters and digits, with hyphens or underscores. This code requires that the first character of the id is a letter, followed by more letters, numbers, underscores and dashes.

If you are willing to limit the accessible element ids in that way, you may use the following validation scheme to prevent XSS.

JavaScript (would run on the server)

var i, l;
var submittedSelectors = ['<script>alert("ha");</script>','<img src="bogus.com?img=5">','geraniums','https://www.example.com','&lt;etc'];

l = submittedSelectors.length;
for (i = 0; i < l; i++) {
    validate(submittedSelectors[i]);
}

function validate(submitted) {
    if (!/^[a-z][\w-.]{1,62}$/i.test(submitted)) {
        console.log(submitted+' is not valid\n');
        return false;
    } else {
        console.log(submitted+' is okay\n');
        return true;
    }
}

PHP

<?php

$submittedSelectors = ['<script>alert("ha");</script>','<img src="bogus.com?img=5">','geraniums','https://www.example.com','&lt;etc'];

foreach ($submittedSelectors as $ss) {
        validate($ss);
}

function validate($submitted = '') {
        $selector = filter_var($submitted,
                        FILTER_VALIDATE_REGEXP,
                        ['options' => ['regexp' => '/^[a-z][\w-.]{1,64}$/i' ]]);

        if (empty($selector)) {
                echo htmlentities($submitted).' is not valid'.PHP_EOL;
                return false;
        } else {
                echo $selector.' is okay'.PHP_EOL;
                return true;
        }
}

This limits entry to simple ids, and it is implied you would add the # into the selector. If you are willing to allow more complex selectors, you can update the validation.