Wiki source code of Security

Last modified by Raphaël Jakse on 2026/06/10 13:51

Show last authors
1 This page aims at listing the specific things that a developer should be careful with to avoid introducing new vulnerabilities in scripts and extensions. All security topic related to administration of the wiki is located in [[the security page of the administrator guide>>doc:Documentation.AdminGuide.Security]].
2
3 {{box cssClass="floatinginfobox" title="**Contents**"}}
4 {{toc/}}
5 {{/box}}
6
7 == Scripting and Escaping ==
8
9 The first vulnerability in scripts is the user inputs: any input that a user can provide could possibly be an open door to an attack. Either XSS when the content is output in an HTML context, or XWiki syntax injection when the syntax is injected, e.g., in a Velocity macro where parsing of the output is enabled (the default). XWiki syntax injection almost always allows executing macros with the rights of the script's author and as this author frequently has the programming right, this gives an attacker the ability to execute arbitrary code. It doesn't matter where in the output the user's input is used. Regardless if it is in a parameter, an HTML macro or a verbatim syntax, by including the respective closing syntax, user input can always close whatever syntax it is part of. The nested script macro protection is no protection against attacks. By putting the nested script macro, e.g., inside an async macro, the nested script macro protection can easily be circumvented as the async macro has its own parsing context.
10
11 So in order to mitigate this, developers should always ensure to use the proper escaping mechanism. The most important ways to escape content are:
12
13 * ##$services.rendering.escape($content, 'xwiki/2.1')## for XWiki syntax
14 * ##$escapetool.xml($content)## for HTML output. This can also be used in an HTML macro and escapes ##{##, thereby preventing the closing of the HTML macro through user input.
15
16 Make sure you always test if escaping actually protects against attacks by writing appropriate tests.
17
18 === ##xwiki/2.0## and ##xwiki/2.1## syntaxes ===
19
20 ==== Link label ====
21
22 In XWiki syntax 2.0 and 2.1 the link is parsed in two passes, each pass having its own escaping:
23
24 * the global link is first parsed with the label being just one big string
25 * then the label is parsed on its own
26
27 What this means in practice is that when you need to escape something in the link label you need to escape it twice. For example if you want to print something that may contains wiki syntax as a link label you could do for example in Velocity:
28
29 {{code language="velocity"}}
30 #set ($userContent = '{{mymacro/}}')
31 #set ($escapedLabel = $services.rendering.escape($services.rendering.escape($userContent, 'xwiki/2.1'), 'xwiki/2.1'))
32 [[label $escapedLabel>>Main.WebHome]]
33 {{/code}}
34
35 {{warning}}
36 If the reference (the part after ##>>##) is dynamic, it also needs to be escaped (once) (like pretty much anything else).
37 {{/warning}}
38
39 ==== Verbatim ====
40
41 It's impossible to properly escape content to put in [[verbatim syntax>>https://jira.xwiki.org/browse/XRENDERING-686]] in syntaxes ##xwiki/2.0## and ##xwiki/2.1##.
42
43 The simplest for this kind of use case is generally to use something like:
44
45 {{code language="velocity"}}
46 (%class="code"%)(((
47 $services.rendering.escape($doc.content, 'xwiki/2.1')
48 )))
49 {{/code}}
50
51 ==== Code macro ====
52
53 It's impossible to properly escape content to put in [[code macro>>https://jira.xwiki.org/browse/XRENDERING-13]] in syntaxes ##xwiki/2.0## and ##xwiki/2.1##.
54
55 There are several alternatives if you need to highlight user input:
56
57 {{version since="14.10.2"}}
58 Use the ##source## code macro parameter: instead of trying to escape the content you provide only a reference of a the content to highlight so no need to escape it anymore.
59
60 See [[extensions:Extension.Code Macro||anchor="HSource"]] for more details.
61 {{/version}}
62
63 {{version before="14.10.2"}}
64 An alternative if you need to highlight user input is to return directly the MacroBlock instead of serializing it. For example in Groovy:
65
66 {{code language="groovy"}}
67 return new org.xwiki.rendering.block.MacroBlock("code", ["language": "xml"], userInput, false)
68 {{/code}}
69 {{/version}}
70
71 === Translations ===
72
73 Translation values are often inserted in content that follows a specific syntax (wiki content, HTML, etc.), which means the translation is often re-parsed for this content syntax. Treat every translation value as untrusted and escape it when you render it for two reasons:
74
75 * **Privilege escalation.** A translation value can contain injection ({{code language="none"}}{{groovy}}{{/code}}, {{code language="none"}}{{html}}{{/code}}, ...). Registering a translation that affects other users requires elevated rights (##GLOBAL## scope needs Programming Right, ##WIKI## scope needs Wiki Admin Right). A ##USER## scope translation only needs Script Right, but that is still dangerous: a user with only Script Right can register such a translation, and if it is then rendered in a request handled for a user who has Admin or Programming rights, the injected macro executes with those rights. In other words, leaving a translation value unescaped turns Script Right into a path to Admin/Programming Right.
76 * **Broken display.** A translation value may legitimately contain characters that are conflicting with the syntax of the context in which it's inserted ({{code language="none"}}*{{/code}}, {{code language="none"}}[[{{/code}}, {{code language="none"}}<{{/code}}, ...). Unless escaped, it might break the display of the whole content around the translation.
77
78 ==== Use the ##~{~{translation}}## macro when you can ====
79
80 The best in terms of performance and security is to use the [[~~{~~{translation}}## macro##>>extensions:Extension.Translation Macro]]. The reason is that in that case the translation is not parsed but directly inserted into the XDOM.
81
82 {{version since="16.10.18,17.10.9,18.4.0RC1"}}
83 But it can be hard to properly escape the parameter values to pass to the macro, to avoid injection through translation parameters.
84
85 In such a case, the translation macro allows passing the name of the variable that contains the list of translation parameters:
86
87 {{code language="none"}}
88 {{velocity}}
89 #set ($txparameters = [$userinput, 42])
90 {{translation key="some.translation" scriptParameters="txparameters"/}}
91 {{/velocity}}
92 {{/code}}
93 {{/version}}
94
95 {{version since="16.10.18,17.10.10,18.4.1,18.5.0RC1"}}
96 A helper for Velocity is provided to make inserting a translation macro with potential user input even easier and more readable:
97
98 {{code language="none"}}
99 {{velocity}}
100 #wikiTranslation('some.translation', [$userinput, 42])
101 {{/velocity}}
102 {{/code}}
103 {{/version}}
104
105 ==== When you cannot use the ##~{~{translation}}## macro ====
106
107 So when you are not in a wiki context, or when you're coding for an older version of XWiki (i.e. before 16.10.18,17.10.9,18.4.0RC1) for which passing translation parameters to the ~{~{translation}} macro is too complex (you'd need to escape each parameter separately), do the following:
108
109 * Escape the entire ###render## output. This protects against both injection through translation value and through translation parameters:(((
110 {{code language="velocity"}}
111 {{html}}
112 $escapetool.xml($services.localization.render('myapp.key', [$param]))
113 {{/html}}
114
115 ## To be used only for older XWiki versions, see above. For new versions, use the translation macro.
116 $services.rendering.escape($services.localization.render('myapp.key', [$param]), 'xwiki/2.1'))
117 {{/code}}
118 )))
119 * Do not rely on translations containing specific syntax (wiki markup, HTML, etc). Aside from making it much more complex for contributors to translate it, it makes it impossible to properly escape it. To wrap translated text in a link or other markup, build the markup in your (trusted) code and put the escaped translation inside it. For example, in the case of a link, having only the link label in the translation:(((
120 {{code language="velocity"}}
121 {{html}}
122 <a href="$link">$esapetool.xml($services.localization.render('myapp.linkLabel', [$param]))</a>
123 {{/html}}
124
125 ## Link label requires double escaping in xwiki/2.1 syntax, see the "Link label" section for more details
126 ## To be used only for older XWiki versions, see above. For new versions, use the translation macro.
127 [[$services.rendering.escape($services.rendering.escape($services.localization.render('myapp.linkLabel', [$param]), 'xwiki/2.1'), 'xwiki/2.1')>>$target]]
128 {{/code}}
129 )))
130 * When you cannot escape the whole result (which should be avoided, as mentioned above), at least escape the parameters that might come from user input before passing them to #render.
131
132 == HTML ==
133
134 While ##$escapetool.xml($content)## is enough for escaping user input/untrusted text that is simply displayed, this is not necessarily the case for values that are used in attributes that have special meaning like the target of a link. There, even a fully escaped string could be interpreted as a script when the user clicks on it. In XWiki syntax, all attributes are automatically validated, but this is not the case for HTML in HTML macros with script right or Velocity templates. You can use ##$services.html.isAttributeSafe($htmlElement, $attributeName, $attributeValue)## to check if a certain attribute with a certain value is safe according to the [[HTML cleaning configuration>>extensions:Extension.XML Module||anchor="HHTMLCleaning"]]. This returns ##false## for script-URLs on links for example. See also the section on [[HTTP requests and redirects>>||anchor="#HHTTPRequestsandRedirects"]] for extra precautions that you should take if the user doesn't expect to land on a different domain when clicking on a link/button, like a "Cancel" button.
135
136 == Restricted Mode in Macros ==
137
138 As explained in details [[in the documentation for writing macros>>rendering:Main.ExtendingMacro||anchor="HSecurityconsiderations"]], the Macro Transformation Context can be set in "Restricted Mode" and in your macro should respect this parameter (by checking ##macroContext.getTransformationContext().isRestricted()##) and either not execute at all or execute in a restricted mode.
139
140 == Protect against XXE attacks ==
141
142 Always follow the [[OWASP recommendations to protect against XXE attacks>>https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html]] when parsing XML.
143
144 == Right Checks in Script Services ==
145
146 Any code that is exposed as a script service needs to check the rights of the context **author**, i.e., the user who wrote the script, in addition to the context **user**, i.e., the user that is accessing the script. Currently, the only easy way to check rights of the context author is to check script or programming right using a contextual authorization manager. It takes important context information into account like if permissions have been dropped. In addition to that, all right checks that are done for the context user should be duplicated for the context author to ensure that no CSRF attacks are possible, i.e., there is no way to, e.g., write a script that executes a dangerous action as soon as a user with more rights accesses the document. It needs to be taken care that if permissions have been dropped, the context author cannot be trusted and thus no dangerous actions must be performed and no sensitive information must be disclosed.
147
148 If the script service exposes information or executes actions without further right checks, it must check for programming right of the context author.
149
150 Note that context author rights are currently not consistently enforced in XWiki, in particular there is no such concept in JavaScript. This is an area for future improvements, new code should still take context author rights into account.
151
152 == Returning Data in Script Services ==
153
154 When returning any object in a script service, ensure that all its methods properly check access rights and don't allow modifying data without proper access right checks. Use wrapper objects to add right checks or hide dangerous methods. For example, returning an ##XWikiDocument## is not safe as it allows modifying author information and executing the content with the new author.
155
156 == Executing Code or XWiki Syntax ==
157
158 If possible, it should be avoided to introduce new code that directly executes (Velocity) code or XWiki syntax with transformations. Instead, existing APIs should be used, e.g., displaying a text area property instead of manually parsing the content of the property. If this should still be necessary, it is of utmost importance to:
159
160 * Check that the author of the code has script right. Make sure you check the content author if the code is in the content of the document and the effective metadata author if the code is in an XObject.
161 * Execute the code or transformations with the correct author in context. In Java, ##AuthorExecutor## should be used for this. There is no way to do this in Velocity. There are hacks like ##dropPermissions## but they are prone to security vulnerabilities and should thus be avoided.
162
163 == Safe Evaluation of Objects ==
164
165 {{version since="14.10.21,15.5.5,15.10.2"}}
166 A new API has been introduced, allowing to specify exactly the XObjects properties that needs to be evaluated and how.
167
168 This includes a new [[ObjectEvaluator>>https://github.com/xwiki/xwiki-platform/blob/xwiki-platform-15.10.2/xwiki-platform-core/xwiki-platform-oldcore/src/main/java/org/xwiki/evaluation/ObjectEvaluator.java]] component, that can be implemented with a hint matching the name of the XClass for which a safe evaluation is required. Implementations of [[ObjectPropertyEvaluator>>https://github.com/xwiki/xwiki-platform/blob/xwiki-platform-15.10.2/xwiki-platform-core/xwiki-platform-oldcore/src/main/java/org/xwiki/evaluation/ObjectPropertyEvaluator.java]] can be used to provide different evaluation strategies: an existing implementation already exists for Velocity evaluation of properties, with the hint ##velocity##. For a full example of an ##ObjectEvaluator## component, see [[the one for SearchSuggestSourceClass XClass>>https://github.com/xwiki/xwiki-platform/blob/xwiki-platform-15.10.2/xwiki-platform-core/xwiki-platform-search/xwiki-platform-search-api/src/main/java/org/xwiki/search/internal/SearchSuggestSourceObjectEvaluator.java]].
169
170 Finally once the component is declared, the object properties can be safely evaluated by calling ##evaluate()## on the object instance, which will return the map of evaluated properties.
171 {{/version}}
172
173 == HTTP Requests and Redirects ==
174
175 Whenever the user is redirected to a URL or HTTP requests are performed on the server side, extra care is needed to avoid introducing an [[open redirect>>https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html]] or [[server side request forgery (SSRF)>>https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html]] vulnerability. While the perfect mitigation is to simply never use user-provided data in redirects and HTTP requests, this is sometimes not possible, in particular if backwards-compatibility needs to be maintained. For this reason, XWiki provides the [[possibility for admins to configure a list of trusted domains and methods to validate a URL>>doc:extensions:Extension.URL API||anchor="HSecurity"]] - both in Java and as a script service that can be used in Velocity. Note that there are [[differences in URL parsing that can be exploited>>https://claroty.com/team82/research/exploiting-url-parsing-confusion]], as the validation might see one domain, but the browser actually uses a different domain. For this reason, the provided method ##parseToSafeURI ##doesn't just validate the passed URL but instead returns the parsed URL to ensure that the URL is interpreted as validated.
176
177 The same that applies to redirections also applies to URLs that are used on buttons in the UI where the user doesn't expect to land on a different domain/website, like "Cancel" buttons. There, in addition to unexpected/malicious target websites, XSS is also a topic. For this purpose, the [[###getSanitizedURLAttributeValue## macro>>doc:extensions:Extension.Velocity Macro.Macros.getSanitizedURLAttributeValue.WebHome]] has been introduced that both checks if the attribute is safe, i.e., not a script-URL, and if it is linking to a trusted domain (or the current domain). You can find an example use in [[restore.vm>>https://github.com/xwiki/xwiki-platform/blob/0ae047883e486d601e45b9dc388c7ce5696b5e57/xwiki-platform-core/xwiki-platform-flamingo/xwiki-platform-flamingo-skin/xwiki-platform-flamingo-skin-resources/src/main/resources/flamingo/restore.vm#L215-L220]].
178
179 == Access environment/resource files
180
181 When accessing a file in the servlet resource based on user input, there is a risk that the user input contains a path traversal attack. That means the value contains things like ##../..## to try to go out of the exepcted folder.
182
183 {{version since="17.10.5, 18.2.0"}}
184 To help protect against this kind of attack, it is recommended to avoid directly accessing files through the servlet API and instead use the ##org.xwiki.environment.Environment## API, and especially ##Environment#getResourceAsStream(String prefixPath, String resourcePath)## which allows indicating a parent folder in which the resource should be located, which is a very common use case. ##Environment#getResourceAsStream(String resourcePath)## will make sure the resource is not trying to go outside of the root resource folder (the root of the web application).
185
186 {{warning}}
187 But in some use cases (like the XWiki Debian packages) some of those resources are actually stored in other locations (like /etc/xwiki/) and then the web application folder contains links to those files. Tomcat (and probably others too) tend to report the real path of the resource behind the link and not the location of the link itself, effectively making the resource identified as being outside the resource root.
188 The property ##environment.servlet.allowedRealPaths## in the configuration file ##xwiki.properties## allows adding more allowed locations.
189 {{/warning}}
190 {{/version}}

Get Connected