Instalar Squid forward proxy com SSL cache (SSL bump) em Rocky Linux 8.9 para cache de pacotes na infrestrutura
Objetivos:
O objetivo é acelerar a instalação de pacotes de atualização de sistema operacional e outros arquivos numa infraestrutura com várias máquinas virtuais / virtual machines.
É um acesso da infraestrutura interna para a internet aberta, até os repositórios de pacotes, com conexões SSL. Por isso o nome forward proxy.
Note a diferença para um reverse proxy que, por exemplo, acelera a entrega de conteúdo de um servidor web para a internet pública.
Utilizaremos Squid proxy, que é naturalmente um forward proxy.
O Nginx é naturalmente um reverse proxy. Somente com uso de patch consegue fazer forward proxy, com protocolo HTTP CONNECT.
E não conseguimos fazer cache de conteúdo https nele, nem com certificado auto-assinado, para descriptografar, armazenar, criptografar novamente.
Usaremos a ferramenta mais adequada para a necessidade, neste caso, o Squid.
Geralmente, os forward proxies apenas estabelecem a conexão SSL usando HTTP CONNECT, que cria um túnel entre o cliente local através do proxy até o servidor original sem fazer cache dos pacotes.
Para fazer cache local é necessário uma técnica de man-in-the-middle (MITM), descriptografando a conexão SSL, fazendo cache local, e recriptografando o conteúdo assinando com chave própria.
A chave própria pode ser válida por autoridade certificadora (CA) ou auto-assinada, já que o forward proxy será usado apenas na infraestrutura interna.
Se a chave for auto-assinada, terá de ser incluída no chaveiro / key-chain para aceitação em todas as máquinas da infraestrutura.
Considerações sobre Squid em container docker em ambientes de nuvem:
As primeiras implementações tentaram fazer um Squid, dentro de um container docker de Ubuntu, dentro de uma VM Rocky Linux como docker host, rodando sobre nuvem VmWare.
Depois alteramos para usar um IP estático próprio com driver ipvlan (macvlan precisa modo promíscuo de interface do docker host, o que nos seria inviável na infraestrutura VmWare por regras de segurança) em vez do IP do docker host com porta mapeada, nem o tipo host de rede. Isso para poder preservar o IP de origem de conexão.
Porém ainda não havíamos conseguido fazer o NAT no nossa nuvem VmWare fazer roteamento de retorno dos pacotes para o container quando configurado com IP estático próprio.
Os pacotes até saem da infraestrutura, mas a resposta não retorna para o container.
O container funciona bem num docker host em bare metal sobre Ubuntu. Futuramente, com mais tempo, faremos novas tentativas de configuração de NAT e de rede tipo host.
Devido a isso tudo fizemos uma nova implantação diretamente em uma VM Rocky Linux.
Desde 2016 constatam que iptables POSTROUTING inviabiliza drivers macvlan e ipvlan em ambientes de nuvem, que não deixam colocar interfaces em modo promíscuo nos NAT.
https://github.com/moby/moby/issues/21735
Talvez uma alternativa seja usar segunda interface física e tentar criar uma rede BRIDGE normal nova e atrelada a essa interface do docker host, com gateway e rotas próprias já na vm do docker host. Veremos.
/etc/squid/squid.conf
Leia com atenção e ADAPTE às suas necessidades, principalmente tamanhos e diretórios e RAM.
Reparar a configuração de SSL database do Squid e os requisitos para o diretório, usar caminhos absolutos, e posicionamento no arquivo de configuração, pois a ordem faz diferença para alguns parâmetros do Squid.
Você precisa inicializar a SSL database ANTES de começar a usar o Squid. Só precisará fazer uma vez.
Também que escolhemos aufs para o cache dir.
Um problema que persiste, nas novas versões de Squid, é como preferir conexões IPV4 sobre as IPV6. Antigamente, havia parâmetro para isso (comentado no arquivo), mas agora o Squid atende a quem responder primeiro.
Portanto, você terá de controlar isso por fora do Squid.
Nos procedimentos mais adiante, chamamos o arquivo de squid_rocky.conf
A porta para https será 4128 e a porta http 3128.
Repare que desabilitamos a verificação de certificados por estarmos usando um auto-assinado.
#
# Recommended minimum configuration:
#
# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 10.0.0.0/8 # RFC1918 possible internal network
acl localnet src 172.16.0.0/12 # RFC1918 possible internal network
acl localnet src 192.168.0.0/16 # RFC1918 possible internal network
acl localnet src fc00::/7 # RFC 4193 local private network range
acl localnet src fe80::/10 # RFC 4291 link-local (directly plugged) machines
acl SSL_ports port 443
acl Safe_ports port 80 # http
acl Safe_ports port 21 # ftp
acl Safe_ports port 443 # https
acl Safe_ports port 70 # gopher
acl Safe_ports port 210 # wais
acl Safe_ports port 1025-65535 # unregistered ports
acl Safe_ports port 280 # http-mgmt
acl Safe_ports port 488 # gss-http
acl Safe_ports port 591 # filemaker
acl Safe_ports port 777 # multiling http
acl CONNECT method CONNECT
#
# Recommended minimum Access Permission configuration:
#
# Deny requests to certain unsafe ports
http_access deny !Safe_ports
# Deny CONNECT to other than secure SSL ports
http_access deny CONNECT !SSL_ports
# Only allow cachemgr access from localhost
http_access allow localhost manager
http_access deny manager
# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access allow localnet
http_access allow localhost
# And finally deny all other access to this proxy
http_access deny all
# Squid normally listens to port 3128
http_port 3128
# Squid normally listens to port 4128 for ssl bump
http_port
4128 ssl-bump generate-host-certificates=on
dynamic_cert_mem_cache_size=4MB cert=/etc/ssl/certs/selfsigned.pem
key=/etc/ssl/certs/selfsigned.key
#AFM For squid >= 4.x
initialize cert db on debian/ubuntu at dockerfile. here only run cert db
on the fly generator. It MUST be outside cache_dir.
sslcrtd_program /usr/lib64/squid/security_file_certgen -s /data/squidssldatabase/ssl_db -M 4MB
acl step1 at_step SslBump1 #there are 3 hardcoded sslbump step names.
ssl_bump peek step1
ssl_bump bump all
ssl_bump server-first all
always_direct allow all
#AFM should be placed above cache_dir
range_offset_limit 10 GB
maximum_object_size 10 GB
quick_abort_min -1
# Uncomment and adjust the following to add a disk cache directory. disk space in MB
#AFM
cache_dir aufs /data/squid 10000 16 256
# Leave coredumps in the first cache dir
coredump_dir /data/squid
#
# Add any of your own refresh_pattern entries above these.
#
refresh_pattern ^ftp: 1440 20% 10080
refresh_pattern ^gopher: 1440 0% 1440
refresh_pattern -i (/cgi-bin/|\?) 0 0% 0
refresh_pattern . 30 20% 4320 reload-into-ims
#AFM prefer ipv4 over ipv6
dns_v4_first on #obsolete?
#AFM dangerous, disabling verification
sslproxy_cert_error allow all
#sslproxy_flags DONT_VERIFY_PEER #obsolete
tls_outgoing_options options=ALL flags=DONT_VERIFY_PEER
Procedimentos:
Comandos a executar no Rocky Linux ANTES de executar Squid
Copiar o squid_rocky.conf para /etc/squid/squid.conf, fazendo antes um backup do arquivo original.
dnf update
dnf install squid
mv /etc/squid/squid.conf /etc/squid/squid.conf.original
Copiar o squid_rocky.conf da estação local para /etc/squid/squid.conf e os certificados (jump através de entreposto, neste exemplo)
scp -r -J andre@entreposto -o ServerAliveInterval=60 ./squid_rocky.conf root@squidhost:/etc/squid/squid.conf
scp -r -J andre@entreposto -o ServerAliveInterval=60 ./selfsigned.* root@squidhost:/etc/ssl/certs/
Executar no squidhost:
ls -lah /etc/ssl/certs/
Habilitar o serviço squid:
systemctl status squid.service
systemctl enable squid
systemctl status squid.service
Crie um diretório para Squid SSL database, ajuste permissões e inicialize o database.
mkdir -p /data/squidssldatabase &&\
chown -R squid:squid /data/squidssldatabase &&\
/usr/lib64/squid/security_file_certgen -c -s /data/squidssldatabase/ssl_db -M 4MB &&\
chown -R squid:squid /data/squidssldatabase/ssl_db
mkdir -p /data/squid &&\
chown -R squid:squid /data/squid
Inclua o certificado auto-assinado para ser reconhecido no servidor e nas máquinas que vão utilizar o ssl forward proxy:
less /etc/pki/ca-trust/source/README
cp /etc/ssl/certs/selfsigned.crt /etc/pki/ca-trust/source/anchors/
update-ca-trust --extract
Inicie o serviço Squid:
systemctl start squid
journalctl -xe
Testando o funcionamento:
export ftp_proxy='http://squidhost:4128'; export https_proxy='http://squidhost:4128'; export http_proxy='http://squidhost:4128'
time wget -v --no-check-certificate https://dl.rockylinux.org/pub/rocky/8/BaseOS/x86_64/os/Packages/g/glibc-all-langpacks-2.28-225.el8_8.6.x86_64.rpm
tail /var/log/squid/cache.log
tail /var/log/squid/access.log
Verifique a saída dos logs.
Liste o conteúdo do cache_dir .
Execute outra vez o wget e os comandos tail, avaliando se houve HIT e a diferença de velocidades.
Liste o conteúdo do cache_dir outra vez e examine. Os arquivos são guardados numa árvore de diretórios e não preservam os nomes, apenas o conteúdo e tamanho.
Bibliografia
Conceitos
https://www.jscape.com/blog/forward-proxy-vs-reverse-proxy
https://dl.rockylinux.org/pub/rocky/8/BaseOS/x86_64/os/Packages/l/
https://dl.rockylinux.org/pub/rocky/8/BaseOS/x86_64/os/Packages/a/
Squid
https://github.com/salrashid123/squid_proxy
https://serverfault.com/questions/1110996/preferring-ip-v4-over-v6-in-squid-proxy-5-0-and-newer
https://www.spinics.net/lists/squid/msg94048.html
https://serverfault.com/questions/1097922/how-to-make-squid-proxy-to-accept-self-signed-certificate
http://www.squid-cache.org/Doc/config/tls_outgoing_options/
https://www.siakabaro.com/how-to-install-squid-as-a-forward-proxy-on-ubuntu-18-04/
https://serverfault.com/questions/568620/configure-squid-as-an-https-forward-proxy
https://github.com/yegor256/squid-proxy
https://github.com/e2guardian/e2guardian
https://hub.docker.com/r/fredbcode/squid
https://gitlab.com/fredbcode-images/squid/-/blob/master/docker-compose/squid/squid.conf
https://gitlab.com/fredbcode-images/squid
https://wiki.squid-cache.org/SquidFaq/
https://wiki.squid-cache.org/ConfigExamples/Caching/AdobeProducts
https://hub.docker.com/r/ubuntu/squid/tags
https://github.com/movax01h/squid-forward-proxy/tree/main
https://github.com/beigi-reza/docker-compose-squid/blob/main/config/squid.conf
https://wiki.squid-cache.org/Features/SslBump
https://wiki.squid-cache.org/Features/SslPeekAndSplice
https://support.kaspersky.com/KWTS/6.1/pt-BR/166244.htm
https://wiki.squid-cache.org/ConfigExamples/Intercept/SslBumpExplicit
https://stackoverflow.com/questions/71095593/caching-with-squid-not-working-for-docker-images-why
https://hub.docker.com/r/alatas/squid-alpine-ssl ***
https://github.com/alatas/squid-alpine-ssl/tree/master
https://hub.docker.com/r/jamesyale/squid-sslbump
https://github.com/jamesyale/squid-sslbump
https://squid-users.squid-cache.narkive.com/OC2mLI8H/ipv6-error
http://www.squid-cache.org/Doc/config/tcp_outgoing_address/
https://squid-users.squid-cache.narkive.com/1y7KG0ff/ssl-errors-with-squid-3-5-27
https://squid-users.squid-cache.narkive.com/cCUTCEwN/need-to-disable-ipv6-aaaa-lookup-in-squid
https://superuser.com/questions/994728/force-squid-to-connect-to-sites-over-ipv4-rather-than-ipv6
https://community.nethserver.org/t/enable-dns-v4-first-on/10575
https://pt.linux-console.net/?p=8563
http://www.squid-cache.org/Doc/config/dns_v4_first/
https://serverfault.com/questions/483038/squid-tproxy-connection-fails-on-specific-sites
http://gagravarr.org/writing/openssl-certs/others.shtml
https://wiki.squid-cache.org/Features/DynamicSslCert
https://serverfault.com/questions/1097922/how-to-make-squid-proxy-to-accept-self-signed-certificate
https://serverfault.com/questions/649976/squid3-ssl-bumping-server-first-with-signed-certificate
https://squid-users.squid-cache.narkive.com/F85nCZEc/ssl-bump-deep-dive-self-signed-certs-in-chain
https://support.kaspersky.com/KWTS/6.0/en-US/166244.htm
http://www.squid-cache.org/Doc/config/maximum_object_size/
https://serverfault.com/questions/596890/squid3-not-caching-larger-files
http://www.squid-cache.org/Doc/config/cache_dir/
https://packages.ubuntu.com/jammy/amd64/squid-openssl/filelist
https://webhostinggeeks.com/howto/how-to-configure-squid-proxy-server-for-ssl-bumping/
https://unix.stackexchange.com/questions/720245/squid-peek-bump-splice-with-self-signed-cert
http://www.squid-cache.org/Doc/config/ssl_bump/
https://wiki.squid-cache.org/Features/BumpSslServerFirst
https://wiki.squid-cache.org/Features/SslPeekAndSplice
http://www.squid-cache.org/Doc/config/always_direct/
https://www.mankier.com/8/security_file_certgen
Dicas de rede docker
https://www.geeksforgeeks.org/how-to-provide-the-static-ip-to-a-docker-container/
https://stackoverflow.com/questions/27937185/assign-static-ip-to-docker-container
https://www.geeksforgeeks.org/how-to-provide-the-static-ip-to-a-docker-container/
https://www.baeldung.com/ops/docker-assign-static-ip-container
https://www.howtogeek.com/devops/how-to-assign-a-static-ip-to-a-docker-container/
https://forums.docker.com/t/static-ip-on-docker-containers/110412/5
https://docs.docker.com/compose/compose-file/06-networks/
https://github.com/docker/compose/issues/4474
https://www.appsloveworld.com/docker/100/3/how-to-assign-static-public-ip-to-docker-container
https://sreeninet.wordpress.com/2016/05/29/docker-macvlan-and-ipvlan-network-plugins/ ***
https://github.com/moby/moby/issues/21735 ***
https://stackoverflow.com/questions/34688906/how-to-assign-static-public-ip-to-a-docker-container
https://asergo.com/knowledge-base/bare-metal-servers/docker/docker-containers-with-public-ips.html
https://micropyramid.com/blog/assign-public-ip-address-to-docker-container-without-port-binding **
https://docs.docker.com/network/drivers/macvlan/ ***
https://docs.docker.com/network/network-tutorial-macvlan/ ***
https://www.reddit.com/r/vmware/comments/11m3sw5/trouble_setting_up_docker_networking_with_macvlan/ **
https://nathanielho.com/docker/macvlan01.html ***
https://stackoverflow.com/questions/55475440/docker-compose-macvlan-cant-access-internet **
https://forwardingplane.net/configuration-archive/docker-compose-wireguard-using-macvlan/ **
https://www.reddit.com/r/docker/comments/ghheg6/how_to_best_use_macvlan_in_a_dockercompose/ **
https://forums.docker.com/t/ipvlan-or-macvlan-in-docker-compose-yml/133137/5
https://docs.docker.com/network/drivers/ipvlan ***
https://www.reddit.com/r/docker/comments/11fdyh6/issue_with_setting_up_static_ip_on_ipvlan_docker/ ****
https://docs.docker.com/compose/compose-file/06-networks/#ipam ***
https://www.reddit.com/r/docker/comments/12ekerj/docker_container_to_get_ip_by_external_dhcp/
https://forums.docker.com/t/ipvlan-l3-network-with-static-route/94189
https://github.com/docker/compose/issues/4613
https://docs.docker.com/compose/compose-file/05-services/#dns
https://docs.docker.com/engine/reference/commandline/network_inspect/
https://docs.docker.com/engine/reference/commandline/network_ls/
https://docs.docker.com/engine/reference/commandline/network_rm/
https://technawk.medium.com/inspecting-network-traffic-for-docker-compose-part-i-423ca6bdaad4
https://byteplumbing.net/2018/01/inspecting-docker-container-network-traffic/
https://docs.docker.com/network/
https://docs.docker.com/network/proxy/ *
https://docs.docker.com/network/drivers/ipvlan/ ***
https://www.linux.org/threads/configuring-a-static-ip-address-docker-containers.45490/
https://stackoverflow.com/questions/73742328/docker-network-access-fixed-ip-address
https://copyprogramming.com/howto/how-can-i-set-a-static-ip-address-in-a-docker-container
https://copyprogramming.com/howto/how-to-assign-a-static-ip-to-a-docker-container
https://devconnected.com/how-to-add-route-on-linux/
https://www.garron.me/en/linux/add-secondary-ip-linux.html
Docker compose examples:
https://www.baeldung.com/ops/docker-compose
https://docs.docker.com/get-started/08_using_compose/
https://dockerlabs.collabnix.com/intermediate/workshop/DockerCompose/run_command.html
https://docs.docker.com/compose/compose-file/07-volumes/
https://docs.docker.com/storage/volumes/
https://docs.docker.com/compose/gettingstarted/
https://docs.tibco.com/pub/om-ll/5.0.0/doc/html/GUID-0618A976-3E0A-4750-B44E-F329452C05CE.html ***
https://www.baeldung.com/ops/docker-compose-multiple-commands
https://www.baeldung.com/ops/docker-compose
https://www.baeldung.com/ops/docker-assign-static-ip-container
https://stackoverflow.com/questions/50121943/docker-compose-hangs-on-attaching-to
https://stackoverflow.com/questions/64221861/an-error-failed-to-solve-with-frontend-dockerfile-v0
https://docs.docker.com/compose/environment-variables/set-environment-variables/
https://ioflood.com/blog/docker-compose-ports-vs-expose-explained/
https://stackoverflow.com/questions/45587214/configure-timezone-in-dockerized-nginx-php-fpm
https://serverfault.com/questions/683605/docker-container-time-timezone-will-not-reflect-changes
https://stackoverflow.com/questions/39172652/using-docker-compose-to-set-containers-timezones
https://stackoverflow.com/questions/54939578/docker-compose-configuring-container-timezone
Minikube
https://minikube.sigs.k8s.io/docs/start/
https://github.com/kubernetes/minikube/releases/tag/v1.31.2
Rocky Linux
https://www.smoothnet.org/squid-proxy-with-ssl-bump/
https://tweenpath.net/perfect-squid-with-transparent-proxy-and-ssl-log/
https://techviewleo.com/install-configure-squid-proxy-server-on-rocky-linux/
https://forums.rockylinux.org/t/ssl-cert-location/10555/7
Comentários
Postar um comentário