fix: resolve critical vulnerability V-001
Automatically generated security fix
This commit is contained in:
committed by
lyingbug
parent
bdc9171242
commit
e023c26af8
@@ -1,12 +1,14 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
import asyncio
|
import asyncio
|
||||||
import io
|
import io
|
||||||
|
import ipaddress
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import time
|
import time
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import Dict, List, Optional, Tuple
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
@@ -30,6 +32,60 @@ class BaseParser(ABC):
|
|||||||
_ocr_engine = None
|
_ocr_engine = None
|
||||||
_ocr_engine_failed = False
|
_ocr_engine_failed = False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _is_safe_url(url: str) -> bool:
|
||||||
|
"""Validate URL to prevent SSRF attacks
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url: URL to validate
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if URL is safe to fetch, False otherwise
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
parsed_url = urlparse(url)
|
||||||
|
|
||||||
|
# Only allow http and https schemes
|
||||||
|
if parsed_url.scheme not in ['http', 'https']:
|
||||||
|
logger.warning(f"Rejected URL with invalid scheme: {parsed_url.scheme}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Extract hostname
|
||||||
|
hostname = parsed_url.hostname
|
||||||
|
if not hostname:
|
||||||
|
logger.warning("No hostname found in URL")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Try to parse as IP address
|
||||||
|
try:
|
||||||
|
ip = ipaddress.ip_address(hostname)
|
||||||
|
# Reject private, loopback, link-local, multicast addresses
|
||||||
|
if (ip.is_private or ip.is_loopback or
|
||||||
|
ip.is_link_local or ip.is_multicast or
|
||||||
|
ip.is_reserved):
|
||||||
|
logger.warning(f"Rejected URL with restricted IP: {ip}")
|
||||||
|
return False
|
||||||
|
except ValueError:
|
||||||
|
# Not an IP address, validate hostname
|
||||||
|
# Reject localhost and common internal hostnames
|
||||||
|
hostname_lower = hostname.lower()
|
||||||
|
restricted_hostnames = [
|
||||||
|
'localhost',
|
||||||
|
'127.0.0.1',
|
||||||
|
'::1',
|
||||||
|
'metadata.google.internal',
|
||||||
|
'metadata.tencentyun.com',
|
||||||
|
'169.254.169.254', # AWS metadata endpoint
|
||||||
|
]
|
||||||
|
if hostname_lower in restricted_hostnames or hostname_lower.endswith('.local'):
|
||||||
|
logger.warning(f"Rejected URL with restricted hostname: {hostname}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Error validating URL: {str(e)}")
|
||||||
|
return False
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_ocr_engine(cls, backend_type="paddle", **kwargs):
|
def get_ocr_engine(cls, backend_type="paddle", **kwargs):
|
||||||
"""Get OCR engine instance
|
"""Get OCR engine instance
|
||||||
@@ -681,6 +737,11 @@ class BaseParser(ABC):
|
|||||||
if is_storage_url:
|
if is_storage_url:
|
||||||
logger.info(f"Image already on COS: {img_url}, no need to re-upload")
|
logger.info(f"Image already on COS: {img_url}, no need to re-upload")
|
||||||
try:
|
try:
|
||||||
|
# Validate URL to prevent SSRF attacks
|
||||||
|
if not self._is_safe_url(img_url):
|
||||||
|
logger.error(f"URL failed validation check: {img_url}")
|
||||||
|
return img_url, img_url, None
|
||||||
|
|
||||||
# Still need to get image object for OCR processing
|
# Still need to get image object for OCR processing
|
||||||
# Get proxy settings from environment variables
|
# Get proxy settings from environment variables
|
||||||
http_proxy = os.environ.get("EXTERNAL_HTTP_PROXY")
|
http_proxy = os.environ.get("EXTERNAL_HTTP_PROXY")
|
||||||
@@ -727,6 +788,11 @@ class BaseParser(ABC):
|
|||||||
|
|
||||||
# Normal remote URL download handling
|
# Normal remote URL download handling
|
||||||
else:
|
else:
|
||||||
|
# Validate URL to prevent SSRF attacks
|
||||||
|
if not self._is_safe_url(img_url):
|
||||||
|
logger.error(f"URL failed validation check: {img_url}")
|
||||||
|
return img_url, img_url, None
|
||||||
|
|
||||||
# Get proxy settings from environment variables
|
# Get proxy settings from environment variables
|
||||||
http_proxy = os.environ.get("EXTERNAL_HTTP_PROXY")
|
http_proxy = os.environ.get("EXTERNAL_HTTP_PROXY")
|
||||||
https_proxy = os.environ.get("EXTERNAL_HTTPS_PROXY")
|
https_proxy = os.environ.get("EXTERNAL_HTTPS_PROXY")
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Tencent/WeKnora/internal/logger"
|
"github.com/Tencent/WeKnora/internal/logger"
|
||||||
@@ -58,6 +61,31 @@ type mcpGoClient struct {
|
|||||||
initialized bool
|
initialized bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// validateURLScheme validates that authentication endpoints use HTTPS
|
||||||
|
func validateURLScheme(serviceURL string, hasBasicAuth bool, hasTokenAuth bool) error {
|
||||||
|
if !hasBasicAuth && !hasTokenAuth {
|
||||||
|
// No authentication, no HTTPS requirement
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if serviceURL == "" {
|
||||||
|
return fmt.Errorf("URL is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse the URL
|
||||||
|
parsedURL, err := url.Parse(serviceURL)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid URL: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enforce HTTPS for authenticated endpoints
|
||||||
|
if parsedURL.Scheme != "https" {
|
||||||
|
return fmt.Errorf("HTTPS is required for authenticated connections, got %s scheme", parsedURL.Scheme)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// NewMCPClient creates a new MCP client based on the transport type
|
// NewMCPClient creates a new MCP client based on the transport type
|
||||||
func NewMCPClient(config *ClientConfig) (MCPClient, error) {
|
func NewMCPClient(config *ClientConfig) (MCPClient, error) {
|
||||||
// Create HTTP client with timeout
|
// Create HTTP client with timeout
|
||||||
|
|||||||
Reference in New Issue
Block a user