AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / server / Perguntas / 1173650
Accepted
ReYuki
ReYuki
Asked: 2025-02-25 04:50:34 +0800 CST2025-02-25 04:50:34 +0800 CST 2025-02-25 04:50:34 +0800 CST

como configurar sessão interativa no ChrootDirectory (não para sFTP)

  • 772

o objetivo é criar algo parecido com o docker, mas usando o método tradicional, chroot.

Comecei criando uma partição como ext4 e montei-a /srv/container/teste instalei o sistema Linux padrão com pacstrap /srv/container/test base. Também estou preparando sistemas de arquivos de kernel virtual :

export ROOTDIR=/srv/container/test
mount -v --bind /dev $ROOTDIR/dev
mount -vt tmpfs tmpfs $ROOTDIR/run
mount -vt sysfs sysfs $ROOTDIR/sys
mount -vt proc proc $ROOTDIR/proc
mount -vt devpts devpts -o gid=5,mode=0620 $ROOTDIR/dev/pts

Eu verifico isso simplesmente fazendo chroot no sistema local e funciona.

no entanto, quando tentei configurar o servidor ssh para usá-lo como ChrootDirectory, ele falhou com o erro de pipe quebrado, verifiquei o log ssh: journalctl -u sshdmas não vejo o erro real impresso no log:

...
Feb 25 03:12:34 zero sshd-session[33517]: Accepted password for root from 10.0.2.15 port 51616 ssh2
Feb 25 03:12:34 zero sshd-session[33517]: debug1: monitor_child_preauth: user root authenticated by privileged process
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_get_keystate: Waiting for new keys
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_request_receive_expect: entering, type 26
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_request_receive: entering
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_get_keystate: GOT new keys
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_auth_password: user authenticated [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug3: user_specific_delay: user specific delay 0.000ms [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug3: ensure_minimum_time_since: elapsed 529.640ms, delaying 131.069ms (requested 5.162ms) [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_do_pam_account entering [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_request_send: entering, type 102 [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_request_receive_expect: entering, type 103 [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_request_receive: entering [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_do_pam_account returning 1 [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug3: send packet: type 52 [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_request_send: entering, type 26 [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug3: mm_send_keystate: Finished sending state [preauth]
Feb 25 03:12:34 zero sshd-session[33517]: debug1: monitor_read_log: child log fd closed
Feb 25 03:12:34 zero sshd-session[33517]: debug3: ssh_sandbox_parent_finish: finished
Feb 25 03:12:34 zero sshd-session[33517]: debug1: PAM: establishing credentials
Feb 25 03:12:34 zero sshd[33514]: debug2: server_accept_loop: child 33517 for connection from 10.0.2.15 to 10.0.2.15 auth done
Feb 25 03:12:34 zero sshd[33514]: debug1: child_close: enter (forcing)
Feb 25 03:12:34 zero sshd-session[33517]: debug3: PAM: opening session
Feb 25 03:12:34 zero sshd-session[33517]: debug2: do_pam_session: auth information in SSH_AUTH_INFO_0
Feb 25 03:12:34 zero sshd-session[33517]: pam_unix(sshd:session): session opened for user root(uid=0) by root(uid=0)

e nada útil no log do lado do cliente:

...
Authenticated to 10.0.2.15 ([10.0.2.15]:22) using "password".
debug1: channel 0: new session [client-session] (inactive timeout: 0)
debug3: ssh_session2_open: channel_new: 0
debug2: channel 0: send open
debug3: send packet: type 90
debug1: Requesting [email protected]
debug3: send packet: type 80
debug1: Entering interactive session.
debug1: pledge: filesystem
debug3: client_repledge: enter
Read from remote host 10.0.2.15: Connection reset by peer
Connection to 10.0.2.15 closed.
debug3: send packet: type 1
client_loop: send disconnect: Broken pipe

O que está causando o cano quebrado? Não está claro para mim.

meu sshd_config se parece com isso:

# Include drop-in configurations
Include /etc/ssh/sshd_config.d/*.conf

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/sbin:/usr/local/bin:/usr/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
ListenAddress 10.0.2.15
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO
LogLevel DEBUG3

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin prohibit-password
PermitRootLogin yes
#PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile  .ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to no to disable s/key passwords
#KbdInteractiveAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the KbdInteractiveAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via KbdInteractiveAuthentication may bypass
# the setting of "PermitRootLogin prohibit-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and KbdInteractiveAuthentication to 'no'.
#UsePAM no

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem   sftp    /usr/lib/ssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#   X11Forwarding no
#   AllowTcpForwarding no
#   PermitTTY no
#   ForceCommand cvs server

# Match User demo
Match User root
        ChrootDirectory /srv/container/test
    PasswordAuthentication yes


no meu entendimento, o seguinte passo é executado:a client authenticated by ssh server -> ssh server do chroot -> exec /srv/container/test/usr/bin/bash and the home dir is set to /srv/container/test/root/

é válido?

linux
  • 1 1 respostas
  • 46 Views

1 respostas

  • Voted
  1. Best Answer
    ReYuki
    2025-02-26T03:35:35+08:002025-02-26T03:35:35+08:00

    Mudei minha abordagem depois de pesquisar um pouco na internet e finalmente encontrei uma postagem que estava procurando.

    TL;DR Eu configurei o servidor openssh no diretório chroot em vez de depender do ChrootDir.

    os posts vinculados me mostram como preparar um ambiente em contêiner ingênuo (não para produção, e apenas para experimentação):

    configurar o sistema de arquivos raiz

    no meu caso, crio uma partição dedicada para o rootfs e a inicializo com o pacstrap:

    mkfs.ext4 /dev/vdb1
    mount /dev/vdb1 /srv/container/test
    pacstrap /srv/container/test
    

    isolar o contêiner com namespace

    para conseguir isso, eu usounshare

    unshare -mpfu chroot /srv/container/test /usr/bin/bash
    

    a opção acima cria um novo namespace para mount, processe uts.

    e cada vez que entro no chroot, preciso preparar o VFS para fornecer alguma funcionalidade do kernel como /proce /dev:

    mount -vt devtmpfs dev /dev
    mount -vt proc proc /proc
    

    o isolamento relacionado à rede é feito usando ipem vez de unshare.

    no sistema host:

    ip netns add container-netns
    ip link add veth-host type veth peer name veth-container
    ip link set veth-container netns container-netns
    ip addr add 10.0.3.1/24 dev veth-host
    ip link set veth-host up
    

    dentro do recipiente

    ip addr add 10.0.3.2/24 dev veth-container
    ip link set veth-container up
    

    os comandos acima farão o seguinte:

    • criar novo namespace de rede chamadocontainer-netns
    • crie uma nova interface virtual chamada veth-hosteveth-container
    • adicione a veth-containerinterface ao novo container-netnsnamespace
    • atribuir endereço IP em ambas as interfaces virtuais, respectivamente

    permitir acesso à Internet no contêiner

    com o poder do iptables host:

    echo 1 > /proc/sys/net/ipv4/ip_forward
    iptables -A FORWARD -o ens3 -i veth-host -j ACCEPT
    iptables -A FORWARD -i ens3 -o veth-host -j ACCEPT
    iptables -t nat -A POSTROUTING -s 10.0.3.2/24 -o ens3 -j MASQUERADE
    

    e antes de entrar no contêiner, você precisa encapsular unshareo comando comip netns exec container-netns <unshare ...>

    dentro do recipiente

    ip route add default via 10.0.3.1
    echo 8.8.4.4 >> /etc/resolv.conf
    

    iniciar servidor ssh

    Preciso puxar /usr/bin/{sshd,ssh-keygen}, /etc/ssh/sshd_confige /usr/lib/ssh/sshd-sessioncriar /usr/share/empty.sshdum diretório (embora eu possa reinstalar openssho pacote com o pacman dentro do contêiner)

    ssh-keygen -A
    `command -v sshd` -dD
    
    • gerar chave de host ssh no servidor
    • executar servidor ssh

    se algo não estiver explicado corretamente ou for enganoso, por favor me avise.

    • 0

relate perguntas

  • Como descobrir detalhes sobre hardware na máquina Linux?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Você pode passar usuário/passar para autenticação básica HTTP em parâmetros de URL?

    • 5 respostas
  • Marko Smith

    Ping uma porta específica

    • 18 respostas
  • Marko Smith

    Verifique se a porta está aberta ou fechada em um servidor Linux?

    • 7 respostas
  • Marko Smith

    Como automatizar o login SSH com senha?

    • 10 respostas
  • Marko Smith

    Como posso dizer ao Git para Windows onde encontrar minha chave RSA privada?

    • 30 respostas
  • Marko Smith

    Qual é o nome de usuário/senha de superusuário padrão para postgres após uma nova instalação?

    • 5 respostas
  • Marko Smith

    Qual porta o SFTP usa?

    • 6 respostas
  • Marko Smith

    Linha de comando para listar usuários em um grupo do Windows Active Directory?

    • 9 respostas
  • Marko Smith

    O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL?

    • 3 respostas
  • Marko Smith

    Como determinar se uma variável bash está vazia?

    • 15 respostas
  • Martin Hope
    Davie Ping uma porta específica 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    kernel O scp pode copiar diretórios recursivamente? 2011-04-29 20:24:45 +0800 CST
  • Martin Hope
    Robert ssh retorna "Proprietário incorreto ou permissões em ~/.ssh/config" 2011-03-30 10:15:48 +0800 CST
  • Martin Hope
    Eonil Como automatizar o login SSH com senha? 2011-03-02 03:07:12 +0800 CST
  • Martin Hope
    gunwin Como lidar com um servidor comprometido? 2011-01-03 13:31:27 +0800 CST
  • Martin Hope
    Tom Feiner Como posso classificar a saída du -h por tamanho 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent Como determinar se uma variável bash está vazia? 2009-05-13 09:54:48 +0800 CST

Hot tag

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve