Mostrando postagens com marcador Linux. Mostrar todas as postagens
Mostrando postagens com marcador Linux. Mostrar todas as postagens

Controle de acesso SSH com hosts.deny e hosts.allow

 

Faça login na sua máquina Linux e abra uma janela de terminal. Primeiro, vamos negar todo o acesso ao daemon SSH. Abra o arquivo hosts.deny com o comando 

sudo nano /etc/hosts.deny

No final desse arquivo, adicione:

sshd: ALL

Salve e feche o arquivo.

Em seguida, abra o arquivo hosts.allow com o comando

sudo nano /etc/hosts.allow

 Digamos que você queira permitir acesso SSH apenas para duas máquinas em sua rede, nos endereços IP 192.168.1.62 e 192.168.1.152. Para isso, adicione a linha:

sshd: 192.168.1.62, 192.168.1.152

Salve e feche o arquivo.

Nesse ponto, apenas essas duas máquinas têm permissão para acessar seu computador ou servidor via SSH. Lembre-se de que o arquivo hosts.deny é lido antes do hosts.allow, portanto, definir sshd: ALL em hosts.deny só é anulado se houver uma entrada em hosts.allow. 

Remove computer from Azure Arc

  

To fully remove a computer from Azure Arc-enabled servers, follow the official steps in the Uninstall the Azure Connected Machine agent guide to clear extensions, disconnect the agent, and remove the local software.

1. Remove VM Extensions

  • Open the Azure portal.

  • Go to Azure Arc and select Machines.

  • Click your target server, go to Extensions, select any installed extensions, and click Uninstall.

2. Disconnect the Agent from the Server

  • Open an administrative command prompt on the physical or virtual machine.

  • Run the following command to disconnect the agent and delete the Azure resource representation:

    bash

    azcmagent disconnect

  • Sign in with your Azure account when prompted.
    (Note: If the Azure resource was already deleted manually in the portal, run
    azcmagent disconnect --force-local-only instead).

3. Uninstall the Agent Software

  • Windows: Open Control Panel > Programs and Features, select Azure Connected Machine Agent, and click Uninstall.

  • Linux: Use your package manager (e.g.,

  • sudo apt purge azcmagent or sudo yum remove azcmagent).

  • Manually delete leftover configuration folders if needed, such as C:\Program Files\AzureConnectedMachineAgent on Windows.


Apt only upgrade selected packages

 apt list --upgradable | cut -d"/" -f1 > /tmp/apt

pico /tmp/apt

cat /tmp/apt | tr "\n" " "

apt install --only-upgrade <list_of_packages>

Checking Root Account Status

 

Checking Local Root Account Status
  • Run sudo passwd -S root: Look for the status letter in the output. An L means the account is locked (disabled), while a P means it has a usable password.
  • Check /etc/shadow directly: Run sudo getent shadow root or sudo grep root /etc/shadow. If the second field (the password hash field) starts with an ! or *, the password is locked and direct login is disabled. [1, 2]
Checking Remote SSH Root Login Status
  • Test the effective SSH setting: Run sudo sshd -T | grep permitrootlogin. If it outputs permitrootlogin no or prohibit-password, remote root access via password is disabled.
  • Inspect the configuration files: Check /etc/ssh/sshd_config and files inside /etc/ssh/sshd_config.d/ for PermitRootLogin no

Command ip examples

 
# Forcefully close a connection to a specific destination
sudo ss -K dst 192.168.1.100

# view routes
ip r
ip route

# To reject a route (block traffic to an IP)
ip route add unreachable 74.1.1.0/24
ip route del unreachable 74.1.1.0/24

  
# add route 
sudo ip route add {NETWORK/MASK} via {GATEWAYIP}
sudo ip route add {NETWORK/MASK} dev {DEVICE}
sudo ip route add default {NETWORK/MASK} dev {DEVICE}
sudo ip route add default {NETWORK/MASK} via {GATEWAYIP}

# Here is another example where I am setting up route for my VPN gateway:
ip link set dev tun0 up mtu 1500
ip addr add dev tun0 10.8.0.2/24 broadcast 10.8.0.255
ip route add 139.59.2.125/32 via 192.168.2.254
ip route add 0.0.0.0/1 via 10.8.0.1
ip route add 128.0.0.0/1 via 10.8.0.1


Edit config file such as /etc/sysconfig/network-scripts/route-eth0 on a CentOS/RHEL/Fedora Linux for interface eth0 using a text editor such as nano command or vim command:
vim /etc/sysconfig/network-scripts/route-eth0

Append the following text:
172.10.1.0/24 via 10.0.0.100 dev eth0

Save and exit (close) the file in a vim text editor. Finally, restart your network service on a CentOS/RHEL/Fedora Linux so they take effect:
systemctl restart network.service



A note about ip command and persistence static routing on a Debian/Ubuntu

Edit your /etc/network/interfaces file for say eth0:
vi /etc/network/interfaces

Update it as follows:

auto eth0
iface eth0 inet static
address 192.168.1.2
netmask 255.255.255.0
gateway 192.168.1.254
## static ip config START ##
up /sbin/ip route add 172.10.1.0/24 via 10.8.0.1 dev eth0
down /sbin/ip route delete 172.10.1.0/24 via 10.8.0.1 dev eth0
## static ip config END ##


## How to find the route used for an destination IP

The syntax is as follows:
ip route get to {IPv4_address_here}
ip route get to {IPv6_address_here}
ip route get to 172.66.43.74

Outputs indicating that 172.66.43.74 can be reached via the wg0 interface with 192.168.13.4 as source IP:

172.66.43.74 dev wg0 table 51832 src 192.168.13.4 uid 1000 
    cache 

Schedule a Linux reboot

 

Schedule a Linux reboot using shutdown -r <time>  

for one-time events, or crontab -e for recurring reboots. 

Common methods include sudo shutdown -r +60 (in 60 mins),  

sudo shutdown -r 02:00 (at 2 AM), 

 Use "shutdown -c" to cancel reboot 

or adding 0 3 * * * /sbin/shutdown -r now to crontab for daily 3 AM reboots


Export netflow from linux server

 
https://github.com/irino/softflowd

pico /etc/systemd/system/softflowd.service

[Unit]
Description=Softflowd exporter
After=network.target


[Service]
ExecStart=softflowd -i ens160 -v 9 -s 1 -t maxlife=1 -t general=15 -d -n 10.25.10.59:9996
Restart=always
User=root
Group=root

[Install]
WantedBy=default.target



Fix netplan gateway4 deprecated

 

example:                  

network:
  version: 2
  ethernets:
    ens192:
      dhcp4: false
      dhcp6: false
      addresses:
        - 10.20.0.16/23
      nameservers:
        addresses:
        - 10.20.0.11
        search:
        - mpro.gov
      routes:
        - to: default
          via: 10.20.0.250
        - to: 10.0.0.0/8
          via: 10.20.0.254
        - to: 172.16.0.0/12
          via: 10.20.0.254


Fix permissions:
chmod 600 /etc/netplan/*.yaml 

 

 

Criando partição com parted

 

parted  /dev/sdb

(parted) select /dev/sdb

(parted) print

 CRIANDO UMA PARTIÇÃO NO DISCO SELECIONADO (/dev/sdb)

Passo 1: Primeiramente, vamos criar um label (tabela de partições) do tipo desejado no disco. Como exemplo usaremos gpt.

 (parted) mklabel gpt

 Passo 2: Criaremos a partição com o comando “mkpart”.

 (parted) mkpart primary ext4 0% -1

 Primary -> aqui definimos o tipo de partição, podendo ser primária, estendida ou uma unidade lógica.

Ext4 -> definimos o tipo de sistema de arquivos a usar. Podemos escolher entre fat16, fat32, ext2, ext3, HFS, linux- swap, NTFS, reiserfs ou ufs.

0% -> local onde a partição inicia no disco.

-1 -> local onde a partição terminará.

A partição ainda não foi formatada. Especificar a opção ext4 para o sistema de arquivos apenas configura o ID correto para o sistema de arquivos que será utilizado.

De forma a finalizar a partição, necessitamos sair do parted com o comando “quit”, e então formatar a partição com o utilitário mkfs.ext4

(parted) quit

# mkfs.ext4 /dev/sdb1

 Adicionar o ponto de montagem em /etc/fstab

 

Increase linux disk size without reboot

First, increase disk size on vmware, then run:

echo 1 > /sys/class/block/sdc/device/rescan

growpart /dev/sdc 1

resize2fs /dev/sdc1

RKHunter - rootkit scan on ubuntu

 

To install the Rkhunter tool using the package manager on the Ubuntu system, run the following command.

sudo apt-get install rkhunter

After installation, you need to update the file properties database. To update the file properties database, run the following command.

sudo rkhunter –propupd

This above command lets the Rkhunter scanner to know the current state of individual files to avoid any false alarms during the scanning. After updating the file properties, run the following command to start the scanning.

sudo rkhunter –checkall

This scanner runs through some system commands, network settings, localhost settings, and files to check for actual rootkits and malware. Then, it records the findings to a log file. You can get the condensed look at the scan log using the below command. After checking the logs, you can implement a different process to improve your server security.

sudo cat /var/log/rkhunter.log | grep -i warning

If you want to scan Ubuntu Server every day at a particular time (suppose 4 am night) and send the report to your email address, add the following cron entry.

0 4 * * * /usr/sbin/rkhunter -c 2>&1 | mail -s “Rkhunter Report of the Server” you@domain.com

This above cron job runs at 4 am night every day and sends a report to your email address with the subject “Rkhunter Report of the Server”.

Shutdown Windows machine from linux terminal

 

There may be more setup to do, especially for Windows Vista, Windows 7 and further windows versions, to allow remote shutdown:

Part A) On the Windows machine:

1) Add a remote shutdown security policy:

  • run secpol.msc

  • in the program tree, open Security Settings > Local Policies > User rights Assignment

  • Find the entry Force shutdown from a remote system

  • Edit the entry, add the windows user account that will be used for shutdown (ex: nouknouk)

2) Add registry keys to disable UAC remote restrictions:

  • Run regedit.exe as Administrator

  • Find HKLM/SOFTWARE/Microsoft/Windows/CurrentVersion/Policies/System

  • Create a new registry DWORD(32) value named LocalAccountTokenFilterPolicy and then assign it the value 1

3) Start remote registry service:

  • Open cmd.exeas Administrator

  • Execute the two following commands:

    sc config RemoteRegistry start= auto

    sc start RemoteRegistry

Part B) On the Linux machine:

1) install the package samba-common:

It depends on your Linux distribution, but for Debian and derivated (Ubuntu, Linux Mint, ...), the apt-get command can be executed like that:

apt-get install samba-common

2) To actually shutdown your Windows machine from the Linux one, run the following command:

net rpc shutdown -f -t 0 -C 'message' -U userName%password -I xxx.yyy.zzz.ttt

Where:

  • -f means force shutting down all applications (may be mandatory)

  • -t 0 is the delay before doing it (0 means 'right now').

  • -U user%password is the local user and his password on the windows machine (the one that has been allowed to do remote shutdown in part A).

  • -I is the IP address of the windows machine to shutdown.

     

     

WSL install without Windows Store

 

wsl --install --web-download

wsl --update --web-download

wsl --install -d ubuntu --web-download

--web-download: Download the update from the internet instead of the Microsoft Store.



Vmware Linux Guest Add a New Hard Disk Without Rebooting

List SCSI hosts
ls /sys/class/scsi_host

Update info
echo "- - -" > /sys/class/scsi_host/host#/scan

Update all

echo "- - -" | tee /sys/class/scsi_host/host*/scan


Now, you can create partition using fdisk and format it using mkfs.ext3 command:
cfdisk /dev/sdc

### [if you want ext4 fs] ###
mkfs.ext4 /dev/sdc3

Create a Mount Point And Update /etc/fstab

First, type the following mkdir command to make a dir/folder to mount the disk:
mkdir /disk3

Open the /etc/fstab file, enter:
vi /etc/fstab
/dev/sdc3               /disk3           ext4    defaults  



How Do I Delete a Single Device Called /dev/sdc?

In addition to re-scanning the entire bus, a specific device can be added or existing device deleted using the following command:
echo 1 > /sys/block/devName/device/delete
echo 1 > /sys/block/sdc/device/delete

 

source: https://www.cyberciti.biz/tips/vmware-add-a-new-hard-disk-without-rebooting-guest.html

Fixing -bash: /dev/null: Permission denied

 This should fix the issue (as root):

rm /dev/null
mknod /dev/null c 1 3
chmod 666 /dev/null


What these commands are doing:

rm is removing the bogus file that has been created because the expected one was missing;
mknod is creating a character device named /dev/null with the appropriate major and minor numbers for a Linux kernel;
chmod is setting the permissions for all users to be able to read and write to /dev/null.

Harden bash_history and bash configuration files

 

Harden bash_history and bash configuration files by making them append-only:

chattr +a /home/user/.bash_history
chattr +a /home/user/.bash_profile
chattr +a /home/user/.bash_login
chattr +a /home/user/.profile
chattr +a /home/user/.bash_logout
chattr +a /home/user/.bashrc

Harden env variables by adding the following lines to /home/user/.bashrc:

shopt -s histappend
readonly PROMPT_COMMAND="history -a"
readonly HISTFILE
readonly HISTFILESIZE
readonly HISTSIZE
readonly HISTCMD
readonly HISTCONTROL
readonly HISTIGNORE

histappend tells bash to append the last $HISTSIZE lines to the $HISTFILE file when an interactive shell exits. PROMPT_COMMAND executes the given command prior to issuing each prompt. history -a appends the command typed just before the current one to $HISTFILE.

Disable access to other shells:

chmod 750 csh
chmod 750 tcsh
chmod 750 ksh

 

 

Clean /var/log/journal

 

$ du -hs /var/log/journal/
4.1G    /var/log/journal/

4,1 GB de arquivos de diários, com o mais antigo datando de mais de dois meses.

$ ls -lath /var/log/journal/*/ | tail -n 2
-rw-r-x---+ 1 root systemd-journal 8.0M Dec 24 05:15 user-xxx.journal

Limpe systemd journals de mais de X dias

A primeira é baseada no tempo, limpando todo o suporte de há mais de, digamos, 10 dias.

$ journalctl --vacuum-time=10d

Vacuuming done, freed 2.3G of archived journals on disk.

Alternativamente, você pode limitar seu tamanho total.
Limpe systemd journals se eles excederem X de armazenamento

Este exemplo manterá 2GB de logs, limpando tudo o que excede isso.

$ journalctl --vacuum-size=2G

Vacuuming done, freed 720.0M of archived journals on disk.

 

 

Limit SSH access by user and network

 Add user filtering with AllowUsers option in sshd_config file:

AllowUsers johndoe@192.168.1.* admin2@192.168.1.* otherid1 otherid2

This allows johndoe and admin2 only from 192.168.1.* addresses and otherid1, otherid2 from anywhere.

 

 

Run local script on remote host via SSH

 

ssh root@<remoteServer> "bash -s" < /opt/script.sh
Run in multiple hosts: 
for i in `cat hosts.txt` ; do echo $i && ssh root@$i "bash -s" < script.sh ; done 

Source: https://unix.stackexchange.com/questions/87405/how-can-i-execute-local-script-on-remote-machine-and-include-arguments

Automatically keep current version of config files when apt-get install

 

apt install -o Dpkg::Options::="--force-confold" --only-upgrade <package> 


Remote:


ssh <user>@<ip_address> 'apt install -o Dpkg::Options::="--force-confold" --only-upgrade <package>'


Corrigir erro NATS no Segura

  ### erro Nats orbit nats stop orbit nats setup orbit services reload orbit services restart all ls -lh /var/orbini/system/incdt/ 

Mais vistos