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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
|
From d1f066bf2198bd46c5ba80cb5123b768ec16e37d Mon Sep 17 00:00:00 2001
From: Federico Mena Quintero <federico@gnome.org>
Date: Thu, 20 Jul 2023 11:12:53 -0600
Subject: [PATCH] (#996): Fix arbitrary file read when href has special
characters
In UrlResolver::resolve_href() we now explicitly disallow URLs that
have a query string ("?") or a fragment identifier ("#").
We also explicitly check for a base URL and not resolving to a path,
for example, "file:///base/foo.svg" + "." would resolve to
"file:///base/" - this is technically correct, but we don't want to
resolve to directories.
Also, we pass a canonicalized path name as a URL upstream, so that
g_file_new_from_url() will consume it later, instead of passing the
original and potentially malicious URL.
Fixes https://gitlab.gnome.org/GNOME/librsvg/-/issues/996
---
librsvg/rsvg-handle.c | 6 +-
rsvg_internals/src/allowed_url.rs | 229 +++++++++++++-----
.../src/filters/component_transfer.rs | 2 +-
tests/Makefile.am | 1 +
tests/fixtures/loading/bar.svg | 1 +
tests/fixtures/loading/foo.svg | 1 +
tests/fixtures/loading/subdir/baz.svg | 1 +
7 files changed, 180 insertions(+), 61 deletions(-)
create mode 100644 tests/fixtures/loading/bar.svg
create mode 100644 tests/fixtures/loading/foo.svg
create mode 100644 tests/fixtures/loading/subdir/baz.svg
diff --git a/librsvg/rsvg-handle.c b/librsvg/rsvg-handle.c
index 95364db34..f49e4d30e 100644
--- a/librsvg/rsvg-handle.c
+++ b/librsvg/rsvg-handle.c
@@ -78,7 +78,11 @@
* </listitem>
*
* <listitem>
- * All other URL schemes in references require a base URL. For
+ * URLs with queries ("?") or fragment identifiers ("#") are not allowed.
+ * </listitem>
+ *
+ * <listitem>
+ * All other URL schemes other than data: in references require a base URL. For
* example, this means that if you load an SVG with
* rsvg_handle_new_from_data() without calling rsvg_handle_set_base_uri(),
* then any referenced files will not be allowed (e.g. raster images to be
diff --git a/rsvg_internals/src/allowed_url.rs b/rsvg_internals/src/allowed_url.rs
index 3a99e00b8..ffa9a2315 100644
--- a/rsvg_internals/src/allowed_url.rs
+++ b/rsvg_internals/src/allowed_url.rs
@@ -2,9 +2,7 @@
use std::error;
use std::fmt;
-use std::io;
use std::ops::Deref;
-use std::path::{Path, PathBuf};
use url::Url;
use crate::error::HrefError;
@@ -37,6 +35,12 @@ pub enum AllowedUrlError {
/// or in one directory below the base file.
NotSiblingOrChildOfBaseFile,
+ /// Loaded file:// URLs cannot have a query part, e.g. `file:///foo?blah`
+ NoQueriesAllowed,
+
+ /// URLs may not have fragment identifiers at this stage
+ NoFragmentIdentifierAllowed,
+
/// Error when obtaining the file path or the base file path
InvalidPath,
@@ -59,6 +63,17 @@ impl AllowedUrl {
return Ok(AllowedUrl(url));
}
+ // Queries are not allowed.
+ if url.query().is_some() {
+ return Err(AllowedUrlError::NoQueriesAllowed);
+ }
+
+ // Fragment identifiers are not allowed. They should have been stripped
+ // upstream, by NodeId.
+ if url.fragment().is_some() {
+ return Err(AllowedUrlError::NoFragmentIdentifierAllowed);
+ }
+
// All other sources require a base url
if base_url.is_none() {
return Err(AllowedUrlError::BaseRequired);
@@ -81,6 +96,26 @@ impl AllowedUrl {
return Err(AllowedUrlError::DisallowedScheme);
}
+ // The rest of this function assumes file: URLs; guard against
+ // incorrect refactoring.
+ assert!(url.scheme() == "file");
+
+ // If we have a base_uri of "file:///foo/bar.svg", and resolve an href of ".",
+ // Url.parse() will give us "file:///foo/". We don't want that, so check
+ // if the last path segment is empty - it will not be empty for a normal file.
+
+ if let Some(segments) = url.path_segments() {
+ if segments
+ .last()
+ .expect("URL path segments always contain at last 1 element")
+ .is_empty()
+ {
+ return Err(AllowedUrlError::NotSiblingOrChildOfBaseFile);
+ }
+ } else {
+ unreachable!("the file: URL cannot have an empty path");
+ }
+
// We have two file: URIs. Now canonicalize them (remove .. and symlinks, etc.)
// and see if the directories match
@@ -98,13 +133,17 @@ impl AllowedUrl {
let base_parent = base_parent.unwrap();
- let url_canon =
- canonicalize(&url_path).map_err(|_| AllowedUrlError::CanonicalizationError)?;
- let parent_canon =
- canonicalize(&base_parent).map_err(|_| AllowedUrlError::CanonicalizationError)?;
-
- if url_canon.starts_with(parent_canon) {
- Ok(AllowedUrl(url))
+ let path_canon = url_path
+ .canonicalize()
+ .map_err(|_| AllowedUrlError::CanonicalizationError)?;
+ let parent_canon = base_parent
+ .canonicalize()
+ .map_err(|_| AllowedUrlError::CanonicalizationError)?;
+
+ if path_canon.starts_with(parent_canon) {
+ // Finally, convert the canonicalized path back to a URL.
+ let path_to_url = Url::from_file_path(path_canon).unwrap();
+ Ok(AllowedUrl(path_to_url))
} else {
Err(AllowedUrlError::NotSiblingOrChildOfBaseFile)
}
@@ -129,32 +168,22 @@ impl error::Error for AllowedUrlError {}
impl fmt::Display for AllowedUrlError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match *self {
- AllowedUrlError::HrefParseError(e) => write!(f, "href parse error: {}", e),
- AllowedUrlError::BaseRequired => write!(f, "base required"),
- AllowedUrlError::DifferentURISchemes => write!(f, "different URI schemes"),
- AllowedUrlError::DisallowedScheme => write!(f, "disallowed scheme"),
- AllowedUrlError::NotSiblingOrChildOfBaseFile => {
- write!(f, "not sibling or child of base file")
- }
- AllowedUrlError::InvalidPath => write!(f, "invalid path"),
- AllowedUrlError::BaseIsRoot => write!(f, "base is root"),
- AllowedUrlError::CanonicalizationError => write!(f, "canonicalization error"),
+ use AllowedUrlError::*;
+ match self {
+ HrefParseError(e) => write!(f, "URL parse error: {e}"),
+ BaseRequired => write!(f, "base required"),
+ DifferentUriSchemes => write!(f, "different URI schemes"),
+ DisallowedScheme => write!(f, "disallowed scheme"),
+ NotSiblingOrChildOfBaseFile => write!(f, "not sibling or child of base file"),
+ NoQueriesAllowed => write!(f, "no queries allowed"),
+ NoFragmentIdentifierAllowed => write!(f, "no fragment identifier allowed"),
+ InvalidPath => write!(f, "invalid path"),
+ BaseIsRoot => write!(f, "base is root"),
+ CanonicalizationError => write!(f, "canonicalization error"),
}
}
}
-// For tests, we don't want to touch the filesystem. In that case,
-// assume that we are being passed canonical file names.
-#[cfg(not(test))]
-fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf, io::Error> {
- path.as_ref().canonicalize()
-}
-#[cfg(test)]
-fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf, io::Error> {
- Ok(path.as_ref().to_path_buf())
-}
-
/// Parsed result of an href from an SVG or CSS file
///
/// Sometimes in SVG element references (e.g. the `href` in the `<feImage>` element) we
@@ -234,6 +263,8 @@ impl Href {
mod tests {
use super::*;
+ use std::path::PathBuf;
+
#[test]
fn disallows_relative_file_with_no_base_file() {
assert_eq!(
@@ -284,56 +315,136 @@ mod tests {
);
}
+ fn url_from_test_fixtures(filename_relative_to_librsvg_srcdir: &str) -> Url {
+ let path = PathBuf::from(filename_relative_to_librsvg_srcdir);
+ let absolute = path
+ .canonicalize()
+ .expect("files from test fixtures are supposed to canonicalize");
+ Url::from_file_path(absolute).unwrap()
+ }
+
#[test]
fn allows_relative() {
- assert_eq!(
- AllowedUrl::from_href(
- "foo.svg",
- Some(Url::parse("file:///example/bar.svg").unwrap()).as_ref()
- )
- .unwrap()
- .as_ref(),
- "file:///example/foo.svg",
- );
+ let resolved = AllowedUrl::from_href(
+ "foo.svg",
+ Some(url_from_test_fixtures("../tests/fixtures/loading/bar.svg")).as_ref()
+ ).unwrap();
+
+ let resolved_str = resolved.as_str();
+ assert!(resolved_str.ends_with("/loading/foo.svg"));
}
#[test]
fn allows_sibling() {
- assert_eq!(
- AllowedUrl::from_href(
- "file:///example/foo.svg",
- Some(Url::parse("file:///example/bar.svg").unwrap()).as_ref()
- )
- .unwrap()
- .as_ref(),
- "file:///example/foo.svg",
- );
+ let sibling = url_from_test_fixtures("../tests/fixtures/loading/foo.svg");
+ let resolved = AllowedUrl::from_href(
+ sibling.as_str(),
+ Some(url_from_test_fixtures("../tests/fixtures/loading/bar.svg")).as_ref()
+ ).unwrap();
+
+ let resolved_str = resolved.as_str();
+ assert!(resolved_str.ends_with("/loading/foo.svg"));
}
#[test]
fn allows_child_of_sibling() {
- assert_eq!(
- AllowedUrl::from_href(
- "file:///example/subdir/foo.svg",
- Some(Url::parse("file:///example/bar.svg").unwrap()).as_ref()
- )
- .unwrap()
- .as_ref(),
- "file:///example/subdir/foo.svg",
- );
+ let child_of_sibling = url_from_test_fixtures("../tests/fixtures/loading/subdir/baz.svg");
+ let resolved = AllowedUrl::from_href(
+ child_of_sibling.as_str(),
+ Some(url_from_test_fixtures("../tests/fixtures/loading/bar.svg")).as_ref()
+ ).unwrap();
+
+ let resolved_str = resolved.as_str();
+ assert!(resolved_str.ends_with("/loading/subdir/baz.svg"));
}
+ // Ignore on Windows since we test for /etc/passwd
+ #[cfg(unix)]
#[test]
fn disallows_non_sibling() {
assert_eq!(
AllowedUrl::from_href(
"file:///etc/passwd",
- Some(Url::parse("file:///example/bar.svg").unwrap()).as_ref()
+ Some(url_from_test_fixtures("../tests/fixtures/loading/bar.svg")).as_ref()
),
Err(AllowedUrlError::NotSiblingOrChildOfBaseFile)
);
}
+ #[test]
+ fn disallows_queries() {
+ assert!(matches!(
+ AllowedUrl::from_href(
+ ".?../../../../../../../../../../etc/passwd",
+ Some(url_from_test_fixtures("../tests/fixtures/loading/bar.svg")).as_ref(),
+ ),
+ Err(AllowedUrlError::NoQueriesAllowed)
+ ));
+ }
+
+ #[test]
+ fn disallows_weird_relative_uris() {
+ let base_url = url_from_test_fixtures("../tests/fixtures/loading/bar.svg");
+
+ assert!(
+ AllowedUrl::from_href(
+ ".@../../../../../../../../../../etc/passwd",
+ Some(&base_url),
+ ).is_err()
+ );
+ assert!(
+ AllowedUrl::from_href(
+ ".$../../../../../../../../../../etc/passwd",
+ Some(&base_url),
+ ).is_err()
+ );
+ assert!(
+ AllowedUrl::from_href(
+ ".%../../../../../../../../../../etc/passwd",
+ Some(&base_url),
+ ).is_err()
+ );
+ assert!(
+ AllowedUrl::from_href(
+ ".*../../../../../../../../../../etc/passwd",
+ Some(&base_url),
+ ).is_err()
+ );
+ assert!(
+ AllowedUrl::from_href(
+ "~/../../../../../../../../../../etc/passwd",
+ Some(&base_url),
+ ).is_err()
+ );
+ }
+
+ #[test]
+ fn disallows_dot_sibling() {
+ println!("cwd: {:?}", std::env::current_dir());
+ let base_url = url_from_test_fixtures("../tests/fixtures/loading/bar.svg");
+
+ assert!(matches!(
+ AllowedUrl::from_href(".", Some(&base_url)),
+ Err(AllowedUrlError::NotSiblingOrChildOfBaseFile)
+ ));
+ assert!(matches!(
+ AllowedUrl::from_href(".#../../../../../../../../../../etc/passwd", Some(&base_url)),
+ Err(AllowedUrlError::NoFragmentIdentifierAllowed)
+ ));
+ }
+
+ #[test]
+ fn disallows_fragment() {
+ // AllowedUrl::from_href() explicitly disallows fragment identifiers.
+ // This is because they should have been stripped before calling that function,
+ // by the Iri machinery.
+
+ assert!(matches!(
+ AllowedUrl::from_href("bar.svg#fragment", Some(Url::parse("https://example.com/foo.svg").unwrap()).as_ref()),
+ Err(AllowedUrlError::NoFragmentIdentifierAllowed)
+ ));
+ }
+
#[test]
fn parses_href() {
assert_eq!(
diff --git a/rsvg_internals/src/filters/component_transfer.rs b/rsvg_internals/src/filters/component_transfer.rs
index 235435ffa..6845eac18 100644
--- a/rsvg_internals/src/filters/component_transfer.rs
+++ b/rsvg_internals/src/filters/component_transfer.rs
@@ -261,7 +261,7 @@ macro_rules! func_or_default {
}
}
_ => &$func_default,
- };
+ }
};
}
diff --git a/tests/Makefile.am b/tests/Makefile.am
index 13c2d51f2..b3faf2da5 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -82,6 +82,7 @@ dist_installed_test_data = \
$(wildcard $(srcdir)/fixtures/errors/*) \
$(wildcard $(srcdir)/fixtures/infinite-loop/*) \
$(wildcard $(srcdir)/fixtures/loading/*) \
+ $(wildcard $(srcdir)/fixtures/loading/subdir/*) \
$(wildcard $(srcdir)/fixtures/reftests/*.css) \
$(wildcard $(srcdir)/fixtures/reftests/*.svg) \
$(wildcard $(srcdir)/fixtures/reftests/*.png) \
diff --git a/tests/fixtures/loading/bar.svg b/tests/fixtures/loading/bar.svg
new file mode 100644
index 000000000..304670099
--- /dev/null
+++ b/tests/fixtures/loading/bar.svg
@@ -0,0 +1 @@
+<!-- Empty file, used just to test URL validation -->
diff --git a/tests/fixtures/loading/foo.svg b/tests/fixtures/loading/foo.svg
new file mode 100644
index 000000000..304670099
--- /dev/null
+++ b/tests/fixtures/loading/foo.svg
@@ -0,0 +1 @@
+<!-- Empty file, used just to test URL validation -->
diff --git a/tests/fixtures/loading/subdir/baz.svg b/tests/fixtures/loading/subdir/baz.svg
new file mode 100644
index 000000000..304670099
--- /dev/null
+++ b/tests/fixtures/loading/subdir/baz.svg
@@ -0,0 +1 @@
+<!-- Empty file, used just to test URL validation -->
--
GitLab
|