Skip to content

Commit

Permalink
fix(tag/include_code): prevent path traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenjoezhang committed Jul 26, 2023
1 parent 1ef75e8 commit cada1bd
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 21 deletions.
40 changes: 20 additions & 20 deletions lib/plugins/tag/include_code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,32 +46,32 @@ export = ctx => function includeCodeTag(args) {
// If the language is not defined, use file extension instead
lang = lang || extname(path).substring(1);

const src = join(ctx.source_dir, codeDir, path);
const src = join(codeDir, path);

// If the title is not defined, use file name instead
const title = match[1] || basename(path);
const caption = `<span>${title}</span><a href="${posix.join(ctx.config.root, codeDir, path)}">view raw</a>`;

return exists(src).then(exist => {
if (exist) return readFile(src);
}).then((code: string) => {
if (!code) return;
// Prevent path traversal: https://github.com/hexojs/hexo/issues/5250
const Page = ctx.model('Page');
const doc = Page.findOne({ source: src });
if (!doc) return;

const lines = code.split('\n');
code = lines.slice(from, to).join('\n').trim();
let code = doc.content;
const lines = code.split('\n');
code = lines.slice(from, to).join('\n').trim();

if (ctx.extend.highlight.query(ctx.config.syntax_highlighter)) {
const options = {
lang,
caption,
lines_length: lines.length
};
return ctx.extend.highlight.exec(ctx.config.syntax_highlighter, {
context: ctx,
args: [code, options]
});
}
if (ctx.extend.highlight.query(ctx.config.syntax_highlighter)) {
const options = {
lang,
caption,
lines_length: lines.length
};
return ctx.extend.highlight.exec(ctx.config.syntax_highlighter, {
context: ctx,
args: [code, options]
});
}

return `<pre><code>${code}</code></pre>`;
});
return `<pre><code>${code}</code></pre>`;
};
6 changes: 5 additions & 1 deletion test/scripts/tags/include_code.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ describe('include_code', () => {

const code = args => includeCode(args.split(' '));

before(() => writeFile(path, fixture));
before(async () => {
await writeFile(path, fixture);
await hexo.init();
await hexo.load();
});

beforeEach(() => {
hexo.config = JSON.parse(JSON.stringify(defaultCfg));
Expand Down

0 comments on commit cada1bd

Please sign in to comment.