Trojaned Ssh Daemon Component Hwclock Binário Opções
Este artigo faz parte da série BackupYourSystem. Mais informações introdutórias podem ser encontradas lá. Introdução a partir da página man: Rsync é uma ferramenta de cópia de arquivos rápida e extraordinariamente versátil. Ele pode copiar localmente, de outro host em qualquer shell remoto, ou de um demônio rsync remoto. Oferece um grande número de opções que controlam todos os aspectos do seu comportamento e permitem uma especificação muito flexível do conjunto de arquivos a serem copiados. É famoso por seu algoritmo de transferência delta, que reduz a quantidade de dados enviados pela rede enviando apenas as diferenças entre os arquivos de origem e os arquivos existentes no destino. O Rsync é amplamente utilizado para backups e espelhamentos e como um comando de cópia melhorado para o uso diário. Por outras palavras, a rsync é uma ferramenta para copiar e fazer cópias de segurança de dados de um local (a fonte) para outro (o destino) de maneira eficiente. É eficiente porque ele só transfere arquivos que são diferentes entre os diretórios de origem e de destino. Rsync é um utilitário de linha de comando. Os usuários que tentam usá-lo devem estar familiarizados com a linha de comando (consulte Usando o Terminal). Se você preferir uma interface gráfica, veja a seção Grsync desta página. Instalação Rsync está instalada no Ubuntu por padrão. Certifique-se de verificar se os seguintes pacotes estão instalados antes de iniciar (consulte Instalar um pacote): rsync, xinetd, ssh. Execute um backup simples O método mais simples para fazer backup em uma rede é usar rsync via SSH (usando a opção - e ssh). Alternativamente, você pode usar o daemon rsync (veja Rsync Daemon, que requer muito mais configuração. O backup local requer apenas rsync e readwrite o acesso às pastas que estão sendo sincronizadas. Abaixo, você encontrará exemplos de comandos que podem ser usados para fazer backup em ambos os casos. Deve notar-se que uma sincronização de rede pode ser realizada localmente, desde que a pasta seja compartilhada (digamos, por Samba) e depois montada na máquina com a pasta 1. Esse processo começa a usar ssh, mas é menos seguro e só deve ser usado Em redes privadas seguras, como em sua casa. Backup Over Network Uma explicação das opções acima para comandos: --dry-run Isso diz a rsync para não fazer nada. Apenas escreverá um registro do que faria na tela. Uma vez que você tenha certeza de que tudo funcionará como você espera, você deve remover esta opção e executar o comando novamente para executar o backup real. --deletar exclui arquivos que não existem no sistema que está sendo feito backup. (Opcional) - a preserva A data e t Imes e permissões dos arquivos (o mesmo que - rlptgoD). Com esta opção, rsync irá: Desça recursivamente em todos os diretórios (-r), copie os enlaces simbólicos como links simbólicos (-l), preserve as permissões do arquivo (-p), preserve os tempos de modificação (-t), preserve a propriedade do arquivo (-o) e - z comprime os dados - vv aumenta a verbosidade do processo de relatório - e especifica shell remoto para usar folder1 e folder2 Nos exemplos acima, folder1 e 2 são espaços reservados para que os diretórios sejam sincronizados. Folder1 é a pasta original e 2 é a nova pasta, ou uma existente para ser sincronizada com a primeira. Substitua-os pelas pastas que você gosta. A foi adicionado após a pasta1 para que apenas o conteúdo, em vez da pasta inteira, fosse movido para o segundo. Uma sinopse completa de todas as opções com o comando rsync pode ser encontrada nas páginas man em Resumo das opções. A página man para rsync também pode ser encontrada no linux. die Grsync é uma interface gráfica da GUI para o utilitário rsync. A interface simples da GUI expõe muitas das opções básicas disponíveis com rsync. É útil para aqueles que preferem não usar a linha de comando. Instalação O programa grsync não vem instalado por padrão no Ubuntu ou em qualquer outra destruição, mas é facilmente disponível nos Repositórios principais. Para obter uma correção de segurança, a seção Universe dos repositórios do Ubuntu está habilitada em suas fontes de software. Em seguida, para instalar este software no Ubuntu, instale o seguinte pacote. Grsync. Configuração Para iniciar o grsync, percorra os seguintes menus: Aplicativos --Gt System Tools --gt grsync. Após o início, você será apresentado com a janela principal, onde toda a configuração ocorre. Nesta janela são todas as opções que a maioria dos usuários sempre precisará. Para explicar, as opções serão listadas e seus efeitos mencionados. Sessões - Esta função é igual a perfis em outros. Cada sessão armazenará um conjunto diferente de diretórios de origem e destino, bem como as opções de configuração associadas ao par de pastas. Isso permite a sincronização de diferentes conjuntos de pastas de acordo com diferentes opções. O gerenciamento de sessões é simples, basta pressionar o botão Adicionar para adicionar um novo. Para excluir, selecione a sessão que não deseja mais do menu suspenso e pressione Excluir. Fonte e Destino - Estas duas caixas lista as duas pastas (tecnicamente referidas como diretórios) que serão sincronizadas. O topo é a Origem e a parte inferior do Destino. Então, quando você executa a sincronização, os arquivos da Fonte serão copiados para o Destino de acordo com as opções que um usuário seleciona. Para especificar os diretórios, procure-os na GUI ou digite-os de acordo com as convenções de caminho padrão. Switch - O sinal de recarregamento universal localizado à direita dos botões Procurar é um botão acessível. Ele mudará instantaneamente a Origem com o Destino. Importar e Exportar - Depois de ter configurado as sessões, um usuário pode querer fazer backup delas para armazenamento. Para fazer isso, basta ir ao Menu Sessões na parte superior e selecionar Importar ou Exportar. O primeiro irá restaurar uma sessão a partir de um backup anteriormente feito, o último fará um backup da sessão atual. Nota: Esta função de backup funciona em uma base por sessão. Isso significa que cada sessão que deseja fazer backup deve ser selecionada na lista suspensa e, em seguida, em backup. Se você tiver 3 sessões diferentes, selecione cada um deles e exporte-os. Mesmo ao importar sessões. Opções básicas - A maioria dos usuários encontrará a maioria das opções que eles nunca precisarão aqui. Os quatro primeiros preservarão as propriedades dos arquivos transferidos. Os outros modificarão como os arquivos são copiados. Para obter mais informações sobre o que cada um faz especificamente, posicione seu cursor estacionário sobre a opção e exibirá uma pequena explicação. As opções verificadas são, naturalmente, as que serão aplicadas durante a sessão. Opções avançadas - Esta guia contém mais opções, muitas são úteis e auto-explicativas. Para aqueles que não são entendidos, as dicas de ferramentas serão exibidas quando o mouse permanecer sobre uma opção o tempo suficiente. Opções adicionais - Esta caixa de entrada permite a entrada de opções adicionais não apresentadas na GUI, mas conhecidas pelo usuário. O uso é sugerido apenas para usuários experientes, a entrada de opções malformadas pode ter conseqüências inesperadas. Simulação e Execução Os dois últimos botões na janela são Simulação e Execução. O botão para simulação é muito útil quando incerto o que acontecerá com base nas opções selecionadas. A tela de diálogo de transferência normal será exibida e, no painel principal, uma lista de arquivos que foram copiados foi listada. O usuário pode verificar se isso é conforme desejado ou fazer alterações. Uma vez que a sessão é iniciada com o botão Executar, a caixa de diálogo aparecerá novamente, mas desta vez, ele processará as pastas de acordo. Certifique-se antes de empurrar Execute que você está feliz com a simulação. O backup de backup remoto em uma rede é possível, de preferência o usuário deve montar o compartilhamento de rede para fazer backup até antes de iniciar o programa. O compartilhamento seria listado na GUI de Navegação e poderia ser facilmente adicionado. Não há uma seção separada para a rede, se recursos mais avançados forem necessários, o usuário é encorajado a procurar alternativas, das quais há muitas. Alternativas Existem várias alternativas, em vários estágios de desenvolvimento. Para uma lista incompleta, veja aqui. Rsync Daemon O daemon rsync é uma alternativa ao SSH para backups remotos. Embora seja mais difícil de configurar, oferece alguns benefícios. Por exemplo, usar SSH para fazer um backup remoto de um sistema inteiro exige que o daemon SSH permita o login do root, que é considerado um risco de segurança. O uso do daemon rsync permite que o login do root via SSH seja desabilitado. Configuração do rsync Daemon 1. Edite o arquivo etcdefaultrsync para iniciar o rsync como daemon usando o xinetd. A entrada listada abaixo, deve ser alterada de falso para inetd. 2. Instale o xinetd porque não está instalado por padrão. 3. Crie o arquivo etcxinetd. drsync para iniciar o rsync via xinetd. Ele deve conter as seguintes linhas de texto. 4. Crie a configuração do arquivo etcrsyncd. conf para rsync no modo daemon. O arquivo deve conter o seguinte. No arquivo, o usuário deve ser substituído pelo nome do usuário na máquina remota que está logada. 5. Crie etcrsyncd. secrets para a senha dos usuários. O usuário deve ser o mesmo que acima, com a senha usada para fazer login na máquina remota como o usuário indicado. 6. Esta etapa define as permissões de arquivo para rsyncd. secrets. 7. StartRestart xinetd Execute o seguinte comando para verificar se tudo está bem. A saída listada é apenas uma amostra, deve ser o que está em sua máquina remota compartilhada. O nome do host pode ser substituído pelo endereço IP da máquina. Backup com Rsync e Ssh (deslize para o fundo se quiser uma sinopse muito menos informativa do que será abordado) Quando eu comecei a mexer com essa idéia, toda a coisa do SSH me confundiu, principalmente porque não pensei que SSH seria fácil Para que um usuário final utilize. Enquanto o SSH é muito complexo em design, eles tornaram muito fácil para o usuário final configurar um conjunto de chaves de autenticação. Essencialmente, o SSH é uma conexão autenticada de 1 a 1 que pode ser obtida sem uma senha. Uma vez que este está no lugar, você pode utilizar o rsync para executar automaticamente. Antes de começar, assegure-se de ter o servidor openssh instalado em seu servidor de arquivos em questão. Em seguida, precisamos configurar um par de chaves. Você receberá uma chave pública e uma chave privada. Você receberá algumas perguntas, como se você quer ou não uma senha para o par de chaves, etc. Eu escolhi não e, basicamente, deixei tudo o resto padrão. Fui sem senha porque as chaves SSH são muito seguras e, mais eu queria que isso fosse automatizado. Eu não tinha certeza de como eu poderia automatizar esse processo enquanto ainda tinha uma senha nele. A chave pública precisa ser copiada para o arquivo authorizedkeys no servidor. Graças a um comando útil, isso é indolor. Substitua jason192.168.1.150 pelo que sua configuração seria. Ele pedirá sua senha. Coloque sua senha na conta de usuário em que você está autenticando no servidor de arquivos. Uma vez feito, você deve ser capaz de executar: se não pediu uma senha e seu prompt mudou, você deve ir. Se lhe pedisse uma senha, é provável que algo seja apagado. Por favor, note que, se você mexer com as chaves SSH (excluindo-as, adicionando novas, etc.), ela precisa de uma reinicialização (algumas pessoas me disseram que efetuar logs funcionam bem também) para redefinir. Eu não sei o suficiente sobre isso para explicar o que está acontecendo além de tomar o palpite educado de que a chave SSH está sendo bloqueada em sua sessão. A menos que você planeje mexer como eu fiz, onde eu apagaria as chaves do SSH e re-gerá-las uma e outra vez para fins de aprendizagem, você não vai se deparar com esse problema. Mas se você fizer isso, eu queria jogar isso lá fora. Então, SSH está configurado e você está disposto a ir. Agora, o que é o rsyncs. Você abriu a porta com a SSH, agora você precisa colocá-la em marcha com o rsync. Rsync é uma ferramenta de sincronização remota. Para meus usos, é praticamente incrível. Sugiro que você leia a página do manual rsync para obter mais informações. Apenas uma nota lateral, qualquer um que lê isso que usa o Linux, mantenha as páginas man em mente. Eles são mais rápidos que o Google. Honestamente. Você pode lê-los, indo ao terminal e digitando o man rsync. Claro, você pode substituir a rsync por qualquer outro comando para ler mais sobre isso também, aka man cp, etc. A página man irá examinar a funcionalidade de um monte de bandeiras. Há algumas que eu pessoalmente uso e as cobrei em minhas próprias palavras abaixo. - um modo de arquivo. Isso mantém o tempo, as permissões, o proprietário, o grupo e outras configurações diferentes da mesma fonte. Eu gosto de usar - a porque garante que meus dados no servidor de arquivos correspondam aos meus dados na área de trabalho, até mesmo para quem possui o que e os carimbos de hora. - z Modo de compressão. Eu realmente não usei isso até recentemente. Não tenho certeza se percebo uma diferença porque a rsync é bastante rápida para começar, mas eu aponto lá, principalmente porque, por que não --exclua o modo Excluir. Isto é, se você deseja excluir um diretório específico, lixo, vídeos, etc. Por exemplo, digamos que deseja excluir TODAS as pastas de arquivos ocultas. Você faria --exclua. Aviso após o sinal de igual, há um período e Isso garante que você esteja fazendo o wild card, ou seja, TUDO, mas somente após o período. Uma vez que as pastas de arquivos ocultas são iniciadas com um período, você pode ver como ela incluiria. folder1.folder2.folder3, etc. Nota - Pessoalmente, eu definitivamente recomendaria excluir. gvfs. Gvfs é o sistema de arquivos virtual do gnome. Ele basicamente atua como um ponto de montagem para recursos de rede. Digamos que seu servidor de arquivos é acessível através de. gvfs. Se você rsync tudo e não exclui. gvfs, você está basicamente duplicando os dados em seu servidor de arquivos que já existem, porque ele existe na sua pasta principal, bem como através de. gvfs, graças ao seu servidor de arquivos. HomejasonDocuments homejasonMusic homejasonPictures homejason. gvfsDocuments homejason. gvfsMusic homejason. gvfsPictures Ao excluir. gvfs, você evita isso tudo em conjunto. Se você estiver fazendo backup de um diretório inicial, Id sugere fazê-lo. Usando simplesmente --exclude. gvfs funciona para mim, mas se você precisar do caminho completo, é claro que será --excludehomejason. gvfs --delete Isso irá excluir arquivos no destino que não existem na fonte. Digamos que você tenha uma pasta que contenha 100 GB de dados e seus dados simplesmente nomeados. Se você renomeá-lo para data2, seu servidor conteria uma cópia de dados e dados2 um total de 200 GB. Se desejar que os dados no seu servidor sejam idênticos, use --delete. Se você quiser ter algum tipo de redundância de arquivos mais antiga (eu sei que algumas pessoas preferem isso), não use --delete. --progress Se você executar rsync manualmente, você poderá ver o progresso do que está acontecendo em vez de apenas um cursor intermitente. Eu uso apenas esta bandeira se eu quiser executar o comando manualmente e ver o que está fazendo. Eu não me incomodo usando isso quando é hora de mostrar e eu quero que seja automatizado em segundo plano. Além disso, é apenas configurar a origem e o destino. Comece com o destino, já que, afinal, estavam mexendo com o SSH aqui, então é um pouco diferente. Para o destino, você precisará do usuário, servidor e caminho da pasta. Como eu disse, meu nome é Jason e meu servidor de arquivos é 192.168.1.150. O caminho da minha pasta em meu servidor em particular é mediaNASjason. No meu caso, o NAS é uma unidade de rede que compartilhei, então é bastante específica para minha situação. É provável que os seus filhos diferem. Adapte o destino para a sua própria situação. Se a sua unidade de backup for o mediastorage e você tiver uma pasta no armazenamento chamada frank, use o mediastoragefrank, etc. No meu caso: é meu destino. Agora, sobre as fontes. Eles são simples o suficiente, como é o mesmo que acima, exceto que ele não inclui o servidor de usuários. Se você deseja que seu diretório pessoal inteiro seja sincronizado, você pode fazê-lo com apenas: Se você deseja que seu diretório pessoal completo seja sincronizado, mas com a exclusão de. gvfs e o sinalizador --delete, use: Obtendo o jist dele agora. Observe, Você também pode ter várias fontes, o que torna acessível se você quiser apenas fazer backup de algumas pastas específicas no seu servidor de arquivos. No meu caso, eu tinha espaço limitado para o servidor de arquivos, então eu só queria fazer backup dos dados mais importantes no meu servidor de arquivos, o que para mim é Documents and Pictures. Exemplo: você pode configurar um trabalho do Cron para que isso seja executado em horários específicos. Eu nunca executo o rsync como root, então, quando eu configurá-lo no Cron, eu configurei-o para iniciar como jason e apenas etiquetado o comando rsync acima. Ive desde que se afastou da rota Cron. Eu desliguei meu computador à noite, mas meu servidor de arquivos permanece o tempo todo, adicionei uma entrada em Aplicativos de Inicialização para fazer o backup para mim, o que é útil porque ele é executado no arranque do sistema. Eu nomeei o NAS Backup e coloquei o comando acima no campo de comando. Tudo funciona como um encanto com zero input necessário de mim. Imagessmiliesguitar. gif Dica rápida, se você gostaria de verificar uma GUI rsync decente, dispare o grsync. É fácil de usar e irá ajudá-lo a estruturar o comando rsync se ainda não estiver completamente seguro. Basta notar, não há nenhuma marca --excluir na GUI, então você precisará adicioná-la manualmente em Opções adicionais, mas isso é muito fácil de fazer. O Grsync também não usa - a, mas sim quebra - a para - t - o - p - g etc. Leia a página do manual rsync sob a seção - a para ver por que isso faz a diferença littleno. Uma vez que você o tenha formulado da maneira que quiser, você também pode fazer um teste, que é uma das características do grsync para garantir que ele funcione corretamente antes de dar a luz verde. Assumindo que tudo está bem e você está pronto, você pode agendar este trabalho com o Grsync, você adivinhou, seja Startup Applications ou Cron. Tenha em mente que a sintaxe é grsync - e nome do trabalho. Então, se você chamou o backup do trabalho, você executou o backup grsync - e. Isso seria o mesmo para Cron ou aplicativos de inicialização. Testei-o executando-o em aplicativos de inicialização. Ele aparece com uma janela GUI quando eu logar me mostrando o status da transferência de dados. Se eu for na rota com Aplicações de Inicialização e apenas atirando o comando rsync completo, ele faz isso completamente em segundo plano. Dependendo da quantidade de um status visual que você deseja, ditará qual rota você vai. De qualquer forma, gratificantes elogios à equipe SSH, Rsync e Grsync, já que fabricaram algumas tecnologias muito impressionantes aqui. O acima foi feito para ser super informativo. Espero que alguns usuários possam configurar um sistema de backup que funcione para eles. Tenha em mente, você nunca sabe quando o Sr. HardDrive vai ao tanque em você, então avance. Abaixo está um resumo aproximado do que você está fazendo para os usuários que não querem ler uma montanha de texto. Nota: mude as configurações abaixo para coincidir com sua configuração, a menos que seu nome aconteça ser Jason e seu servidor de arquivos passa a ser 192.168.1.150. Aplicativos de Inicialização de Cliente - Selecione Novo - Nomeie o backup ou o que quiser, e adicione a linha rsync desejada na caixa de comando, como por exemplo: Steve Friedls Unixwiz Tech Tips Muitos usuários implementaram o Secure Shell (ssh) para fornecer acesso protegido a um Linux remoto Sistema, mas não percebem que ao permitir autenticação de senha, eles ainda estão abertos a ataques de força bruta de qualquer lugar na internet. Existem worms correntes desenfreados na internet que fazem um trabalho efetivo encontrando combinações fracas de senha de nome de usuário, e estas não são interrompidas pelo uso do Secure Shell. Esta Dica Técnica detalha como usar o cliente PuTTY SSH gratuito para se conectar a um sistema Linux executando o servidor OpenSSH, tudo ao usar criptografia de chave pública e suporte de agente SSH. Muitas dessas informações se aplicam a qualquer instalação do OpenSSH em qualquer sistema UNIX - Solaris, BSD, OpenServer -, mas nós fomos direcionados para a plataforma Linux quando os requerimentos são específicos. Instalação e configuração simples Fornecendo acesso total sem senhas e com base em agente requer muitos passos, então, aproxime isso em etapas fornecendo primeiro acesso com senha padrão ao sistema. Isso permite testar a instalação inicial e a capacidade de login antes de ativar os recursos mais avançados. Baixe e instale os programas Ao contrário da maioria dos programas do Windows, o conjunto PuTTY não requer um instalador: os arquivos. EXE individuais são simplesmente colocados em um diretório onde são executados diretamente. Admiramos a economia e o estilo que o autor PuTTYs demonstra. Os arquivos podem ser descartados em qualquer diretório que esteja no caminho de comando dos usuários, e normalmente usamos C: BIN (veja o próximo item para saber como configurar isso). Cinco arquivos devem ser baixados do site PuTTY. PuTTY. exe mdash Cliente Shell Seguro PuTTYgen. exe mdash SSH gerador de chave públicapripriate Pagent. exe mdash SSH agente da chave PSCP. exe mdash Cópia segura da linha de comando PSFTP. exe mdash Cópia segura com interface tipo FTP Certifique-se de que o diretório de instalação esteja no comando Caminho Embora seja possível executar o PuTTY com um caminho completo ou atalho, na prática é útil quando está totalmente disponível no prompt CMD para acessar ou copiar arquivos de qualquer lugar do sistema de arquivos. Clique com o botão direito do mouse em Meu Computador na área de trabalho e selecione Propriedades. Clique na guia Avançado na parte superior e, em seguida, clique no botão Variáveis de ambiente. Isso exibe a caixa de diálogo mostrada à direita. Existe sempre uma variável PATH na seção Variáveis do sistema, e às vezes também na seção Variáveis de usuário. Somente os administradores têm acesso às Variáveis do Sistema, então Edite ou Adicione o CAMINHO conforme necessário. Normalmente, colocamos o novo diretório no início do caminho, e é separado do resto da lista com um ponto e vírgula. Clique em OK para salvar todas as alterações. Criar um atalho na área de trabalho PuTTY é freqüentemente usado pesadamente por um trabalhador de TI, por isso é útil ter um atalho na área de trabalho para facilitar o acesso. Para adicionar isso, clique com o botão direito do mouse na área de trabalho e clique em Novo atalho. Ou navegue para, ou digite o nome, o caminho do executável PuTTY. No nosso exemplo, foi C: binputty. exe. Clique em OK e atribua ao atalho um nome conveniente. Inicie PuTTY e configure para o sistema de destino. Inicie o PuTTY através do atalho e exibirá a caixa de diálogo de configuração: existem várias opções aqui. Bem preencha vários para fornecer acesso com senha ao sistema, depois configure para acesso de chave pública mais tarde. Categoria: Hostname: dbserver Protocol: () SSH Connection. Nome de usuário de login automático de dados: conexão de steve. SSH Versão de protocolo SSH preferida: () 2 Somente uma vez que essas configurações simples foram inseridas, elas podem ser salvas para facilitar o acesso na próxima vez. Clique na sessão à esquerda e, em seguida, insira um nome em Sessões salvas - este nome geralmente estará relacionado à máquina à qual está se conectando. Clique em Salvar para armazenar essas configurações no Registro: selecionamos o nome do servidor de banco de dados. Login Com as configurações salvas da etapa anterior, wed para usá-las para se conectar ao sistema alvo. Inicie o PuTTY (se não estiver já aberto) e, na seção Sessão, clique no nome da sessão salva e clique em Carregar. Clique em Abrir para iniciar a conexão. Quando solicitado, digite a senha da sua conta no sistema remoto e, se correto, você receberá um shell. Agora você pode começar a trabalhar no sistema. No entanto, cada vez que o PuTTY se conecta com um servidor, troca a identificação na forma de chaves do host. Se a chave de host for desconhecida ou não combinando com o que vimos anteriormente, ele avisa o usuário. Para hosts desconhecidos, esta é principalmente uma operação pro forma, mas para sistemas anteriormente conhecidos, pode sugerir que o host não seja o mesmo que originalmente conectado. As chaves de host que mudaram sem aviso podem ocorrer quando o sistema operacional de destino é reinstalado sem restaurar as chaves de host do backup, ou pode ser algo mais nefasto, como um host rogue mascarado como o genuíno. É preciso sempre investigar as chaves de host alteradas de forma inesperada. Criando e usando várias sessões. Quando o usuário só precisa se conectar a um sistema, é possível programar nesses parâmetros na Sessão Padrão, mas é muito mais comum acessar vários sistemas. Com um pouco de configuração, podemos criar e conectar facilmente esses sistemas com um clique. Crie e salve as sessões Como fizemos na seção anterior, crie e salve tantas sessões nomeadas quanto necessário, e anote os nomes das sessões. Esses nomes podem ser referenciados na linha de comando com o parâmetro - load e podem ser incorporados no atalho. Clique com o botão direito do mouse no atalho e selecione Propriedades, então insira o parâmetro - load juntamente com o nome da sessão (entre aspas, se necessário). Clique em OK para salvar as propriedades do atalho. É também uma boa idéia mudar o nome do atalho para refletir o nome do servidor ao qual está se conectando: clique com o botão direito do mouse no atalho e selecione Renomear. Uma vez que o atalho da sessão está totalmente configurado, clique duas vezes no ícone lança a conexão. Crie tantos atalhos pré-programados quanto necessário. Crie e instale um par de chaves publicprivate O poder real do Secure Shell entra em jogo quando as chaves publicprivate são usadas. Ao contrário da autenticação de senha, o acesso à chave pública é feito executando uma criação única de um par de números binários muito longos que estão matematicamente relacionados. A etapa de configuração inicial está moderadamente envolvida, mas precisa ser feita apenas uma vez: uma vez criada, a chave pode ser facilmente instalada em tantos sistemas remotos como desejado. Run PuTTYgen Um par de chaves publicprivate mdash pequenos arquivos contendo mdash de números binários muito grandes é necessário, e PuTTYgen faz isso. É executado apenas uma vez para criar um par pessoal de chaves, que são então instaladas onde for necessário. Clique em Iniciar. então corra . Em seguida, insira puttygen na caixa de linha de comando. Isso exibe a caixa de diálogo principal, mostrada à direita. Selecione os parâmetros-chave como mostrado e clique em Gerar. Como o tamanho do teclado DSA é fixado em 1024 bits, e o tamanho das chaves RSA pode ser feito muito maior, recomendamos uma chave RSA de 2048 bits. Observe que o padrão é 1024 bits, você deve substituir manualmente para selecionar 2048. Nota: Não crie uma chave SSH versão 1 de qualquer tipo: elas não são seguras. Você será solicitado a criar alguma aleatoriedade ao mover o mouse ao redor: isso dá ao sistema alguma entropia adicional que ajuda a criar melhores chaves. Isso leva apenas alguns segundos para gerar completamente o par de chaves. Proteja e salve as chaves Agora o par de chaves foi gerado, mas existe apenas na memória PuTTYgens: ele deve ser salvo no disco para ser de qualquer utilidade. Embora a chave pública não contenha informações confidenciais e será instalada em sistemas remotos, a chave privada deve ser protegida vigorosamente: qualquer pessoa que conheça a chave privada tenha uma execução completa de todos os sistemas remotos. A chave privada normalmente está protegida com uma senha, e esta frase é inserida duas vezes nos campos indicados. O comentário é opcional, mas é normalmente o endereço de e-mail do proprietário da chave. Também pode ser apenas o nome do proprietário. Não esqueça a frase-senha de que o par de chaves é inútil sem ele. A chave gerada agora deve ser salva, e isso é feito em três partes: Salvar Chave Pública e Salvar Chave Privada, tanto para um nome de arquivo quanto para a chave privada (com extensão. ppk) deve ser salvo em um local seguro. A chave pública está em um formato padrão e pode ser usada direta ou indiretamente por outro software, e isso parece: a chave privada está em um formato específico de PuTTY que não pode ser usado por nenhum outro software. Nunca será examinado diretamente pelo operador. Instale a chave pública no sistema Linux Com o puttygen ainda aberto, destaque toda a Chave Pública para colar na área do arquivo OpenSSH authorizedkeys e digite controle-C para copiar para a área de transferência dos sistemas locais. Este é essencialmente os mesmos dados encontrados no arquivo de chave pública salvo, mas é de uma forma que pode ser usada diretamente no sistema Linux. Faça login no computador Linux usando a senha das contas, crie o diretório. ssh, se necessário, edite o arquivo. sshauthorizedkeys. Este será um arquivo de texto, e a área de transferência deve ser colada nela. A chave pública será apenas uma linha longa, e é realmente fácil colar os dados de uma maneira que trunca os primeiros caracteres. Isso torna a chave inoperável, então certifique-se de que a chave comece ssh-rsa ou ssh-dsa. Salve o arquivo. Certifique-se de que tanto o diretório. ssh quanto os arquivos dentro dele são legíveis apenas pelo usuário atual (esta é uma precaução de segurança), e isso pode ser alcançado usando o comando chmod com os parâmetros que se aplicam a todo o diretório: Feche o sistema. Nota: o arquivo authorizedkeys deve ser de propriedade do usuário e não legível por qualquer outra pessoa - o servidor OpenSSH negará os logins se não for esse o caso. Pode-se verificar isso com o comando ls: O arquivo deve ser o modo - rw -------. Anexe a chave privada à sessão SSH Agora que o par de chaves publicprivate foi criado, ele pode ser associado a uma sessão SSH. Primeiro, bem, faça isso no PuTTY, iniciando o programa e carregando a sessão de interesse. Navegue até Conexão. SSH. Autente no painel de categorias à esquerda, preencha o arquivo de chave particular para o campo de autenticação, navegando para o arquivo. ppk salvo anteriormente. Nota - Com outros clientes do Secure Shell, vimos a capacidade de anexar uma chave privada a todas as sessões (como parte de uma configuração global), mas com PuTTY parece exigir configuração para cada sessão. Não tinha certeza do porquê. Retorne ao nível da categoria Sessão e guarde a sessão atual. Neste ponto, PuTTY (no Windows) e OpenSSH (no Linux) são ambos configurados para acesso seguro e de chave pública. Conecte-se através da chave pública Agora que as etapas de configuração foram concluídas, estavam prontas para entrar efetivamente usando o mecanismo da chave pública, evitando completamente a etapa da senha. Conecte-se de forma segura. Lance o PuTTY com opções para carregar a sessão salva com a chave privada: Em vez de solicitar a senha das contas (que será diferente em todos os sistemas remotos), em vez disso, pede a frase secreta que protege a chave privada local. Quando a chave privada se encaixa na chave pública no servidor OpenSSH, acesso concedido e um shell apresentado ao usuário. É importante notar que, embora o usuário digite uma palavra secreta ao efetuar o login, a frase secreta está associada à chave privada local. Não é a conta remota. Mesmo que a chave pública dos usuários esteja instalada em 1.000 diferentes servidores remotos, a mesma frase secreta de chave privada é exigida para todos eles. Isso simplifica muito a tarefa de lembrar as credenciais de acesso e encoraja a escolha de pessoas fortes e seguras. Desabilitando a autenticação de senha no OpenSSH Uma vez que o par de chaves público e privado dos usuários seja verificado como correto, é possível desabilitar completamente a autenticação de senha no servidor Linux. Isso impede totalmente todas as possíveis tentativas de adivinhação de senha e protege dramaticamente uma máquina. No entanto, para máquinas não fisicamente locais, é sábio adiar para desativar a autenticação de senha até que seja absolutamente claro que o acesso com chave está funcionando corretamente, especialmente se vários usuários estiverem envolvidos. Uma vez que a autenticação de senha foi desativada, mesmo a senha de root não permitirá uma no sistema. Os novos acessos à chave pública são encorajados a testar com muito cuidado. A configuração do SSD Daemon é encontrada no arquivo sshdconfig, muitas vezes armazenado no diretório etcssh. Este é um arquivo de texto que é relativamente fácil de ler, bem, procurando duas entradas para modificar. Primeiro é configurar PasswordAuthentication para o valor no. Isso pode ser definido explicitamente como sim. or it may be commented out to rely on the default, but we wish to explicitly disable this: Second, we wish to disable SSH protocol version 1: this is old, has several substantial security weaknesses, and should not be allowed from the outside world. Edit the configuration file and ensure that the two keyword entries are set properly comment out the old entries if necessary. Once the configuration file has been saved, the Secure Shell daemon must be restarted on most platforms this can be done with the service mechanism: This kills the listening daemon and restarts it, but does not terminate any existing individual user sessions. Those who feel this might be a risky step are invited to simply reboot the machine. At this point, OpenSSH will no longer accept passwords of any kind, with access granted only for users with pre-established public keys. Enabling SSH Agent Support Up to this point, weve provided a large manner of security of system access, but its still not terribly convenient: we still must type a (hopefully) complex pass phrase each time. This can get tedious when large numbers of systems are involved. Fortunately, the SSH suite provides a wonderful mechanism for unlocking the private key once, and allowing individual ssh connections to piggyback on it without querying for the passphrase every time. Launch the agent Navigate to and launch the pageant. exe program from the same location as the other PuTTY-related files, and it will put itself into the system tray (in the lower right near the clock). Double-click the icon in the tray, and it launches a dialog box with an empty list of keys. Click Add Key and navigate to the. ppk file which contains your private key. When prompted for the passphrase, enter it and click OK. Click Close to dismiss the agent. Now, launch one of the already-configured SSH sessions to a pubkey-secured remote host: it will query the agent for the private key, exchange it with the remote, and grant access without further user intervention. Note - the thoughtful reader may wonder just how the agent stores the data, and whether untrusted programs are able to obtain this secret key surreptitiously. Were not sure how it works, but weve not ever heard of real security concerns on this front. Well update this document if we learn something. Preload the private key The first thing that many PuTTY users do when logging into the system for the day is to launch the agent and add the private key. This is just a few steps, but we can optimize it just a bit more. If we launch the agent with the private key file as a parameter, it loads the key automatically. Navigate to pageant. exe and right-click to copy this icon. Paste this as a shortcut on the desktop, then right-click and select Properties. Enter the full path of the. ppk private key file as the parameter, then save the changes. Double-clicking this icon will load the keyfile, demanding the passphrase. Once entered, thats the last time its needed as long as the agent sticks around. There is very little not to like about SSH agent support. Agent Forwarding But weve not exhausted the benefits of SSH agent support. Its a clear win to avoid typing the passphrase every time a new connection is launched, but SSH also provides Agent Forwarding which can pass the credential down the connection to the remote server. This credential can then be passed to yet another server where the users public key has been installed, obviating passwords or the secret passphrase for the entire duration of a network navigation. User launches a connection to Server A: PuTTY on the local machine gets the private key from the agent and provides it to the remote server. Remote server processes the public and private key data and grants access. The user is given a shell on the local system. User attempts to connect to SystemB with ssh - A systemb ( - A enables agent forwarding), and it connects to the SSH server there. System B asks system A for the users private key data, and the SSH server on system A in turn forwards this back to the original workstation where the agent is queried. The local agent passes the data back up the connection, where its forwarded from SystemA to SystemB. SystemB receives this credential, and access is granted by comparing to the public key stored on that machine for that user. This happens automatically and quickly: it takes no more than a second or two for the entire exchange to occur, and this forwarding can go over quite a long chain of SSH connections. This provides for transparent, secure access to a wide range of remote systems. Note - All of this requires that the user have an account on each machine in question, and that the users public key is installed properly on each one. SSH forwarding doesnt provide any access which would not be granted absent forwarding it just adds a more convenient mechanism to whats already provided. Enable Forwarding in PuTTY Enabling agent forwarding is done in the PuTTY configuration dialogs much like all the rest, and just one additional box need to be checked. This option requires, of course, the use of pageant on the local system - without an agent, theres nothing to forward. Should a key-protected connection be attempted with no agent present, PuTTY will simply prompt for the passphrase as it has all along (and will do so on each connection ). Enable Forwarding on the Server In the example above, we saw that the user typed ssh - A host . but its common to make Use agent forwarding the default setting to remove the need to type the - A. The OpenSSH server configuration is found in sshdconfig . while the client configuration is in sshconfig (typically in the etcssh directory). The file can be edited and the ForwardAgent setting set to yes: This setting doesnt affect the server, so it requires no reboot or special operation for it to take effect: the next outbound connection will enable forwarding automatically. This change need be made only once (and its the default on some systems). Copying files securely With the configuration of PuTTY, public key access, and agent support (with forwarding), were prepared to step beyond terminal shell access and move files around. Secure Shell provides multiple methods for copying files from one machine to another, all working together with the same keys and agents. PSCP allows for command-line copying of files to and from a remote SSH server, and PSFTP provides an FTP-like interface for convenient file transfer. Well discuss both. PSFTP - an FTP-like client The PSFTP program can be launched from the command line or from a desktop shortcut, and in both cases accepts either a hostname or a saved session name. When launched, it connects to the target server (fully taking advantage of public keys and the local agent, if any), and presents a psftpgt prompt: Regular users of command-line FTP clients will find this familiar, though its certainly not up to the ease of use as popular GUI clients. The help command may provide some guidance. PSCP - Secure Copy Users at the command line may wish to copy files directly, and this is done with pscp . the Secure Copy command. Just like copying regular files on the local filesystem, pscp takes a machine name and directory as a source or destination. pscp can transfer one file at a time, or a whole set in a single instance: Curiously, the saved session name need not be provided just the hostname and the current username (which is usually taken automatically from the environment. It appears that psftp and pscp both consult the saved-session list, find an appropriate match, and then use the access information associated. This makes for a smooth file-transfer experience. Security Concerns and the Finer Points This Tech Tip has intended to provide a fast path to setting up a Secure Shell environment from workstation to server, but it has skipped over many of the finer points. The whole point of using Secure Shell is Security, and wed be remiss if we didnt touch on some of these points here. Well make the broader point that one must take care when working on an untrusted system: when using advanced features such as agent forwarding or private keys, one is at the mercy of a hostile operator. Kernel-based keyloggers and Trojaned binssh bi naries are just a few of many obvious risks when operating in that kind of environment. Here well touch on a few of the non-obvious points and note that in a trusted and controlled environment, these issues simply dont arise. Protect your private key Though the public key is of only minor concern, the private key must be protected vigorously. Anyone who can get to the decrypted private key (either by learning the passphrase, or brute-forcing it) has full run of all networks where the public key is installed. We strongly recommend limiting dramatically the number of places where the private key is kept. We presume that applications exist which can take a private-key file and attempt to brute-force the key, though weve not yet run across one. Agent use requires trusted machines Whenever an SSH key agent is present, whether it be on the local machine which initiates the outgoing connection, or on intermediate machines which are forwarding them, its technically possible for interlopers on those machines to get access to the secure channel. In OpenSSH, an ssh client communicates with the agent via a UNIX domain socket under the tmp directory( a representative file is tmpssh-DeB10132agent.10132 ), and its restricted to the local user. But superusers also have access to the socket, and its relatively straightforward to hijack the agent to connect to the same target machine. Related ResourcesOpenSSH is the premier connectivity tool for remote login with the SSH protocol. It encrypts all traffic to eliminate eavesdropping, connection hijacking, and other attacks. In addition, OpenSSH provides a large suite of secure tunneling capabilities, several authentication methods, and sophisticated configuration options. OpenSSH is developed by a few developers of the OpenBSD Project and made available under a BSD-style license. OpenSSH is incorporated into many commercial products, but very few of those companies assist OpenSSH with funding. Contributions towards OpenSSH can be sent to the OpenBSD Foundation. This site Copyright copy 1999-2017 OpenBSD. sshdconfig(5) - Linux man page sshdconfig - OpenSSH SSH daemon configuration file Description sshd (8) reads configuration data from etcsshsshdconfig (or the file specified with - f on the command line). The file contains keyword-argument pairs, one per line. Lines starting with and empty lines are interpreted as comments. Arguments may optionally be enclosed in double quotes () in order to represent arguments containing spaces. The possible keywords and their meanings are as follows (note that keywords are case-insensitive and arguments are case-sensitive): Specifies what environment variables sent by the client will be copied into the sessions environ (7). See SendEnv in sshconfig (5) for how to configure the client. Note that environment passing is only supported for protocol 2. Variables are specified by name, which may contain the wildcard characters and . Multiple environment variables may be separated by whitespace or spread across multiple AcceptEnv directives. Be warned that some environment variables could be used to bypass restricted user environments. For this reason, care should be taken in the use of this directive. The default is not to accept any environment variables. AddressFamily Specifies which address family should be used by sshd (8). Valid arguments are any, inet (use IPv4 only), or inet6 (use IPv6 only). The default is any. AllowAgentForwarding Specifies whether ssh-agent (1) forwarding is permitted. The default is yes. Note that disabling agent forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders. AllowGroups This keyword can be followed by a list of group name patterns, separated by spaces. If specified, login is allowed only for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid a numerical group ID is not recognized. By default, login is allowed for all groups. The allowdeny directives are processed in the following order: DenyUsers . AllowUsers . DenyGroups . and finally AllowGroups . See PATTERNS in sshconfig (5) for more information on patterns. AllowTcpForwarding Specifies whether TCP forwarding is permitted. The default is yes. Note that disabling TCP forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders. AllowUsers This keyword can be followed by a list of user name patterns, separated by spaces. If specified, login is allowed only for user names that match one of the patterns. Only user names are valid a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USERHOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. The allowdeny directives are processed in the following order: DenyUsers . AllowUsers . DenyGroups . and finally AllowGroups . See PATTERNS in sshconfig (5) for more information on patterns. AuthorizedKeysFile Specifies the file that contains the public keys that can be used for user authentication. AuthorizedKeysFile may contain tokens of the form T which are substituted during connection setup. The following tokens are defined: is replaced by a literal , h is replaced by the home directory of the user being authenticated, and u is replaced by the username of that user. After expansion, AuthorizedKeysFile is taken to be an absolute path or one relative to the users home directory. The default is. sshauthorizedkeys. Banner The contents of the specified file are sent to the remote user before authentication is allowed. If the argument is none then no banner is displayed. This option is only available for protocol version 2. By default, no banner is displayed. ChallengeResponseAuthentication Specifies whether challenge-response authentication is allowed (e. g. via PAM or though authentication styles supported in login. conf (5)) The default is yes. ChrootDirectory Specifies a path to chroot (2) to after authentication. This path, and all its components, must be root-owned directories that are not writable by any other user or group. After the chroot, sshd (8) changes the working directory to the users home directory. The path may contain the following tokens that are expanded at runtime once the connecting user has been authenticated: is replaced by a literal , h is replaced by the home directory of the user being authenticated, and u is replaced by the username of that user. The ChrootDirectory must contain the necessary files and directories to support the users session. For an interactive session this requires at least a shell, typically sh (1), and basic dev nodes such as null (4), zero (4), stdin (4), stdout (4), stderr (4), arandom (4) and tty (4) devices. For file transfer sessions using sftp, no additional configuration of the environment is necessary if the in-process sftp server is used, though sessions which use logging do require devlog inside the chroot directory (see sftp-server (8) for details). The default is not to chroot (2). Ciphers Specifies the ciphers allowed for protocol version 2. Multiple ciphers must be comma-separated. The supported ciphers are 3des-cbc, aes128-cbc, aes192-cbc, aes256-cbc, aes128-ctr, aes192-ctr, aes256-ctr, arcfour128, arcfour256, arcfour, blowfish-cbc, and cast128-cbc. The default is: aes128-ctr, aes192-ctr, aes256-ctr, arcfour256,arcfour128, aes128-cbc,3des-cbc, blowfish-cbc, cast128-cbc, aes192-cbc, aes256-cbc, arcfour Sets the number of client alive messages (see below) which may be sent without sshd (8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session. It is important to note that the use of client alive messages is very different from TCPKeepAlive (below). The client alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The client alive mechanism is valuable when the client or server depend on knowing when a connection has become inactive. The default value is 3. If ClientAliveInterval (see below) is set to 15, and ClientAliveCountMax is left at the default, unresponsive SSH clients will be disconnected after approximately 45 seconds. This option applies to protocol version 2 only. ClientAliveInterval Sets a timeout interval in seconds after which if no data has been received from the client, sshd (8) will send a message through the encrypted channel to request a response from the client. The default is 0, indicating that these messages will not be sent to the client. This option applies to protocol version 2 only. Compression Specifies whether compression is allowed, or delayed until the user has authenticated successfully. The argument must be yes, delayed, or no. The default is delayed. DenyGroups This keyword can be followed by a list of group name patterns, separated by spaces. Login is disallowed for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid a numerical group ID is not recognized. By default, login is allowed for all groups. The allowdeny directives are processed in the following order: DenyUsers . AllowUsers . DenyGroups . and finally AllowGroups . See PATTERNS in sshconfig (5) for more information on patterns. DenyUsers This keyword can be followed by a list of user name patterns, separated by spaces. Login is disallowed for user names that match one of the patterns. Only user names are valid a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USERHOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. The allowdeny directives are processed in the following order: DenyUsers . AllowUsers . DenyGroups . and finally AllowGroups . See PATTERNS in sshconfig (5) for more information on patterns. ForceCommand Forces the execution of the command specified by ForceCommand . ignoring any command supplied by the client and. sshrc if present. The command is invoked by using the users login shell with the - c option. This applies to shell, command, or subsystem execution. It is most useful inside a Match block. The command originally supplied by the client is available in the SSHORIGINALCOMMAND environment variable. Specifying a command of internal-sftp will force the use of an in-process sftp server that requires no support files when used with ChrootDirectory . GatewayPorts Specifies whether remote hosts are allowed to connect to ports forwarded for the client. By default, sshd (8) binds remote port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to connect. The argument may be no to force remote port forwardings to be available to the local host only, yes to force remote port forwardings to bind to the wildcard address, or clientspecified to allow the client to select the address to which the forwarding is bound. The default is no. GSSAPIAuthentication Specifies whether user authentication based on GSSAPI is allowed. The default is no. Note that this option applies to protocol version 2 only. GSSAPIKeyExchange Specifies whether key exchange based on GSSAPI is allowed. GSSAPI key exchange doesnt rely on ssh keys to verify host identity. The default is no. Note that this option applies to protocol version 2 only. GSSAPICleanupCredentials Specifies whether to automatically destroy the users credentials cache on logout. The default is yes. Note that this option applies to protocol version 2 only. GSSAPIStrictAcceptorCheck Determines whether to be strict about the identity of the GSSAPI acceptor a client authenticates against. If yes then the client must authenticate against the host service on the current hostname. If no then the client may authenticate against any service key stored in the machines default store. This facility is provided to assist with operation on multi homed machines. The default is yes. Note that this option applies only to protocol version 2 GSSAPI connections, and setting it to no may only work with recent Kerberos GSSAPI libraries. GSSAPIStoreCredentialsOnRekey Controls whether the users GSSAPI credentials should be updated following a successful connection rekeying. This option can be used to accepted renewed or updated credentials from a compatible client. The default is no. HostbasedAuthentication Specifies whether rhosts or etchosts. equiv authentication together with successful public key client host authentication is allowed (host-based authentication). This option is similar to RhostsRSAAuthentication and applies to protocol version 2 only. The default is no. HostbasedUsesNameFromPacketOnly Specifies whether or not the server will attempt to perform a reverse name lookup when matching the name in the. rhosts . and etchosts. equiv files during HostbasedAuthentication . A setting of yes means that sshd (8) uses the name supplied by the client rather than attempting to resolve the name from the TCP connection itself. The default is no. HostKey Specifies a file containing a private host key used by SSH. The default is etcsshsshhostkey for protocol version 1, and etcsshsshhostrsakey and etcsshsshhostdsakey for protocol version 2. Note that sshd (8) will refuse to use a file if it is groupworld-accessible. It is possible to have multiple host key files. rsa1 keys are used for version 1 and dsa or rsa are used for version 2 of the SSH protocol. IgnoreRhosts Specifies that. rhosts and. shosts files will not be used in RhostsRSAAuthentication or HostbasedAuthentication . etchosts. equiv and etcsshshosts. equiv are still used. The default is yes. IgnoreUserKnownHosts Specifies whether sshd (8) should ignore the users. sshknownhosts during RhostsRSAAuthentication or HostbasedAuthentication . The default is no. KerberosAuthentication Specifies whether the password provided by the user for PasswordAuthentication will be validated through the Kerberos KDC. To use this option, the server needs a Kerberos servtab which allows the verification of the KDCs identity. The default is no. KerberosGetAFSToken If AFS is active and the user has a Kerberos 5 TGT, attempt to acquire an AFS token before accessing the users home directory. The default is no. KerberosOrLocalPasswd If password authentication through Kerberos fails then the password will be validated via any additional local mechanism such as etcpasswd . The default is yes. KerberosTicketCleanup Specifies whether to automatically destroy the users ticket cache file on logout. The default is yes. KerberosUseKuserok Specifies whether to look at. k5login file for users aliases. The default is yes. KeyRegenerationInterval In protocol version 1, the ephemeral server key is automatically regenerated after this many seconds (if it has been used). The purpose of regeneration is to prevent decrypting captured sessions by later breaking into the machine and stealing the keys. The key is never stored anywhere. If the value is 0, the key is never regenerated. The default is 3600 (seconds). ListenAddress Specifies the local addresses sshd (8) should listen on. The following forms may be used: If port is not specified, sshd will listen on the address and all prior Port options specified. The default is to listen on all local addresses. Multiple ListenAddress options are permitted. Additionally, any Port options must precede this option for non-port qualified addresses. LoginGraceTime The server disconnects after this time if the user has not successfully logged in. If the value is 0, there is no time limit. The default is 120 seconds. LogLevel Gives the verbosity level that is used when logging messages from sshd (8). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of debugging output. Logging with a DEBUG level violates the privacy of users and is not recommended. MACs Specifies the available MAC (message authentication code) algorithms. The MAC algorithm is used in protocol version 2 for data integrity protection. Multiple algorithms must be comma-separated. The default is: hmac-md5,hmac-sha1,umac-64openssh , hmac-ripemd160,hmac-sha1-96,hmac-md5-96 Introduces a conditional block. If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. The arguments to Match are one or more criteria-pattern pairs. The available criteria are User . Group . Host . and Address . The match patterns may consist of single entries or comma-separated lists and may use the wildcard and negation operators described in the PATTERNS section of sshconfig (5). The patterns in an Address criteria may additionally contain addresses to match in CIDR addressmasklen format, e. g. 192.0.2.024 or 3ffe:ffff::32. Note that the mask length provided must be consistent with the address - it is an error to specify a mask length that is too long for the address or one with bits set in this host portion of the address. For example, 192.0.2.033 and 192.0.2.08 respectively. Only a subset of keywords may be used on the lines following a Match keyword. Available keywords are AllowAgentForwarding . AllowTcpForwarding . Banner . ChrootDirectory . ForceCommand . GatewayPorts . GSSAPIAuthentication . HostbasedAuthentication . KbdInteractiveAuthentication . KerberosAuthentication . KerberosUseKuserok . MaxAuthTries . MaxSessions . PubkeyAuthentication . AuthorizedKeysCommand . AuthorizedKeysCommandRunAs . PasswordAuthentication . PermitEmptyPasswords . PermitOpen . PermitRootLogin . RequiredAuthentications1, RequiredAuthentications2, RhostsRSAAuthentication . RSAAuthentication . X11DisplayOffset . X11Forwarding and X11UseLocalHost . MaxAuthTries Specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. The default is 6. MaxSessions Specifies the maximum number of open sessions permitted per network connection. The default is 10. MaxStartups Specifies the maximum number of concurrent unauthenticated connections to the SSH daemon. Additional connections will be dropped until authentication succeeds or the LoginGraceTime expires for a connection. The default is 10. Alternatively, random early drop can be enabled by specifying the three colon separated values start:rate:full (e. g. 10:30:60). sshd (8) will refuse connection attempts with a probability of rate100 (30) if there are currently start (10) unauthenticated connections. The probability increases linearly and all connection attempts are refused if the number of unauthenticated connections reaches full (60). PasswordAuthentication Specifies whether password authentication is allowed. The default is yes. PermitEmptyPasswords When password authentication is allowed, it specifies whether the server allows login to accounts with empty password strings. The default is no. PermitOpen Specifies the destinations to which TCP port forwarding is permitted. The forwarding specification must be one of the following forms: Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. By default all port forwarding requests are permitted. PermitRootLogin Specifies whether root can log in using ssh (1). The argument must be yes, without-password, forced-commands-only, or no. The default is yes. If this option is set to without-password, password authentication is disabled for root. If this option is set to forced-commands-only, root login with public key authentication will be allowed, but only if the command option has been specified (which may be useful for taking remote backups even if root login is normally not allowed). All other authentication methods are disabled for root. If this option is set to no, root is not allowed to log in. PermitTunnel Specifies whether tun (4) device forwarding is allowed. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no. Specifying yes permits both point-to-point and ethernet. The default is no. PermitUserEnvironment Specifies whether. sshenvironment and environment options in. sshauthorizedkeys are processed by sshd (8). The default is no. Enabling environment processing may enable users to bypass access restrictions in some configurations using mechanisms such as LDPRELOAD. PidFile Specifies the file that contains the process ID of the SSH daemon. The default is varrunsshd. pid . Port Specifies the port number that sshd (8) listens on. The default is 22. Multiple options of this type are permitted. See also ListenAddress . PrintLastLog Specifies whether sshd (8) should print the date and time of the last user login when a user logs in interactively. The default is yes. PrintMotd Specifies whether sshd (8) should print etcmotd when a user logs in interactively. (On some systems it is also printed by the shell, etcprofile . or equivalent.) The default is yes. Protocol Specifies the protocol versions sshd (8) supports. The possible values are 1 and 2. Multiple versions must be comma-separated. The default is 2,1. Note that the order of the protocol list does not indicate preference, because the client selects among multiple protocol versions offered by the server. Specifying 2,1 is identical to 1,2. PubkeyAuthentication Specifies whether public key authentication is allowed. The default is yes. Note that this option applies to protocol version 2 only. AuthorizedKeysCommand Specifies a program to be used for lookup of the users public keys. The program will be invoked with its first argument the name of the user being authorized, and should produce on standard output AuthorizedKeys lines (see AUTHORIZEDKEYS in sshd (8)). By default (or when set to the empty string) there is no AuthorizedKeysCommand run. If the AuthorizedKeysCommand does not successfully authorize the user, authorization falls through to the AuthorizedKeysFile. Note that this option has an effect only with PubkeyAuthentication turned on. AuthorizedKeysCommandRunAs Specifies the user under whose account the AuthorizedKeysCommand is run. Empty string (the default value) means the user being authorized is used. RequiredAuthentications12 Specifies required methods of authentications that has to succeed before authorizing the connection. (RequiredAuthentication1 for Protocol version 1, and RequiredAuthentication2 for v2) RequiredAuthentications1 method, method. RequiredAuthentications2 method, method. Example 1: Example 2: Available methods: Specifies whether rhosts or etchosts. equiv authentication together with successful RSA host authentication is allowed. The default is no. This option applies to protocol version 1 only. RSAAuthentication Specifies whether pure RSA authentication is allowed. The default is yes. This option applies to protocol version 1 only. ServerKeyBits Defines the number of bits in the ephemeral protocol version 1 server key. The minimum value is 512, and the default is 1024. ShowPatchLevel Specifies whether sshd will display the patch level of the binary in the identification string. The patch level is set at compile-time. The default is no. This option applies to protocol version 1 only. StrictModes Specifies whether sshd (8) should check file modes and ownership of the users files and home directory before accepting login. This is normally desirable because novices sometimes accidentally leave their directory or files world-writable. The default is yes. Subsystem Configures an external subsystem (e. g. file transfer daemon). Arguments should be a subsystem name and a command (with optional arguments) to execute upon subsystem request. The command sftp-server (8) implements the sftp file transfer subsystem. Alternately the name internal-sftp implements an in-process sftp server. This may simplify configurations using ChrootDirectory to force a different filesystem root on clients. By default no subsystems are defined. Note that this option applies to protocol version 2 only. SyslogFacility Gives the facility code that is used when logging messages from sshd (8). The possible values are: DAEMON, USER, AUTH, AUTHPRIV, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is AUTH. TCPKeepAlive Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. On the other hand, if TCP keepalives are not sent, sessions may hang indefinitely on the server, leaving ghost users and consuming server resources. The default is yes (to send TCP keepalive messages), and the server will notice if the network goes down or the client host crashes. This avoids infinitely hanging sessions. To disable TCP keepalive messages, the value should be set to no. UseDNS Specifies whether sshd (8) should look up the remote host name and check that the resolved host name for the remote IP address maps back to the very same IP address. The default is yes. UseLogin Specifies whether login (1) is used for interactive login sessions. The default is no. Note that login (1) is never used for remote command execution. Note also, that if this is enabled, X11Forwarding will be disabled because login (1) does not know how to handle xauth (1) cookies. If UsePrivilegeSeparation is specified, it will be disabled after authentication. UsePAM Enables the Pluggable Authentication Module interface. If set to yes this will enable PAM authentication using ChallengeResponseAuthentication and PasswordAuthentication in addition to PAM account and session module processing for all authentication types. Because PAM challenge-response authentication usually serves an equivalent role to password authentication, you should disable either PasswordAuthentication or ChallengeResponseAuthentication. If UsePAM is enabled, you will not be able to run sshd (8) as a non-root user. The default is no. UsePrivilegeSeparation Specifies whether sshd (8) separates privileges by creating an unprivileged child process to deal with incoming network traffic. After successful authentication, another process will be created that has the privilege of the authenticated user. The goal of privilege separation is to prevent privilege escalation by containing any corruption within the unprivileged processes. The default is yes. X11DisplayOffset Specifies the first display number available for sshd (8)s X11 forwarding. This prevents sshd from interfering with real X11 servers. The default is 10. X11Forwarding Specifies whether X11 forwarding is permitted. The argument must be yes or no. The default is no. When X11 forwarding is enabled, there may be additional exposure to the server and to client displays if the sshd (8) proxy display is configured to listen on the wildcard address (see X11UseLocalhost below), though this is not the default. Additionally, the authentication spoofing and authentication data verification and substitution occur on the client side. The security risk of using X11 forwarding is that the clients X11 display server may be exposed to attack when the SSH client requests forwarding (see the warnings for ForwardX11 in sshconfig (5)). A system administrator may have a stance in which they want to protect clients that may expose themselves to attack by unwittingly requesting X11 forwarding, which can warrant a no setting. Note that disabling X11 forwarding does not prevent users from forwarding X11 traffic, as users can always install their own forwarders. X11 forwarding is automatically disabled if UseLogin is enabled. X11UseLocalhost Specifies whether sshd (8) should bind the X11 forwarding server to the loopback address or to the wildcard address. By default, sshd binds the forwarding server to the loopback address and sets the hostname part of the DISPLAY environment variable to localhost. This prevents remote hosts from connecting to the proxy display. However, some older X11 clients may not function with this configuration. X11UseLocalhost may be set to no to specify that the forwarding server should be bound to the wildcard address. The argument must be yes or no. The default is yes. XAuthLocation Specifies the full pathname of the xauth (1) program. The default is usrbinxauth . Time Formats sshd (8) command-line arguments and configuration file options that specify time may be expressed using a sequence of the form: time qualifier , where time is a positive integer value and qualifier is one of the following: seconds s S seconds m M minutes h H hours d D days w W weeks Each member of the sequence is added together to calculate the total time value. Time format examples: 600 600 seconds (10 minutes) 10m 10 minutes 1h30m 1 hour 30 minutes (90 minutes) Contains configuration data for sshd (8). This file should be writable by root only, but it is recommended (though not necessary) that it be world-readable. OpenSSH is a derivative of the original and free ssh 1.2.12 release by Tatu Ylonen. Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos, Theo de Raadt and Dug Song removed many bugs, re-added newer features and created OpenSSH. Markus Friedl contributed the support for SSH protocol versions 1.5 and 2.0. Niels Provos and Markus Friedl contributed support for privilege separation. BSD April 14, 2013 BSD Referenced By
Comments
Post a Comment