Hyrje
Output encoding transforms data so that special characters cannot be interpreted as code by the receiving parser.
Teoria
The exact encoding depends on the context. For HTML body, convert <, >, &, " and ' to < > & " '. For HTML attributes, use attribute encoding which is even stricter. For JavaScript string literals, escape all non-alphanumerics as \xHH. For URLs, percent-encode. For JSON embedded in HTML, encode unsafe characters as \u00XX. Mixing these up is a common source of XSS.
Modern templating engines — Twig, Jinja2, Blade, ERB with Rails, React JSX — auto-escape by default for the HTML context, which handles 90% of cases. The remaining 10% are places where developers bypass the auto-escape to inject raw HTML (dangerouslySetInnerHTML, Twig raw filter, Jinja |safe). Each of those should be reviewed as if it were a dedicated security control.
For rich text fields where users legitimately submit HTML, do not write your own sanitizer. Use a battle-tested library like DOMPurify (client) or HTML Purifier (PHP) that maintains an allow-list of tags and attributes and strips everything else. These libraries are updated regularly to cover new bypass techniques discovered by researchers.
Mjetet
Mjete encoding:
- PHP:
htmlspecialchars,rawurlencode,json_encode(meJSON_HEX_TAG). - Java: OWASP Encoder.
- JavaScript: Template engines që auto-escape (Handlebars, Twig, React JSX).
Praktika
Kontekste të ndryshme, encoding të ndryshme:
// HTML body
echo htmlspecialchars($name, ENT_QUOTES|ENT_HTML5, 'UTF-8');
// Attribute
echo '<a title="' . htmlspecialchars($t, ENT_QUOTES) . '">';
// JavaScript context
echo '<script>var u = ' . json_encode($u, JSON_HEX_TAG|JSON_HEX_AMP) . ';</script>';
// URL
echo '<a href="/q?s=' . rawurlencode($q) . '">'; Ushtrime
- Identifiko tre kontekste të ndryshme në një template dhe zbato encoding-un e saktë për secilin.
- Shpjego pse
htmlspecialcharsnuk mbron kur output-i shkon brenda një<script>.
Burime
- OWASP — Output Encoding Cheat Sheet.
- Google — Trusted Types.
Vlerësimet dhe komentet
Kyçu për të lënë një vlerësim.
Ende pa komente. Bëhu i pari!
Diskutime
Ende pa diskutime. Hap një temë të re