test_external_camera_ssrf.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. """The RTSP camera paths must not become a request generator for arbitrary hosts.
  2. `_sanitize_camera_url` is the SSRF boundary for user-configured camera URLs. It
  3. was applied to the MJPEG and snapshot paths but not to the two RTSP ones, which
  4. handed the URL to `ffmpeg -i` unchecked — and ffmpeg's `-i` speaks http, tcp,
  5. file and everything else it was built with, so `camera_type=rtsp` was a way to
  6. name any destination and any protocol.
  7. Wiring the guard in is only half of it. The guard rebuilt URLs from
  8. `parsed.hostname`, which drops credentials and unbrackets IPv6 literals, and it
  9. recognised loopback by comparing against four spellings of it. So these tests
  10. pin three things at once: the RTSP paths refuse what they should, the guard
  11. recognises a destination however it is written, and a real camera — which
  12. usually means an authenticated one — still works.
  13. """
  14. from unittest.mock import patch
  15. import pytest
  16. from backend.app.services.external_camera import (
  17. _blocked_host_reason,
  18. _capture_rtsp_frame,
  19. _safe_usb_device_path,
  20. _sanitize_camera_url,
  21. _stream_rtsp,
  22. )
  23. from backend.tests._fixtures.external_camera import fake_ffmpeg, spawn_spy
  24. RTSP_SCHEMES = ("rtsp", "rtsps")
  25. HTTP_SCHEMES = ("http", "https")
  26. class TestTheHostsWeRefuse:
  27. """Loopback, the unspecified address and link-local, however they are spelled."""
  28. @pytest.mark.parametrize(
  29. "host",
  30. [
  31. "127.0.0.1",
  32. "127.0.0.2", # the whole 127/8 range, not just .1
  33. "127.1", # short form
  34. "2130706433", # decimal
  35. "0177.0.0.1", # octal
  36. "0x7f.0.0.1", # hex
  37. "[::1]",
  38. "[::ffff:127.0.0.1]", # loopback wearing an IPv6 spelling
  39. "localhost",
  40. "sub.localhost",
  41. ],
  42. )
  43. def test_loopback_is_refused(self, host):
  44. assert _sanitize_camera_url(f"rtsp://{host}:554/live", RTSP_SCHEMES) is None
  45. @pytest.mark.parametrize("host", ["0.0.0.0", "[::]"]) # nosec B104
  46. def test_the_unspecified_address_is_refused(self, host):
  47. assert _sanitize_camera_url(f"rtsp://{host}:554/live", RTSP_SCHEMES) is None
  48. @pytest.mark.parametrize(
  49. "host",
  50. [
  51. "169.254.169.254", # AWS/GCP/Azure metadata
  52. "169.254.1.1", # the rest of the range, not just the metadata IP
  53. "[fe80::1]",
  54. "metadata.google.internal",
  55. "metadata.google",
  56. ],
  57. )
  58. def test_link_local_and_metadata_are_refused(self, host):
  59. assert _sanitize_camera_url(f"rtsp://{host}/live", RTSP_SCHEMES) is None
  60. def test_the_reason_is_reported_for_logging(self):
  61. assert _blocked_host_reason("2130706433") == "loopback"
  62. assert _blocked_host_reason("169.254.169.254") is not None
  63. assert _blocked_host_reason("192.168.1.50") is None
  64. class TestTheCamerasWeAllow:
  65. """LAN is allowed on purpose — that is where cameras are."""
  66. @pytest.mark.parametrize(
  67. "url",
  68. [
  69. "rtsp://192.168.1.50:554/live",
  70. "rtsp://10.0.0.5/stream1",
  71. "rtsp://172.16.4.9:8554/cam",
  72. "rtsp://[fd00::1]:554/live", # unique-local IPv6
  73. "rtsp://cam.lan/live",
  74. "rtsps://camera.example.com:322/stream",
  75. ],
  76. )
  77. def test_a_camera_url_survives(self, url):
  78. assert _sanitize_camera_url(url, RTSP_SCHEMES) is not None
  79. def test_a_hostname_is_not_resolved(self):
  80. """A name that would resolve to loopback still passes.
  81. Not an oversight: aiohttp and ffmpeg resolve independently afterwards,
  82. so a lookup here decides nothing (DNS rebinding) while costing a DNS
  83. round trip on every capture. Pinned so the omission stays deliberate.
  84. """
  85. assert _sanitize_camera_url("rtsp://localtest.me/live", RTSP_SCHEMES) is not None
  86. class TestWhatTheGuardMustNotDestroy:
  87. """Most RTSP cameras carry their login in the URL. Stripping it would turn
  88. every one of them into an authentication failure — a worse outage than the
  89. hole being closed."""
  90. def test_credentials_survive(self):
  91. url = "rtsp://admin:hunter2@192.168.1.50:554/live"
  92. assert _sanitize_camera_url(url, RTSP_SCHEMES) == url
  93. def test_percent_encoded_credentials_survive_byte_for_byte(self):
  94. """urlparse's .username/.password are already decoded, so rebuilding
  95. from them would corrupt any password containing an @ or a :."""
  96. url = "rtsp://ad%40min:p%3Ass%40word@192.168.1.50:554/live"
  97. assert _sanitize_camera_url(url, RTSP_SCHEMES) == url
  98. def test_an_ipv6_literal_keeps_its_brackets(self):
  99. """Without them the result is not a URL any client can parse."""
  100. assert _sanitize_camera_url("rtsp://[fd00::1]:554/live", RTSP_SCHEMES) == "rtsp://[fd00::1]:554/live"
  101. def test_http_cameras_keep_their_basic_auth_too(self):
  102. url = "http://admin:hunter2@192.168.1.50/stream.mjpg"
  103. assert _sanitize_camera_url(url, HTTP_SCHEMES) == url
  104. def test_port_query_and_fragment_survive(self):
  105. url = "rtsp://192.168.1.50:8554/live?channel=2&subtype=1#frag"
  106. assert _sanitize_camera_url(url, RTSP_SCHEMES) == url
  107. class TestSchemeAllowlist:
  108. """What keeps an ffmpeg input a camera fetch rather than a fetch."""
  109. @pytest.mark.parametrize(
  110. "url",
  111. [
  112. "http://192.168.1.50:8080/internal",
  113. "https://192.168.1.50/internal",
  114. "tcp://192.168.1.50:22",
  115. "file:///etc/passwd",
  116. "concat:/etc/passwd",
  117. "udp://192.168.1.50:1234",
  118. "ftp://192.168.1.50/x",
  119. ],
  120. )
  121. def test_only_rtsp_reaches_the_rtsp_paths(self, url):
  122. assert _sanitize_camera_url(url, RTSP_SCHEMES) is None
  123. def test_rtsp_does_not_reach_the_http_paths(self):
  124. assert _sanitize_camera_url("rtsp://192.168.1.50/live", HTTP_SCHEMES) is None
  125. @pytest.mark.parametrize("url", ["", "not a url", "rtsp://", "://192.168.1.50/x"])
  126. def test_malformed_input_is_refused(self, url):
  127. assert _sanitize_camera_url(url, RTSP_SCHEMES) is None
  128. class TestRtspCaptureRefusesUnsafeUrls:
  129. """`_capture_rtsp_frame` — the one-shot path behind the test-connection
  130. endpoint, which takes url and camera_type straight off the query string."""
  131. @pytest.mark.asyncio
  132. @pytest.mark.parametrize(
  133. "url",
  134. [
  135. "http://127.0.0.1:8080/internal-service", # the reported PoC
  136. "http://192.168.1.100:8080/any-image.jpg",
  137. "file:///etc/passwd",
  138. "rtsp://127.0.0.1:554/live",
  139. "rtsp://2130706433:554/live",
  140. "rtsp://169.254.169.254/live",
  141. ],
  142. )
  143. async def test_no_process_is_spawned(self, url):
  144. with fake_ffmpeg(), spawn_spy() as spawn:
  145. assert await _capture_rtsp_frame(url, timeout=5) is None
  146. spawn.assert_not_awaited()
  147. @pytest.mark.asyncio
  148. async def test_a_real_camera_still_captures(self):
  149. with fake_ffmpeg(), spawn_spy() as spawn:
  150. frame = await _capture_rtsp_frame("rtsp://admin:hunter2@192.168.1.50:554/live", timeout=5)
  151. assert frame is not None
  152. cmd = spawn.await_args.args
  153. assert "rtsp://admin:hunter2@192.168.1.50:554/live" in cmd, (
  154. "the camera's credentials must reach ffmpeg or every authenticated camera breaks"
  155. )
  156. @pytest.mark.asyncio
  157. async def test_ffmpeg_is_confined_to_rtsp_protocols(self):
  158. """Belt and braces behind the scheme check: a stream that references
  159. something outside itself must not be able to pull it in."""
  160. with fake_ffmpeg(), spawn_spy() as spawn:
  161. await _capture_rtsp_frame("rtsp://192.168.1.50:554/live", timeout=5)
  162. cmd = spawn.await_args.args
  163. whitelist = cmd[cmd.index("-protocol_whitelist") + 1].split(",")
  164. assert "rtsp" in whitelist
  165. assert "file" not in whitelist
  166. assert "http" not in whitelist
  167. class TestRtspStreamRefusesUnsafeUrls:
  168. """`_stream_rtsp` — the live-view path, and the one the report missed."""
  169. @pytest.mark.asyncio
  170. @pytest.mark.parametrize(
  171. "url",
  172. [
  173. "http://127.0.0.1:8080/internal-service",
  174. "rtsp://127.0.0.1:554/live",
  175. "rtsp://[::ffff:127.0.0.1]:554/live",
  176. "file:///etc/passwd",
  177. ],
  178. )
  179. async def test_no_process_is_spawned(self, url):
  180. with fake_ffmpeg(), spawn_spy() as spawn:
  181. frames = [frame async for frame in _stream_rtsp(url, fps=5)]
  182. assert frames == []
  183. spawn.assert_not_awaited()
  184. @pytest.mark.asyncio
  185. async def test_a_real_camera_still_reaches_ffmpeg(self):
  186. with fake_ffmpeg(), spawn_spy(returncode=None) as spawn:
  187. [frame async for frame in _stream_rtsp("rtsp://admin:hunter2@192.168.1.50:554/live", fps=5)]
  188. spawn.assert_awaited_once()
  189. cmd = spawn.await_args.args
  190. assert "rtsp://admin:hunter2@192.168.1.50:554/live" in cmd
  191. assert "-protocol_whitelist" in cmd
  192. class TestUsbDevicePaths:
  193. """The USB paths take a device path from the same request field, and the
  194. streaming one used to check only that it started with /dev/video."""
  195. @pytest.mark.parametrize(
  196. "device",
  197. [
  198. "/dev/video/../../etc/passwd",
  199. "/dev/videos/../../etc/shadow",
  200. "/dev/video0; rm -rf /",
  201. "/etc/passwd",
  202. "/dev/video100", # three digits is not a device number
  203. "",
  204. ],
  205. )
  206. def test_a_path_that_is_not_a_device_node_is_refused(self, device):
  207. assert _safe_usb_device_path(device) is None
  208. def test_a_missing_device_is_refused(self):
  209. """Existence is part of the check — ffmpeg must never be pointed at a
  210. path just because it is shaped like one."""
  211. with patch("backend.app.services.external_camera.Path") as path_cls:
  212. path_cls.return_value.exists.return_value = False
  213. assert _safe_usb_device_path("/dev/video0") is None
  214. def test_the_path_is_rebuilt_from_the_device_number(self):
  215. with patch("backend.app.services.external_camera.Path") as path_cls:
  216. path_cls.return_value.exists.return_value = True
  217. path_cls.return_value.__str__.return_value = "/dev/video7"
  218. assert _safe_usb_device_path("/dev/video7") == "/dev/video7"
  219. path_cls.assert_called_once_with("/dev/video7")