
    i                        U d Z ddlmZ ddlZddlmZ ddlZddlZddlZ	ddl	m
Z
mZ ddl	mZ ddlmZmZ ddlmZmZmZmZmZmZmZmZmZmZ  e
j6                  d	      Z
daej:                  dz  ed
<   da ee       jB                  dz  Z"	 dej:                  fdZ#dedejH                  dz  fdZ%d Z&d Z'dejP                  fdZ)y)ah  Bot protection / IP rate limitation.  The intention of rate limitation is to
limit suspicious requests from an IP.  The motivation behind this is the fact
that SearXNG passes through requests from bots and is thus classified as a bot
itself.  As a result, the SearXNG engine then receives a CAPTCHA or is blocked
by the search engine (the origin) in some other way.

To avoid blocking, the requests from bots to SearXNG must also be blocked, this
is the task of the limiter.  To perform this task, the limiter uses the methods
from the :ref:`botdetection`:

- Analysis of the HTTP header in the request / :ref:`botdetection probe headers`
  can be easily bypassed.

- Block and pass lists in which IPs are listed / :ref:`botdetection ip_lists`
  are hard to maintain, since the IPs of bots are not all known and change over
  the time.

- Detection & dynamically :ref:`botdetection rate limit` of bots based on the
  behavior of the requests.  For dynamically changeable IP lists a Valkey
  database is needed.

The prerequisite for IP based methods is the correct determination of the IP of
the client. The IP of the client is determined via the X-Forwarded-For_ HTTP
header.

.. attention::

   A correct setup of the HTTP request headers ``X-Forwarded-For`` and
   ``X-Real-IP`` is essential to be able to assign a request to an IP correctly:

   - `NGINX RequestHeader`_
   - `Apache RequestHeader`_

.. _X-Forwarded-For:
    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
.. _NGINX RequestHeader:
    https://docs.searxng.org/admin/installation-nginx.html#nginx-s-searxng-site
.. _Apache RequestHeader:
    https://docs.searxng.org/admin/installation-apache.html#apache-s-searxng-site

Enable Limiter
==============

To enable the limiter activate:

.. code:: yaml

   server:
     ...
     limiter: true  # rate limit the number of request on the instance, block some bots

and set the valkey-url connection. Check the value, it depends on your valkey DB
(see :ref:`settings valkey`), by example:

.. code:: yaml

   valkey:
     url: valkey://localhost:6379/0


Configure Limiter
=================

The methods of :ref:`botdetection` the limiter uses are configured in a local
file ``/etc/searxng/limiter.toml``.  The defaults are shown in limiter.toml_ /
Don't copy all values to your local configuration, just enable what you need by
overwriting the defaults.  For instance to activate the ``link_token`` method in
the :ref:`botdetection.ip_limit` you only need to set this option to ``true``:

.. code:: toml

   [botdetection.ip_limit]
   link_token = true

.. _limiter.toml:

``limiter.toml``
================

In this file the limiter finds the configuration of the :ref:`botdetection`:

- :ref:`botdetection ip_lists`
- :ref:`botdetection rate limit`
- :ref:`botdetection probe headers`

.. kernel-include:: $SOURCEDIR/limiter.toml
   :code: toml

Implementation
==============

    )
ip_addressN)Path)loggervalkeydb)botdetection)SXNG_Requestsxng_request)
confighttp_accepthttp_accept_encodinghttp_accept_languagehttp_user_agenthttp_sec_fetchip_limitip_listsget_networkdump_requestlimiterCFGFlimiter.tomlreturnc                  (   t         ddlm}  | j                         xs t	        d      dz  }t
        j                  j                  t        |t        j                  j                        a t        j                  j                  t         |       t         S )z/Returns SearXNG's global limiter configuration.   )settings_loaderz/etc/searxngr   )r    r   get_user_cfg_folderr   r
   Config	from_tomlLIMITER_CFG_SCHEMAsearxcompatLIMITER_CFG_DEPRECATEDlimiter_fix_cfg)r   cfg_files     /root/searxng/searx/limiter.pyget_cfgr&      sf     {%#779QT.=QUccmm%%&8(ELLDgDgh$$S(3J    requestc                    t               }t        | j                        }t        ||      }| j                  dk(  ry |j
                  ry t        j                  ||      \  }}|r"t        j                  d|j                  |       y t        j                  ||      \  }}|r;t        j                  d|j                  |       t        j                  d|z  df      S t        fD ]O  }|j!                  || |      }|t        j"                  d|j$                   d| dt'        t(                     |c S  | j                  d	k(  rrt*        t,        t.        t        t0        t2        fD ]O  }|j!                  || |      }|t        j"                  d|j$                   d| dt'        t(                     |c S  t        j"                  d
| dt'        t(                     y )Nz/healthzzPASS %s: matched PASSLIST - %sz BLOCK %s: matched BLOCKLIST - %szIP is on BLOCKLIST - %si  zNOT OK (z): z: %sz/searchzOK )r&   r   remote_addrr   pathis_link_localr   pass_ipr   warning
compressedblock_iperrorflaskmake_responser   filter_requestdebug__name__r   r	   r   r   r   r   r   )r(   cfgreal_ipnetworkmatchmsgfuncvals           r%   r4   r4      s    )C,,-G'3'G||z!  !!'3/JE379K9KSQ""7C0JE379K9KSQ""$=$CS#IJJ
 	  !!'7C8?LL8DMM?#gYdC\R^E_`J ||y    
 	D %%gw<Cxc'$GVbIcd
	 LL3wit$l<&@Ar'   c                       t        t              S )z(See :py:obj:`flask.Flask.before_request`)r4   r	    r'   r%   pre_requestr@      s    ,''r'   c                      t         S )zCReturns ``True`` if limiter is active and a valkey DB is available.)
_INSTALLEDr?   r'   r%   is_installedrC      s    r'   appc                 Z   t               }t        j                         }t        j                  ||       |d   d   s	|d   d   sy|s3t        j                  d       |d   d   rt        j                  d       yda	|d   d   r|j                  dd       | j                  t               y)	zInstall the limiterserverr   public_instanceNzpThe limiter requires Valkey, please consult the documentation: https://docs.searxng.org/admin/searx.limiter.htmlr   Tz botdetection.ip_limit.link_token)r&   r   clientr   initr   r1   sysexitrB   setbefore_requestr@   )rD   settingsr7   valkey_clients       r%   
initializerP      s     )COO%Mc=)Xy)Xh-?@Q-R@	
 H/0HHQKJ+,2D9{#r'   )*__doc__	ipaddressr   rJ   pathlibr   r2   werkzeugsearx.compatr    r   r   r   searx.extended_typesr   r	   searx.botdetectionr
   r   r   r   r   r   r   r   r   r   getChildr   r   __annotations__rB   __file__parentr   r&   Responser4   r@   rC   FlaskrP   r?   r'   r%   <module>r^      s   [z ! 
      ;   
	# V]]T  
(^**^;  6 >L >X->->-E >B(

$EKK $r'   