Skip to content

Commit

Permalink
Merge pull request #36 from Jonhvmp/alert-autofix-37
Browse files Browse the repository at this point in the history
Fix code scanning alert no. 37: Incomplete multi-character sanitization
  • Loading branch information
Jonhvmp authored Dec 18, 2024
2 parents 37aaf1b + 60c1eb7 commit b9a5c04
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 26 deletions.
3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"nodemailer": "^6.9.16",
"nodemon": "^3.1.7",
"uuid": "^11.0.3",
"validator": "^13.12.0"
"validator": "^13.12.0",
"sanitize-html": "^2.13.1"
},
"devDependencies": {
"@types/axios": "^0.14.4",
Expand Down
39 changes: 14 additions & 25 deletions backend/src/models/Snippet.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Schema, model, Document } from 'mongoose';
import sanitizeHtml from 'sanitize-html';

// Interface para tipagem TypeScript
export interface ISnippet extends Document {
Expand Down Expand Up @@ -87,32 +88,20 @@ const SnippetSchema = new Schema<ISnippet>(

// Middleware para sanitizar o campo "code" e evitar ataques
SnippetSchema.pre<ISnippet>('save', function (next) {
// Codificar tags HTML perigosas
this.code = this.code.replace(/</g, '&lt;').replace(/>/g, '&gt;');

// Remover atributos perigosos
let previousCode;
const dangerousAttrRegex = /on\w+=(["'])(?:(?=(\\?))\2.)*?\1|javascript:|data:|vbscript:/gi;
do {
previousCode = this.code;
this.code = this.code.replace(dangerousAttrRegex, '');
} while (this.code !== previousCode);

// Remover URLs perigosas em estilos inline
this.code = this.code.replace(/style\s*=\s*["'][^"']*(javascript|data|vbscript):[^"']*["']/gi, 'style=""');

// Remover o uso de expression em estilos
this.code = this.code.replace(/expression\([^)]*\)/gi, '');

// Remover tags específicas não desejadas
const forbiddenTags = ['script', 'iframe', 'img', 'embed', 'object', 'link', 'style'];
forbiddenTags.forEach((tag) => {
const tagRegex = new RegExp(`<${tag}[^>]*>`, 'gi');
const closeTagRegex = new RegExp(`</${tag}>`, 'gi');
this.code = this.code.replace(tagRegex, `&lt;${tag}&gt;`);
this.code = this.code.replace(closeTagRegex, `&lt;/${tag}&gt;`);
// Sanitize the code field using sanitize-html
this.code = sanitizeHtml(this.code, {
allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]),
allowedAttributes: {
'*': [ 'style', 'class' ],
'a': [ 'href', 'name', 'target' ],
'img': [ 'src' ]
},
allowedSchemes: [ 'http', 'https', 'ftp', 'mailto', 'tel' ],
allowedSchemesByTag: {},
allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ],
allowProtocolRelative: true,
enforceHtmlBoundary: true
});

next();
});

Expand Down

0 comments on commit b9a5c04

Please sign in to comment.