-
Notifications
You must be signed in to change notification settings - Fork 234
Expand file tree
/
Copy pathStylingPolicy.java
More file actions
291 lines (261 loc) · 10.1 KB
/
StylingPolicy.java
File metadata and controls
291 lines (261 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// Copyright (c) 2011, Mike Samuel
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the OWASP nor the names of its contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package org.owasp.html;
import java.util.List;
import javax.annotation.Nullable;
import org.owasp.html.AttributePolicy.JoinableAttributePolicy;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
/**
* An HTML sanitizer policy that tries to preserve simple CSS by white-listing
* property values and splitting combo properties into multiple more specific
* ones to reduce the attack-surface.
*/
@TCB
final class StylingPolicy implements JoinableAttributePolicy {
final CssSchema cssSchema;
final Function<String, String> urlRewriter;
StylingPolicy(CssSchema cssSchema, Function<String, String> urlRewriter) {
this.cssSchema = cssSchema;
this.urlRewriter = urlRewriter;
}
public @Nullable String apply(
String elementName, String attributeName, String value) {
return value != null ? sanitizeCssProperties(value) : null;
}
/**
* Lossy filtering of CSS properties that allows textual styling that affects
* layout, but does not allow breaking out of a clipping region, absolute
* positioning, image loading, tab index changes, or code execution.
*
* @return A sanitized version of the input.
*/
@VisibleForTesting
String sanitizeCssProperties(String style) {
final StringBuilder sanitizedCss = new StringBuilder();
CssGrammar.parsePropertyGroup(style, new CssGrammar.PropertyHandler() {
CssSchema.Property cssProperty = CssSchema.DISALLOWED;
List<CssSchema.Property> cssProperties = null;
int propertyStart = 0;
boolean hasTokens;
boolean inQuotedIdents;
String lastToken = null;
private void emitToken(String token) {
closeQuotedIdents();
if (hasTokens) { sanitizedCss.append(' '); }
sanitizedCss.append(token);
hasTokens = true;
}
private void closeQuotedIdents() {
if (inQuotedIdents) {
sanitizedCss.append('\'');
inQuotedIdents = false;
}
}
private void sanitizeAndAppendUrl(String urlContent) {
String rewrittenUrl = urlRewriter.apply(urlContent);
if (rewrittenUrl != null && !rewrittenUrl.isEmpty()) {
if (hasTokens) { sanitizedCss.append(' '); }
sanitizedCss.append("url('").append(rewrittenUrl).append("')");
hasTokens = true;
}
}
public void url(String token) {
closeQuotedIdents();
if (cssProperty != null) {
if ((cssProperty.bits & CssSchema.BIT_URL) != 0) {
String urlContent = CssGrammar.cssContent(
Strings.stripHtmlSpaces( // TODO: css spaces
token.substring(4, token.length() - 1)));
sanitizeAndAppendUrl(urlContent);
}
}
lastToken = token;
}
public void startProperty(String propertyName) {
if (cssProperties != null) { cssProperties.clear(); }
cssProperty = cssSchema.forKey(propertyName);
hasTokens = false;
propertyStart = sanitizedCss.length();
if (sanitizedCss.length() != 0) {
sanitizedCss.append(';');
}
sanitizedCss.append(propertyName).append(':');
}
public void startFunction(String uncanonToken) {
closeQuotedIdents();
if (cssProperties == null) { cssProperties = Lists.newArrayList(); }
cssProperties.add(cssProperty);
String token = Strings.toLowerCase(uncanonToken);
String key = cssProperty.fnKeys.get(token);
cssProperty = key != null
? cssSchema.forKey(key)
: CssSchema.DISALLOWED;
if (cssProperty != CssSchema.DISALLOWED) {
emitToken(token);
}
lastToken = token;
}
public void quotedString(String token) {
closeQuotedIdents();
// The contents of a quoted string could be treated as
// 1. a run of space-separated words, as in a font family name,
// 2. as a URL,
// 3. as plain text content as in a list-item bullet,
// 4. or it could be ambiguous as when multiple bits are set.
int meaning =
cssProperty.bits
& (CssSchema.BIT_UNRESERVED_WORD | CssSchema.BIT_URL);
if ((meaning & (meaning - 1)) == 0) { // meaning is unambiguous
if (meaning == CssSchema.BIT_UNRESERVED_WORD
&& token.length() > 2
&& isAlphanumericOrSpaceOrHyphen(token, 1, token.length() - 1)) {
emitToken(Strings.toLowerCase(token));
} else if (meaning == CssSchema.BIT_URL) {
// convert to a URL token and hand-off to the appropriate method
sanitizeAndAppendUrl(CssGrammar.cssContent(token));
}
}
lastToken = token;
}
public void quantity(String token) {
int test = token.startsWith("-")
? CssSchema.BIT_NEGATIVE : CssSchema.BIT_QUANTITY;
if ((cssProperty.bits & test) != 0
// font-weight uses 100, 200, 300, etc.
|| cssProperty.literals.contains(token)) {
emitToken(token);
}
lastToken = token;
}
public void punctuation(String token) {
closeQuotedIdents();
if (cssProperty.literals.contains(token)) {
emitToken(token);
}
lastToken = token;
}
private static final int IDENT_TO_STRING =
CssSchema.BIT_UNRESERVED_WORD | CssSchema.BIT_STRING;
public void identifier(String uncanonToken) {
String token = Strings.toLowerCase(uncanonToken);
if ("!".equals(lastToken) && "important".equals(token)) {
emitToken("!important");
} else if (cssProperty.literals.contains(token)) {
emitToken(token);
} else if ((cssProperty.bits & IDENT_TO_STRING) == IDENT_TO_STRING) {
if (!inQuotedIdents) {
inQuotedIdents = true;
if (hasTokens) { sanitizedCss.append(' '); }
sanitizedCss.append('\'');
hasTokens = true;
} else {
sanitizedCss.append(' ');
}
sanitizedCss.append(Strings.toLowerCase(token));
}
lastToken = token;
}
public void hash(String token) {
closeQuotedIdents();
if ((cssProperty.bits & CssSchema.BIT_HASH_VALUE) != 0) {
emitToken(Strings.toLowerCase(token));
}
lastToken = token;
}
public void endProperty() {
if (!hasTokens) {
sanitizedCss.setLength(propertyStart);
} else {
closeQuotedIdents();
}
lastToken = null;
}
public void endFunction(String token) {
if (cssProperty != CssSchema.DISALLOWED) { emitToken(")"); }
cssProperty = cssProperties.remove(cssProperties.size() - 1);
lastToken = ")";
}
});
return sanitizedCss.length() == 0 ? null : sanitizedCss.toString();
}
static boolean isAlphanumericOrSpaceOrHyphen(
String token, int start, int end) {
for (int i = start; i < end; ++i) {
char ch = token.charAt(i);
if (ch <= 0x20) {
if (ch != '\t' && ch != ' ') {
return false;
}
} else {
int chLower = ch | 32;
if (!(('0' <= chLower && chLower <= '9')
|| ('a' <= chLower && chLower <= 'z')
|| ('-' == ch))) {
return false;
}
}
}
return true;
}
@Override
public boolean equals(Object o) {
return o != null && getClass() == o.getClass()
&& cssSchema.equals(((StylingPolicy) o).cssSchema);
}
@Override
public int hashCode() {
return cssSchema.hashCode();
}
public Joinable.JoinStrategy<JoinableAttributePolicy> getJoinStrategy() {
return StylingPolicyJoinStrategy.INSTANCE;
}
static final class StylingPolicyJoinStrategy
implements Joinable.JoinStrategy<JoinableAttributePolicy> {
static final StylingPolicyJoinStrategy INSTANCE =
new StylingPolicyJoinStrategy();
public JoinableAttributePolicy join(
Iterable<? extends JoinableAttributePolicy> toJoin) {
Function<String, String> identity = Functions.<String>identity();
CssSchema cssSchema = null;
Function<String, String> urlRewriter = identity;
for (JoinableAttributePolicy p : toJoin) {
StylingPolicy sp = (StylingPolicy) p;
cssSchema = cssSchema == null
? sp.cssSchema : CssSchema.union(cssSchema, sp.cssSchema);
urlRewriter = urlRewriter.equals(identity)
|| urlRewriter.equals(sp.urlRewriter)
? sp.urlRewriter
: Functions.compose(urlRewriter, sp.urlRewriter);
}
return new StylingPolicy(cssSchema, urlRewriter);
}
}
}