quarta-feira, 20 de março de 2024

Como baixar pacotes DEB com dependências localmente

0 comentários

 Fonte: https://www.edivaldobrito.com.br/como-baixar-pacotes-com-dependencias-localmente-no-debian-ubuntu-e-derivados/


Se você precisar dos pacotes de instalação de um programa, mas não quer instalar ele, veja como baixar pacotes deb com dependências localmente no Debian, Ubuntu e derivados.

Neste tutorial, você verá como baixar um pacote .DEB, juntamente com todas as dependências necessárias, sem realmente instalá-lo.

Como baixar pacotes deb com dependências localmente no Debian, Ubuntu e derivados
Como baixar pacotes deb com dependências localmente no Debian, Ubuntu e derivados

Usando este método, podemos baixar pacotes de um sistema e instalá-los mais tarde no mesmo sistema ou em qualquer outro, que não tenha conexão com a Internet.

Também é possível fazer o download de pacotes para diferentes sistemas de arquitetura. Por exemplo, você pode baixar os pacotes de 32 bits a partir de um sistema de 64 bits e vice-versa.

Para saber mais sobre esse programa, acesse essa página.

Como baixar pacotes deb com dependências localmente no Debian, Ubuntu e derivados

Para baixar localmente pacotes com dependências no Debian, Ubuntu e derivados, você pode um dos métodos abaixo.

Como baixar pacotes com dependências localmente no Debian, Ubuntu e derivados – Método 1

Este é o método mais simples e direto. Execute o comando abaixo para baixar um pacote com todas as dependências sem instalá-las (substitua ‘nomepacote’ pelo nome do pacote):

sudo apt-get install --download-only nomepacote

Todos os arquivos baixados serão salvos na pasta /var/cache/apt/archives. Basta copiar toda a pasta de cache em qualquer pendrive ou transferi-los via rede para qualquer sistema onde você deseja instalar os pacotes.

Para instalar os pacotes baixados, vá para a pasta de cache e instale-os, usando o comando abaixo:

sudo dpkg -i *

Como baixar pacotes com dependências localmente no Debian, Ubuntu e derivados – Método 2

Nesse método, primeiramente você baixa as dependências do programa que precisa. Para exibir a lista de todas as dependências de um pacote, por exemplo, Python, execute:

sudo apt-cache depends python

A saída será mais ou menos assim:

python
PreDepends: python-minimal
Depends: python2.7
Depends: libpython-stdlib
Conflicts: 
Breaks: update-manager-core
Suggests: python-doc
Suggests: python-tk
Replaces: python-dev

Agora, você deve fazer o download do pacote python com suas dependências para o disco local. Para fazer isso, primeiro crie uma pasta para salvar os pacotes.

mkdir python

Depois, acesse a pasta criada:

cd python

E então execute o seguinte comando:

for i in $(apt-cache depends python | grep -E 'Depends|Recommends|Suggests' | cut -d ':' -f 2,3 | sed -e s/''/''/); do sudo apt-get download $i 2>>errors.txt; done

O comando acima irá baixar o pacote Python juntamente com todas as dependências necessárias e salvá-los no diretório de trabalho atual. Este comando também salvará quaisquer erros no arquivo errors.txt.

Você pode notar que o comando acima baixou os pacotes de 64 bits. É porque estou baixando-os do sistema Ubuntu de 64 bits. E se você quiser baixar pacotes para sistemas de arco de 32 bits? Também é possível.

Primeiro, habilite a arquitetura que deseja no seu sistema Ubuntu usando o comando:

sudo dpkg --add-architecture i386*

Após habilitar a arquitetura de sua escolha, execute o seguinte comando para baixar pacotes relacionados à arquitetura específica.

for i in $(apt-cache depends python:i386 | grep -E 'Depends|Recommends|Suggests' | cut -d ':' -f 2,3 | sed -e s/''/''/); do sudo apt-get download $i 2>>errors.txt; done

Se quiser listar os arquivos baixados use o comando ‘ls’ e saída será algo assim:

cd pythonerrors.txt
libpython-stdlib_2.7.11-1_amd64.deb
python2.7_2.7.11-7ubuntu1_amd64.deb
python-doc_2.7.11-1_all.deb
python-minimal_2.7.11-1_amd64.deb
python-tk_2.7.11-2_amd64.debcode>

Como é possível ver na saída acima, o pacote python foi baixado, junto com todas as suas dependências.

Agora, basta copiá-los para sua unidade USB e instalar os pacotes python em qualquer sistema off-line.

Ou seja, apenas monte a unidade USB, vá para o local onde você montou a unidade e execute o seguinte comando para instalar o Python.

sudo dpkg -i *

Agora que você já sabe como fazer o download de pacotes com dependências localmente nos sistemas Debian, Ubuntu, Linux Mint e outros derivados, fique a vontade para baixar e instalar onde quiser, e quando quiser. E viva a liberdade!

Continue reading →
terça-feira, 23 de janeiro de 2024

Exportando automaticamente unidades USB pelo Samba

0 comentários

 Fonte: Exportando automaticamente unidades USB pelo Samba | davidc.net


Para o meu novo NAS, eu queria que os discos USB recém-conectados fossem montados automaticamente e, em seguida, exportados pelo Samba. O programa usbmount do Debian é usado para lidar com a montagem, e alguns scripts lidam com a exportação do Samba.

USBMauricular

O Debian tem o pacote usbmount disponível, um programa prático que roda independente de qualquer GUI. udev chama-o quando um disco USB é inserido, e usbmount monta o disco automaticamente. Ele também executa quaisquer scripts em /etc/usbmount/mount.d usando run-parts (e o equivalente /etc/usbmount/umount.d após a desconexão). Isso permite que um script personalizado seja inserido para manipular a exportação do Samba.

usbmount por padrão será montado nos diretórios /media/usb0 até /media/usb7.

smb.conf

Eu não queria editar o smb.conf diretamente. O Samba tem uma diretiva de inclusão - não permite que você inclua um diretório, mas ignora silenciosamente todos os arquivos de inclusão que não existem.

Crie o diretório vazio /etc/samba/auto e adicione as seguintes linhas à parte inferior do smb.conf:

include = /etc/samba/auto/usb0.conf
include = /etc/samba/auto/usb1.conf
include = /etc/samba/auto/usb2.conf
include = /etc/samba/auto/usb3.conf
include = /etc/samba/auto/usb4.conf
include = /etc/samba/auto/usb5.conf
include = /etc/samba/auto/usb6.conf
include = /etc/samba/auto/usb7.conf

mount.d

Em seguida, um script para criar automaticamente os arquivos de configuração acima quando uma unidade é inserida. Crie o arquivo /etc/usbmount/mount.d/50_add_samba_export com o seguinte conteúdo e chmod executável.

#!/bin/bash
SHARENAME=`basename $UM_MOUNTPOINT`
cat > /etc/samba/auto/$SHARENAME.conf <<EOF
[$SHARENAME]
   comment = $UM_VENDOR $UM_MODEL
   path = $UM_MOUNTPOINT
   read only = no
EOF
 
/etc/init.d/samba restart

Obviamente, você pode colocar qualquer coisa que quiser no fragmento do arquivo de configuração para configurar o compartilhamento da maneira que desejar.

Note que eu forço um reinício do Samba, em vez de um reload. Isso depende de você - uma recarga não interromperá as conexões existentes, mas significará que os usuários terão que se desconectar e se reconectar para ver o novo compartilhamento. Uma reinicialização interromperá brevemente as conexões, mas permitirá que elas vejam o novo compartilhamento imediatamente. Escolha o que funciona melhor para você.

umount.d

Crie um script semelhante para remover o compartilhamento quando o disco for desmontado ou removido. Isso vai em /etc/usbmount/umount.d/50_remove_samba_export - novamente, lembre-se de chmod ele +x.

#!/bin/bash
SHARENAME=`basename $UM_MOUNTPOINT`
rm -f /etc/samba/auto/$SHARENAME.conf
 
/etc/init.d/samba restart

Novamente, escolha se deseja recarregar ou reiniciar.

Arrumação final

Se a máquina for reinicializada sem desmontar corretamente, os compartilhamentos aparecerão novamente, mesmo que a unidade não esteja mais conectada. Para lidar com essa eventualidade, crie um script de inicialização para limpar o /etc/samba/auto.

Como o Debian gentilmente removeu o recurso rc.boot do administrador local, você tem que fazer isso da maneira complicada usando um script init, digamos /etc/init.d/auto-share-clean

#! /bin/sh
### BEGIN INIT INFO
# Provides:          auto-share-clean
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Cleans auto samba shares
### END INIT INFO
 
rm -f /etc/samba/auto/*

Em seguida, chmod +x /etc/init.d/auto-share-clean e update-rc.d auto-share-clean padrões.

Outros trabalhos

Provavelmente há algo inteligente que pode ser feito aqui com o UUID e a nomenclatura persistente - ou seja, exportar o compartilhamento com um nome que seja persistente em reinicializações/reconexões. Por exemplo, com duas unidades USB conectadas, qual unidade é montada primeiro pode variar, o que não é ótimo para nomes de caminho de rede persistentes.

Continue reading →
sexta-feira, 12 de janeiro de 2024

Raspberrypi set static ip with network-manager

0 comentários

 Fonte: static-ip | wiki.pcw.de


#!/bin/bash

nmcli c mod "Wired connection 1" ipv4.addresses 192.168.31.16/24 ipv4.method manual

nmcli con mod "Wired connection 1" ipv4.gateway 192.168.31.1

nmcli con mod "Wired connection 1" ipv4.dns "192.168.31.16,192.168.31.17"

nmcli c down "Wired connection 1" && nmcli c up "Wired connection 1"

Continue reading →
terça-feira, 12 de setembro de 2023

OpenVPN: configure 2FA with Google Authenticator

0 comentários

 Fonte: https://binsec.wiki/en/security/howto/protect-hardening/authorization-and-authentication/openvpn-configure-2fa-google-authenticator/


This article explains how to configure 2FA (two factor authentication) for OpenVPN via the google authenticator PAM plugin. The configuration example below is done on a Debian bullseye Server. If you do this on a remote connection, you should have backup access to the server if something goes wrong during configuration.

Install libpam-google-authenticator on the server

After installing and configuring openvpn in general, install the package libpam-google-authenticator:

sudo apt install libpam-google-authenticator

Create a OpenVPN specific PAM configuration:

cat /etc/pam.d/openvpn < EOF
@include common-account
auth required pam_google_authenticator.so
EOF

This configuration will enable the google authenticator PAM module for the OpenVPN daemon.

In the OpenVPN configuration the following line has to be added:

plugin /usr/lib/x86_64-linux-gnu/openvpn/plugins/openvpn-plugin-auth-pam.so openvpn

Configure google-authenticator for a user

To enable the google authenticator for the VPN user, the user has to run google-authenticator on the server. The following questions during configuration setup should be answered according to your needs.

google-authenticator

Do you want authentication tokens to be time-based (y/n) y

<QRCODE>

Your new secret key is: <secret>
Your verification code is: <number>
Your emergency scratch codes are:
  <number>
  ....
Do you want me to update your "/home/user/.google_authenticator" file? (y/n) y

Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y

y default, a new token is generated every 30 seconds by the mobile app.
In order to compensate for possible time-skew between the client and the server,
we allow an extra token before and after the current time. This allows for a
time skew of up to 30 seconds between authentication server and client. If you
experience problems with poor time synchronization, you can increase the window
from its default size of 3 permitted codes (one previous code, the current
code, the next code) to 17 permitted codes (the 8 previous codes, the current
code, and the 8 next codes). This will permit for a time skew of up to 4 minutes
between client and server.
Do you want to do so? (y/n) y

If the computer that you are logging into isn't hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every 30s.
Do you want to enable rate-limiting? (y/n) y

Connect google authenticator on your smartphone

The QR-Code can now be scanned by a mobile app like Google Authenticator or similar applications on your smart phone. If a YubiKey is available, the Yubico Authenticator could also be used.

The emergency codes should be stored on a safe place e.g. a password manager like pass. They could be used to access the VPN if the access to the 2FA device get's lost.

Updating openvpn client config for google authenticator

In the openvpn client configuration, the following line has to be added:

auth-user-pass

With this line, the openvpn client will ask for a additional password before the connection is established. Now you can enter the 6 digit code on your smartphone app.

Continue reading →
terça-feira, 5 de setembro de 2023

How to Install KVM on Ubuntu 22.04 (Jammy Jellyfish)

0 comentários

 Fonte: https://www.linuxtechi.com/how-to-install-kvm-on-ubuntu-22-04/


KVM, an acronym for Kernel-based Virtual Machine is an opensource virtualization technology integrated into the Linux kernel. It’s a type 1 (bare metal ) hypervisor that enables the kernel to act as a bare-metal hypervisor.

KVM allows users to create and run multiple guest machines which can be either Windows or Linux. Each guest machine runs independently of other virtual machines and the underlying OS ( host system ) and has its own computing resources such as CPU, RAM, network interfaces, and storage to mention a few.

This guide shows you how to install KVM on Ubuntu 22.04 LTS (Jammy Jellyfish). At the tail end of this guide, we will demonstrate how you can create a virtual machine once the installation of KVM is complete.

1) Update Ubuntu 22.04

To get off the ground, launch the terminal and update your local package index as follows.

$ sudo apt update

2) Check if Virtualization is enabled

Before you proceed any further, you need to check if your CPU supports KVM virtualization. For this to be possible, your system needs to either have a VT-x( vmx ) Intel processor or an AMD-V (svm) processor.

This is achieved by running the following command. if the output is greater than 0, then virtualization is enabled. Otherwise, virtualization is disabled and you need to enable it.

$ egrep -c '(vmx|svm)' /proc/cpuinfo

SVM-VMX-Flags-Cpuinfo-linux

From the above output, you can deduce that virtualization is enabled since the result printed is greater than 0. If Virtualization is not enabled, be sure to enable the virtualization feature in your system’s BIOS settings.

In addition, you can verify if KVM virtualization is enabled by running the following command:

$ kvm-ok

For this to work, you need to have installed the cpu-checker package, otherwise, you will bump into the error ‘Command ‘kvm-ok’ not found’.

Directly below, you will get instructions on how to resolve this issue, and that is to install the cpu-checker package.

KVM-OK-Command-Not-Found-Ubuntu

Therefore, install the cpu-checker package as follows.

$ sudo apt install -y cpu-checker

Then run the kvm-ok command, and if KVM virtualization is enabled, you should get the following output.

$ kvm-ok

KVM-OK-Command-Output

3) Install KVM on Ubuntu 22.04

Next, run the command below to install KVM and additional virtualization packages on Ubuntu 22.04.

$ sudo apt install -y qemu-kvm virt-manager libvirt-daemon-system virtinst libvirt-clients bridge-utils

Let us break down the packages that we are installing:

  • qemu-kvm  – An opensource emulator and virtualization package that provides hardware emulation.
  • virt-manager – A Qt-based graphical interface for managing virtual machines via the libvirt daemon.
  • libvirt-daemon-system – A package that provides configuration files required to run the libvirt daemon.
  • virtinst – A  set of command-line utilities for provisioning and modifying virtual machines.
  • libvirt-clients – A set of client-side libraries and APIs for managing and controlling virtual machines & hypervisors from the command line.
  • bridge-utils – A set of tools for creating and managing bridge devices.

 4) Enable the virtualization daemon (libvirtd)

With all the packages installed, enable and start the Libvirt daemon.

$ sudo systemctl enable --now libvirtd
$ sudo systemctl start libvirtd

Confirm that the virtualization daemon is running as shown.

$ sudo systemctl status libvirtd

Libvirtd-Status-Ubuntu-Linux

In addition, you need to add the currently logged-in user to the kvm and libvirt groups so that they can create and manage virtual machines.

$ sudo usermod -aG kvm $USER
$ sudo usermod -aG libvirt $USER

The $USER environment variable points to the name of the currently logged-in user.  To apply this change, you need to log out and log back again.

5) Create Network Bridge (br0)

If you are planning to access KVM virtual machines outside from your Ubuntu 22.04 system, then you must map VM’s interface to a network bridge. Though a virtual bridge named virbr0, created automatically when KVM is installed but it is used for testing purposes.

To create a network bridge, create the file ‘01-netcfg.yaml’ with following content under the folder /etc/netplan.

$ sudo vi /etc/netplan/01-netcfg.yaml
network:
  ethernets:
    enp0s3:
      dhcp4: false
      dhcp6: false
  # add configuration for bridge interface
  bridges:
    br0:
      interfaces: [enp0s3]
      dhcp4: false
      addresses: [192.168.1.162/24]
      macaddress: 08:00:27:4b:1d:45
      routes:
        - to: default
          via: 192.168.1.1
          metric: 100
      nameservers:
        addresses: [4.2.2.2]
      parameters:
        stp: false
      dhcp6: false
  version: 2

save and exit the file.

Note: These details as per my setup, so replace the IP address entries, interface name and mac address as per your setup.

To apply above change, run ‘netplan apply

$ sudo netplan apply

Verify the network bridge ‘br0’, run below ip command

$ ip add show

Network-Bridge-br0-ubuntu-linux

6) Launch KVM Virtual Machines Manager

With KVM installed, you can begin creating your virtual machines using the virt-manager GUI tool. To get started, use the GNOME search utility and search for ‘Virtual machine Manager’.

Click on the icon that pops up.

Access-Virtual-Machine-Manager-Ubuntu-Linux

This launches the Virtual Machine Manager Interface.

Virtual-Machine-Manager-Interface-Ubuntu-Linux

Click on “File” then select “New Virtual Machine”. Alternatively, you can click on the button shown.

New-Virtual-Machine-Icon-Virt-Manager

This pops open the virtual machine installation wizard which presents you with the following four options:

  • Local install Media ( ISO image or CDROM )
  • Network Install ( HTTP, HTTPS, and FTP )
  • Import existing disk image
  • Manual Install

In this guide, we have downloaded a Debian 11 ISO image, and therefore, if you have an ISO image, select the first option and click ‘Forward’.

Local-Install-Media-ISO-Virt-Manager

In the next step, click ‘Browse’ to navigate to the location of the ISO image,

Browse-ISO-File-Virt-Manager-Ubuntu-Linux

In the next window, click ‘Browse local’ in order to select the ISO image from the local directories on your Linux PC.

Browse-Local-ISO-Virt-Manager

As demonstrated below, we have selected the Debian 11 ISO image. Then click ‘Open

Choose-ISO-File-Virt-Manager

Once the ISO image is selected, click ‘Forward’ to proceed to the next step.

Forward-after-browsing-iso-file-virt-manager

Next, define the RAM and the number of CPU cores for your virtual machine and click ‘Forward’.

Virtual-Machine-RAM-CPU-Virt-Manager

In the next step, define the disk space for your virtual machine and click ‘Forward’.

Storage-for-Virtual-Machine-KVM-Virt-Manager

To associate virtual machine’s nic to network bridge, click on ‘Network selection’ and choose br0 bridge.

Network-Selection-KVM-Virtual-Machine-Virt-Manager

Finally, click ‘Finish’ to wind up setting the virtual machine.

Choose-Finish-to-OS-Installation-KVM-VM

Shortly afterward, the virtual machine creation will get underway.

Creating-Domain-Virtual-Machine-Virt-Manager

Once completed, the virtual machine will start with the OS installer displayed. Below is the Debian 11 installer listing the options for installation. From here, you can proceed to install your preferred system.

Virtual-Machine-Console-Virt-Manager

Conclusion

And that’s it. In this guide, we have demonstrated how you can install the KVM hypervisor on Ubuntu 22.04. Your feedback on this guide is much welcome.

Continue reading →