Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added warning when adding torrent from invalid HTTPS #8225

Merged
merged 1 commit into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions src/tribler/core/libtorrent/restapi/torrentinfo_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import libtorrent as lt
from aiohttp import (
BaseConnector,
ClientConnectorCertificateError,
ClientConnectorError,
ClientResponseError,
ClientSession,
Expand All @@ -20,7 +21,7 @@
)
from aiohttp_apispec import docs
from ipv8.REST.schema import schema
from marshmallow.fields import String
from marshmallow.fields import Boolean, String
from yarl import URL

from tribler.core.database.orm_bindings.torrent_metadata import tdef_to_metadata_dict
Expand Down Expand Up @@ -65,7 +66,8 @@ def recursive_unicode(obj: Iterable, ignore_errors: bool = False) -> Iterable:


async def query_uri(uri: str, connector: BaseConnector | None = None, headers: LooseHeaders | None = None,
timeout: ClientTimeout | None = None, return_json: bool = False, ) -> bytes | dict:
timeout: ClientTimeout | None = None, return_json: bool = False,
valid_cert: bool = True) -> bytes | dict:
"""
Retrieve the response for the given aiohttp context.
"""
Expand All @@ -76,7 +78,7 @@ async def query_uri(uri: str, connector: BaseConnector | None = None, headers: L
kwargs["timeout"] = timeout

async with ClientSession(connector=connector, raise_for_status=True) as session, \
await session.get(uri, **kwargs) as response:
await session.get(uri, ssl=valid_cert, **kwargs) as response:
if return_json:
return await response.json(content_type=None)
return await response.read()
Expand Down Expand Up @@ -112,7 +114,8 @@ def __init__(self, download_manager: DownloadManager) -> None:
responses={
200: {
"description": "Return a hex-encoded json-encoded string with torrent metainfo",
"schema": schema(GetMetainfoResponse={"metainfo": String})
"schema": schema(GetMetainfoResponse={"metainfo": String, "download_exists": Boolean,
"valid_certificate": Boolean})
}
}
)
Expand All @@ -136,6 +139,7 @@ async def get_torrent_info(self, request: Request) -> RESTResponse: # noqa: C90

uri = await unshorten(p_uri)
scheme = URL(uri).scheme
valid_cert = True

if scheme == "file":
file_path = url_to_path(uri)
Expand All @@ -147,7 +151,11 @@ async def get_torrent_info(self, request: Request) -> RESTResponse: # noqa: C90
status=HTTP_INTERNAL_SERVER_ERROR)
elif scheme in ("http", "https"):
try:
response = await query_uri(uri)
try:
response = await query_uri(uri)
except ClientConnectorCertificateError:
response = await query_uri(uri, valid_cert=False)
valid_cert = False
except (ServerConnectionError, ClientResponseError, SSLError, ClientConnectorError,
AsyncTimeoutError, ValueError) as e:
self._logger.warning("Error while querying http uri: %s", str(e))
Expand Down Expand Up @@ -219,7 +227,8 @@ async def get_torrent_info(self, request: Request) -> RESTResponse: # noqa: C90
json_dump = json.dumps(ready_for_unicode, ensure_ascii=False)

return RESTResponse({"metainfo": hexlify(json_dump.encode()).decode(),
"download_exists": download and not download_is_metainfo_request})
"download_exists": download and not download_is_metainfo_request,
"valid_certificate": valid_cert})

@docs(
tags=["Libtorrent"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
from ssl import SSLError
from unittest.mock import AsyncMock, Mock, patch

from aiohttp import ClientConnectorError, ClientResponseError, ServerConnectionError
from aiohttp import ClientConnectorCertificateError, ClientConnectorError, ClientResponseError, ServerConnectionError
from ipv8.test.base import TestBase
from ipv8.util import succeed

import tribler
from tribler.core.libtorrent.download_manager.download_manager import MetainfoLookup
Expand Down Expand Up @@ -352,6 +353,28 @@ async def test_get_torrent_info_https_valueerror(self) -> None:
self.assertEqual(HTTP_INTERNAL_SERVER_ERROR, response.status)
self.assertEqual("test", response_body_json["error"])

async def test_get_torrent_info_https_certificate_error(self) -> None:
"""
Test if it is returned that an invalid certificate for an HTTPS request was used.
"""
async def server_response(_: str, valid_cert: bool = True) -> bytes:
"""
Pretend that the request causes a certificate error in strict "valid_cert" mode.
"""
if valid_cert:
raise ClientConnectorCertificateError(None, RuntimeError("Invalid certificate test error!"))
return await succeed(b"d4:infod6:lengthi0eee")
with patch.dict(tribler.core.libtorrent.restapi.torrentinfo_endpoint.__dict__,
{"unshorten": mock_unshorten}), \
patch("tribler.core.libtorrent.restapi.torrentinfo_endpoint.query_uri",
server_response):
response = await self.endpoint.get_torrent_info(GetTorrentInfoRequest({"hops": 0,
"uri": "https://127.0.0.1/file"}))
response_body_json = await response_to_json(response)

self.assertEqual(200, response.status)
self.assertFalse(response_body_json["valid_certificate"])

async def test_get_torrent_info_http_no_metainfo(self) -> None:
"""
Test if a graceful error is returned when no metainfo is available for a http link.
Expand Down
1 change: 1 addition & 0 deletions src/tribler/ui/public/locales/en_US.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"Download": "Download",
"Cancel": "Cancel",
"LoadingTorrent": "Loading torrent files {{method, string}}...",
"HTTPSCertificateInvalid": "The server has an invalid HTTPS certificate!\nAn attacker could have given you the wrong torrent.",
"anonymously": "anonymously",
"directly": "directly",
"MagnetDialogInputLabel": "Please enter the URL/magnet link in the field below:",
Expand Down
1 change: 1 addition & 0 deletions src/tribler/ui/public/locales/es_ES.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"Download": "Descarga",
"Cancel": "Cancelar",
"LoadingTorrent": "Cargando archivos torrent {{method, string}}...",
"HTTPSCertificateInvalid": "¡El servidor tiene un certificado HTTPS no válido!\nUn atacante podría haberte proporcionado el torrent equivocado.",
"anonymously": "anónimamente",
"directly": "directamente",
"MagnetDialogInputLabel": "Introduzca el enlace URL/magnet en el siguiente recuadro:",
Expand Down
1 change: 1 addition & 0 deletions src/tribler/ui/public/locales/ko_KR.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"Download": "내려받기",
"Cancel": "취소",
"LoadingTorrent": "토렌트 파일 {{method, string}}을(를) 불러오는 중...",
"HTTPSCertificateInvalid": "서버에 잘못된 HTTPS 인증서가 있습니다!\n공격자가 잘못된 토렌트를 제공했을 수도 있습니다.",
"anonymously": "무기명",
"directly": "직접",
"MagnetDialogInputLabel": "아래에 URL/마그넷 링크를 입력 :",
Expand Down
2 changes: 2 additions & 0 deletions src/tribler/ui/public/locales/pt_BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@
"DownloadTorrent": "Baixar torrent",
"Download": "Download",
"Cancel": "Cancelar",
"LoadingTorrent": "Carregando arquivos torrent {{method, string}}...",
"HTTPSCertificateInvalid": "O servidor possui um certificado HTTPS inválido!\nUm invasor pode ter fornecido o torrent errado.",
"MagnetDialogInputLabel": "Por favor adicione o link URL/magnet no campo abaixo:",
"MagnetDialogHeader": "Adicionar torrent de um link URL/magnet",
"MagnetDialogError": "Não foi possível processar URL/link magnético",
Expand Down
1 change: 1 addition & 0 deletions src/tribler/ui/public/locales/ru_RU.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"Download": "Входящий",
"Cancel": "Отмена",
"LoadingTorrent": "Загружаем список файлов торрента {{method, string}}...",
"HTTPSCertificateInvalid": "Сервер имеет недействительный сертификат HTTPS!\nЗлоумышленник мог предоставить вам неправильный торрент.",
"anonymously": "анонимно",
"directly": "напрямую",
"MagnetDialogInputLabel": "Пожалуйста, введите URL/magnet-ссылку в поле ниже:",
Expand Down
1 change: 1 addition & 0 deletions src/tribler/ui/public/locales/zh_CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
"Download": "下载",
"Cancel": "取消",
"LoadingTorrent": "正在载入种子文件 {{method, string}}……",
"HTTPSCertificateInvalid": "服务器的 HTTPS 证书无效!\n攻击者可能给您提供了错误的种子。",
"anonymously": "匿名",
"directly": "直接",
"MagnetDialogInputLabel": "请在下面字段输入 URL/磁力链接:",
Expand Down
10 changes: 9 additions & 1 deletion src/tribler/ui/src/dialogs/SaveAs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { Settings } from "@/models/settings.model";
import { useTranslation } from "react-i18next";
import { TFunction } from 'i18next';
import { PathInput } from "@/components/path-input";
import { ChevronDown, ChevronRight } from "lucide-react";
import { ChevronDown, ChevronRight, AlertTriangle } from "lucide-react";
import { FileTreeItem } from "@/models/file.model";


Expand Down Expand Up @@ -95,6 +95,7 @@ export default function SaveAs(props: SaveAsProps & JSX.IntrinsicAttributes & Di

const [settings, setSettings] = useState<Settings | undefined>();
const [error, setError] = useState<string | undefined>();
const [warning, setWarning] = useState<string | undefined>();
const [exists, setExists] = useState<boolean>(false);
const [files, setFiles] = useState<FileTreeItem[]>([]);

Expand Down Expand Up @@ -164,6 +165,7 @@ export default function SaveAs(props: SaveAsProps & JSX.IntrinsicAttributes & Di
setFiles(files);
setParams((prev) => ({ ...prev, selected_files: getSelectedFilesFromTree(files[0]) }));
setExists(!!response.download_exists);
setWarning((!('valid_certificate' in response) || (response.valid_certificate == true)) ? undefined : t("HTTPSCertificateInvalid"));
}
}
reload();
Expand Down Expand Up @@ -268,6 +270,12 @@ export default function SaveAs(props: SaveAsProps & JSX.IntrinsicAttributes & Di
</label>
</div>
<DialogFooter>
{warning && (
<div className="flex flex-row text-muted-foreground space-x-2">
<AlertTriangle className="self-center" />
<label className="whitespace-pre-line text-xs self-center">{warning}</label>
</div>
)}
<Button
variant="outline"
type="submit"
Expand Down
2 changes: 1 addition & 1 deletion src/tribler/ui/src/services/tribler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ export class TriblerService {

// Torrents / search

async getMetainfo(uri: string): Promise<undefined | ErrorDict | {metainfo: string, download_exists: boolean}> {
async getMetainfo(uri: string): Promise<undefined | ErrorDict | {metainfo: string, download_exists: boolean, valid_certificate: boolean}> {
try {
return (await this.http.get(`/torrentinfo?uri=${uri}`)).data;
} catch (error) {
Expand Down