alexbers / mtprotoproxy

Async MTProto proxy for Telegram
MIT License
1.55k stars 343 forks source link

Installing Python MTProxy on CentOS 8 with Python update #293

Open kmurachev opened 11 months ago

kmurachev commented 11 months ago
yum -y install epel-release
yum -y update
yum -y upgrade
yum -y install wget htop nano mc vim-common traceroute bind-utils yum-utils lsof net-tools git
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
firewall-cmd --list-all
setenforce 0
sed -i 's/^SELINUX=.*/SELINUX=disabled/g' /etc/selinux/config
echo 'net.core.default_qdisc=fq' | sudo tee -a /etc/sysctl.conf
echo 'net.ipv4.tcp_congestion_control=bbr' | sudo tee -a /etc/sysctl.conf
sysctl -p
sysctl net.ipv4.tcp_available_congestion_control

# This should include bbr in it

sysctl -n net.ipv4.tcp_congestion_control

# This one should be bbr

lsmod | grep bbr

# The output will be similar to "tcp_bbr 16384 0"

python3 -V

>> Python 3.6.8

yum groupinstall 'development tools' -y && yum install wget openssl-devel bzip2-devel libffi-devel xz-devel -y
cd /tmp
wget https://www.python.org/ftp/python/3.11.4/Python-3.11.4.tgz
tar xzf Python-3.11.4.tgz
cd Python-3.11.4 && ./configure --enable-optimizations
make altinstall
ls /usr/local/bin/python*
alternatives --install /usr/bin/python3 python3 /usr/local/bin/python3.11 1 && alternatives --set python3 /usr/local/bin/python3.11 && echo "3" | alternatives --config python
/usr/local/bin/python3.11 -m pip install --upgrade pip
ls /usr/local/bin/pip*
alternatives --install /usr/bin/pip pip /usr/local/bin/pip3.11 1 && alternatives --set pip /usr/local/bin/pip3.11
python -V && pip -V

>> Python 3.11.4 >> pip 23.1.2 from /usr/local/lib/python3.11/site-packages/pip (python 3.11)

head -c 16 /dev/urandom | xxd -ps
echo -n "www.cloudflare.com" | od -A n -t x1 | sed 's/ *//g'

AD_TAG = "<tag>"

git clone -b stable https://github.com/alexbers/mtprotoproxy.git /opt/mtprotoproxy
cd /opt/mtprotoproxy
nano /opt/mtprotoproxy/config.py
useradd --no-create-home -s /usr/sbin/nologin tgproxy
nano /etc/systemd/system/mtprotoproxy.service
[Unit]
    Description=Async MTProto proxy for Telegram
    After=network-online.target
    Wants=network-online.target

[Service]
    ExecStart=/opt/mtprotoproxy/mtprotoproxy.py
    AmbientCapabilities=CAP_NET_BIND_SERVICE
    LimitNOFILE=infinity
    User=tgproxy
    Group=tgproxy
    Restart=on-failure

[Install]
    WantedBy=multi-user.target
pip install setuptools_rust
pip install cryptography
pip install uvloop
systemctl enable mtprotoproxy
systemctl daemon-reload
systemctl restart mtprotoproxy
systemctl status mtprotoproxy
journalctl -u mtprotoproxy | cat
kmurachev commented 11 months ago

Столкнулся с тем, что не прогружаются картинки в каналах, по типу как в https://github.com/alexbers/mtprotoproxy/issues/283#issuecomment-1439784088

попробовал изменить MAX_CONNS_IN_POOL на 8 как тут https://github.com/alexbers/mtprotoproxy/issues/283#issuecomment-1472572835 , но особо ничего не поменялось В итоге изменил на 1 как тут https://github.com/alexbers/mtprotoproxy/issues/169#issuecomment-560168918 и пока вроде всё работет и грузится

alexbers commented 11 months ago

Хм.. интересно, вероятно, у них что-то поменялось, гляну

kmurachev commented 11 months ago

Тут https://github.com/alexbers/mtprotoproxy/wiki/Optimization-and-Fine-Tuning с целью повышения производительности прокси рекомендовано внести в конфиг

nano /opt/mtprotoproxy/config.py
TO_CLT_BUFSIZE = 262144
TO_TG_BUFSIZE = 262144

а какие ещё документированные настройки имеются?

Где-то пробегало, что если проблема с ntp-синхронизацией на сервере, то (не)рекомендуется внести в конфиг IGNORE_TIME_SKEW = True

также пробегали, но уже не вспомню, где и для чего BLOCK_IF_FIRST_PKT_BAD = False REPLAY_CHECK_LEN = 0

alexbers commented 11 months ago

REPLAY_CHECK_LEN - это сколько хранить последних хендшейков для защиты от активных replay-атак, направленных на детектирование прокси IGNORE_TIME_SKEW - принимать ли соединение от клиентов с плохим временем (если принимать, увеличивается шанс детекции из-за replay-атак)

А в целом настроек много, их можно посмотреть в исходнике, продублирую сюда

    # accept incoming connections only with proxy protocol v1/v2, useful for nginx and haproxy
    conf_dict.setdefault("PROXY_PROTOCOL", False)

    # set the tls domain for the proxy, has an influence only on starting message
    conf_dict.setdefault("TLS_DOMAIN", "www.google.com")

    # enable proxying bad clients to some host
    conf_dict.setdefault("MASK", True)

    # the next host to forward bad clients
    conf_dict.setdefault("MASK_HOST", conf_dict["TLS_DOMAIN"])

    # set the home domain for the proxy, has an influence only on the log message
    conf_dict.setdefault("MY_DOMAIN", False)

    # the next host's port to forward bad clients
    conf_dict.setdefault("MASK_PORT", 443)

    # use upstream SOCKS5 proxy
    conf_dict.setdefault("SOCKS5_HOST", None)
    conf_dict.setdefault("SOCKS5_PORT", None)
    conf_dict.setdefault("SOCKS5_USER", None)
    conf_dict.setdefault("SOCKS5_PASS", None)

    if conf_dict["SOCKS5_HOST"] and conf_dict["SOCKS5_PORT"]:
        # Disable the middle proxy if using socks, they are not compatible
        conf_dict["USE_MIDDLE_PROXY"] = False

    # user tcp connection limits, the mapping from name to the integer limit
    # one client can create many tcp connections, up to 8
    conf_dict.setdefault("USER_MAX_TCP_CONNS", {})

    # expiration date for users in format of day/month/year
    conf_dict.setdefault("USER_EXPIRATIONS", {})
    for user in conf_dict["USER_EXPIRATIONS"]:
        expiration = datetime.datetime.strptime(conf_dict["USER_EXPIRATIONS"][user], "%d/%m/%Y")
        conf_dict["USER_EXPIRATIONS"][user] = expiration

    # the data quota for user
    conf_dict.setdefault("USER_DATA_QUOTA", {})

    # length of used handshake randoms for active fingerprinting protection, zero to disable
    conf_dict.setdefault("REPLAY_CHECK_LEN", 65536)

    # accept clients with bad clocks. This reduces the protection against replay attacks
    conf_dict.setdefault("IGNORE_TIME_SKEW", False)

    # length of last client ip addresses for logging
    conf_dict.setdefault("CLIENT_IPS_LEN", 131072)

    # delay in seconds between stats printing
    conf_dict.setdefault("STATS_PRINT_PERIOD", 600)

    # delay in seconds between middle proxy info updates
    conf_dict.setdefault("PROXY_INFO_UPDATE_PERIOD", 24*60*60)

    # delay in seconds between time getting, zero means disabled
    conf_dict.setdefault("GET_TIME_PERIOD", 10*60)

    # delay in seconds between getting the length of certificate on the mask host
    conf_dict.setdefault("GET_CERT_LEN_PERIOD", random.randrange(4*60*60, 6*60*60))

    # max socket buffer size to the client direction, the more the faster, but more RAM hungry
    # can be the tuple (low, users_margin, high) for the adaptive case. If no much users, use high
    conf_dict.setdefault("TO_CLT_BUFSIZE", (16384, 100, 131072))

    # max socket buffer size to the telegram servers direction, also can be the tuple
    conf_dict.setdefault("TO_TG_BUFSIZE", 65536)

    # keepalive period for clients in secs
    conf_dict.setdefault("CLIENT_KEEPALIVE", 10*60)

    # drop client after this timeout if the handshake fail
    conf_dict.setdefault("CLIENT_HANDSHAKE_TIMEOUT", random.randrange(5, 15))

    # if client doesn't confirm data for this number of seconds, it is dropped
    conf_dict.setdefault("CLIENT_ACK_TIMEOUT", 5*60)

    # telegram servers connect timeout in seconds
    conf_dict.setdefault("TG_CONNECT_TIMEOUT", 10)

    # listen address for IPv4
    conf_dict.setdefault("LISTEN_ADDR_IPV4", "0.0.0.0")

    # listen address for IPv6
    conf_dict.setdefault("LISTEN_ADDR_IPV6", "::")

    # listen unix socket
    conf_dict.setdefault("LISTEN_UNIX_SOCK", "")

    # prometheus exporter listen port, use some random port here
    conf_dict.setdefault("METRICS_PORT", None)

    # prometheus listen addr ipv4
    conf_dict.setdefault("METRICS_LISTEN_ADDR_IPV4", "0.0.0.0")

    # prometheus listen addr ipv6
    conf_dict.setdefault("METRICS_LISTEN_ADDR_IPV6", None)

    # prometheus scrapers whitelist
    conf_dict.setdefault("METRICS_WHITELIST", ["127.0.0.1", "::1"])

    # export proxy link to prometheus
    conf_dict.setdefault("METRICS_EXPORT_LINKS", False)

    # default prefix for metrics
    conf_dict.setdefault("METRICS_PREFIX", "mtprotoproxy_")
kmurachev commented 11 months ago

спасибо Вам большое, что до сих пор продолжаете поддерживать проект, несмотря на то, что офф. команда то ли вообще его забросила, то ли выжидает чего, им одним только известно

и хоть пока тема прокси и не актуальна в этой стране, но надо быть готовым к любой подляне внезапно, держать "порох сухим", ткскзтб