Categoria Sem categoria

porplague70

Instalando e habilitando SSH no CentOS 7

Aqui vai um jeito bem fácil e rápido de instalar e habilitar o SSH no CentOS 7.
Para isso, nosso ponto de partida será uma imagem padrão do CentOS 7 e vamos seguir os seguintes passos:

  1. Instalar o SSH
  2. Habilitar as regras de firewall
  3. Testar 🙂

Instalar o SSH

Usando `yum`, basta seguir os seguintes comandos (você vai precisar executar o comando como root):

# yum update -y && yum install -y openssh openssh-server

Para verificar se tudo está funcionando:

$ systemctl status sshd

Se por algum motivo o serviço não foi corretamente configurado durante a instalação, podemos fazê-lo com:

# chkconfig sshd on# service sshd start

Configurações finas sobre o serviço do SSH podem ser encontradas em /etc/ssh/sshd_config.

Habilitar as regras de firewall

Normalmente esse processo de instalação habilita as configurações de ssh no serviço de firewall do CentOS 7 (firewalld)

Para verificar as configurações podemos:

# firewall-cmd --list-service | grep ssh

Se não houver configuração apropriada, podemos:

# firewall-cmd --add-service ssh# firewall-cmd --reload

Testar

Nesse ponto, já temos tudo certo para realizar o primeiro acesso.

Próximos passos

Esse mini tutorial mostra uma instalação simples destinada a ambientes de estudo e testes, sendo desaconselhável para ambientes produtivos.

Para ganhar um pouco de robustez e segurança você pode procurar sobre:

  1. Habilitar acesso SSH através de certificados
  2. Habilitar restrição de IP no firewall
porplague70

How To Use Linux Screen

Introduction

Screen or GNU Screen is a terminal multiplexer. In other words, it means that you can start a screen session and then open any number of windows (virtual terminals) inside that session. Processes running in Screen will continue to run when their window is not visible even if you get disconnected.

Install Linux GNU Screen

The screen package is pre-installed on most Linux distros nowadays. You can check if it is installed on your system by typing:

screen --version
Screen version 4.06.02 (GNU) 23-Oct-17

If you don’t have screen installed on your system, you can easily install it using the package manager of your distro.

Install Linux Screen on Ubuntu and Debian

sudo apt updatesudo apt install screenCopyCopy

Install Linux Screen on CentOS and Fedora

sudo yum install screen

Starting Linux Screen

To start a screen session, simply type screen in your console:

screen

This will open a screen session, create a new window, and start a shell in that window.

Now that you have opened a screen session, you can get a list of commands by typing:

Ctrl+a ?

Starting Named Session

Named sessions are useful when you run multiple screen sessions. To create a named session, run the screen command with the following arguments:

screen -S session_name

It’s always a good idea to choose a descriptive session name.

Working with Linux Screen Windows

When you start a new screen session, it creates a single window with a shell in it.

You can have multiple windows inside a Screen session.

To create a new window with shell type Ctrl+a c, the first available number from the range 0...9 will be assigned to it.

Below are some most common commands for managing Linux Screen Windows:

  • Ctrl+a c Create a new window (with shell)
  • Ctrl+a " List all window
  • Ctrl+a 0 Switch to window 0 (by number )
  • Ctrl+a A Rename the current window
  • Ctrl+a S Split current region horizontally into two regions
  • Ctrl+a | Split current region vertically into two regions
  • Ctrl+a tab Switch the input focus to the next region
  • Ctrl+a Ctrl+a Toggle between the current and previous region
  • Ctrl+a Q Close all regions but the current one
  • Ctrl+a X Close the current region

Detach from Linux Screen Session

You can detach from the screen session at any time by typing:

Ctrl+a d

The program running in the screen session will continue to run after you detach from the session.

Reattach to a Linux Screen

To resume your screen session use the following command:

screen -r

In case you have multiple screen sessions running on your machine, you will need to append the screen session ID after the r switch.

To find the session ID list the current running screen sessions with:

screen -ls
There are screens on:
    10835.pts-0.linuxize-desktop   (Detached)
    10366.pts-0.linuxize-desktop   (Detached)
2 Sockets in /run/screens/S-linuxize.

If you want to restore screen 10835.pts-0, then type the following command:

screen -r 10835

Customize Linux Screen

When screen is started, it reads its configuration parameters from /etc/screenrc and ~/.screenrc if the file is present. We can modify the default Screen settings according to our preferences using the .screenrc file.

Here is a sample ~/.screenrc configuration with customized status line and few additional options:~/.screenrc

# Turn off the welcome message
startup_message off

# Disable visual bell
vbell off

# Set scrollback buffer to 10000
defscrollback 10000

# Customize the status line
hardstatus alwayslastline
hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B} %m-%d %{W}%c %{g}]'

Copy

Gnu Screen Terminal

porplague70

How to Install PostgreSQL on Debian 9

How to Install PostgreSQL on Debian 9

Updated  Feb 13, 2019•

5 min read

Install PostgreSQL on Debian 9

PostgreSQL, often known simply as Postgres, is an open-source general-purpose object-relational database management system. PostgreSQL has many advanced features such as online backups, point in time recovery, nested transactions, SQL and JSON querying, multi-version concurrency control (MVCC), asynchronous replication and more.

In this tutorial, we will show you how to install PostgreSQL on Debian 9 and explore the fundamentals of basic database administration.

Prerequisites

Before proceeding with this tutorial, make sure the user you are logged in as has sudo privileges .

Installing PostgreSQL

At the time of writing this article, the latest version of PostgreSQL available from the Debian repositories is PostgreSQL version 9.6.

To install PostgreSQL on your Debian server complete the following steps:

  1. Begin by updating the local package index:sudo apt updateCopy
  2. Install the PostgreSQL server and PostgreSQL contrib package which provides additional features for the PostgreSQL database:sudo apt install postgresql postgresql-contribCopy
  3. When the installation is completed, the PostgreSQL service will start automatically. To verify the installation we’ll connect to the PostgreSQL database server using the psql utility and print the server version :sudo -u postgres psql -c "SELECT version();"CopyThe output will look like this: version ----------------------------------------------------------------------------------------------------------- PostgreSQL 9.6.10 on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit (1 row)Copy

Psql is an interactive terminal program that allows you to interact with the PostgreSQL server.

PostgreSQL Roles and Authentication Methods

PostgreSQL handles database access permissions using the concept of roles. A role can represent a database user or a group of database users.

PostgreSQL supports a number of authentication methods . The most commonly used methods are:

  • Trust – With this method, the role can connect without a password, as long as the criteria defined in the pg_hba.conf are met.
  • Password – A role can connect by providing a password. The passwords can be stored as scram-sha-256 md5 and password (clear-text)
  • Ident – This method is only supported on TCP/IP connections. Works by obtaining the client’s operating system user name, with an optional user name mapping.
  • Peer – Same as Ident but it is only supported on local connections.

PostgreSQL client authentication is defined in the configuration file named pg_hba.conf. By default for local connections, PostgreSQL is set to use the peer authentication method.

The postgres user is created automatically when you install PostgreSQL. This user is the superuser for the PostgreSQL instance and it is equivalent to the MySQL root user.

To log in to the PostgreSQL server as the postgres user first you need to switch to the user postgres and then you can access a PostgreSQL prompt using the psql utility:

sudo su - postgrespsqlCopyCopy

From here, you can interact with your PostgreSQL instance. To exit out of the PostgreSQL shell type:

\q

You can use the sudo command to access the PostgreSQL prompt without switching users:

sudo -u postgres psql

The postgres user is typically used only from the local host and it is recommended not to set the password for this user.

Creating PostgreSQL Role and Database

You can create new roles from the command line using the createuser command. Only superusers and roles with CREATEROLE privilege can create new roles.

In the following example, we will create a new role named john a database named johndb and grant privileges on the database.

  1. Create a new PostgreSQL RoleThe following command will create a new role named “john”:sudo su - postgres -c "createuser john"Copy
  2. Create a new PostgreSQL DatabaseCreate a new database named “johndb” using the createdb command:sudo su - postgres -c "createdb johndb"Copy
  3. Grant privilegesTo grant permissions to the john user on the database we created in the previous step, connect to the PostgreSQL shell:sudo -u postgres psqlCopyand run the following query:GRANT ALL PRIVILEGES ON DATABASE johndb TO john;Copy

Enable remote access to PostgreSQL server

By default the PostgreSQL, server listens only on the local interface 127.0.0.1. To enable remote access to your PostgreSQL server open the configuration file postgresql.conf and add listen_addresses = '*' in the CONNECTIONS AND AUTHENTICATION section.

sudo vim /etc/postgresql/9.6/main/postgresql.conf

/etc/postgresql/9.6/main/postgresql.conf

#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

listen_addresses = '*'     # what IP address(es) to listen on;

save the file and restart the PostgreSQL service with:

sudo service postgresql restart

Verify the changes with the ss utility:

ss -nlt | grep 5432
LISTEN   0         128                 0.0.0.0:5432             0.0.0.0:*
LISTEN   0         128                    [::]:5432                [::]:*

As you can see from the output above the PostgreSQL server is listening on all interfaces (0.0.0.0).

The last step is to configure the server to accept remote connections by editing the pg_hba.conf file.

Below are some examples showing different use cases:/etc/postgresql/9.6/main/pg_hba.conf

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# The user jane will be able to access all databases from all locations using a md5 password
host    all             jane            0.0.0.0/0                md5

# The user jane will be able to access only the janedb from all locations using a md5 password
host    janedb          jane            0.0.0.0/0                md5

# The user jane will be able to access all databases from a trusted location (192.168.1.134) without a password
host    all             jane            192.168.1.134            trust

Conclusion

You have learned how to install and configure PostgreSQL on your Debian 9 server. For more information on this topic, consult the PostgreSQL Documentation .

If you have any questions, please leave a comment below.

porplague70

How To Setup a Firewall with UFW on an Ubuntu and Debian Cloud Server.

Introduction

One of the first lines of defense in securing your cloud server is a functioning firewall. In the past, this was often done through complicated and arcane utilities. There is a lot of functionality built into these utilities, iptables being the most popular nowadays, but they require a decent effort on behalf of the user to learn and understand them. Firewall rules are not something you want yourself second-guessing.

To this end, UFW is a considerably easier-to-use alternative.

What is UFW?

UFW, or Uncomplicated Firewall, is a front-end to iptables. Its main goal is to make managing your firewall drop-dead simple and to provide an easy-to-use interface. It’s well-supported and popular in the Linux community—even installed by default in a lot of distros. As such, it’s a great way to get started securing your server.

Before We Get Started

First, obviously, you want to make sure UFW is installed. It should be installed by default in Ubuntu, but if for some reason it’s not, you can install the package using aptitude or apt-get using the following commands:

sudo aptitude install ufw

or

sudo apt-get install ufw

Check the Status

You can check the status of UFW by typing:

sudo ufw status

Right now, it will probably tell you it is inactive. Whenever ufw is active, you’ll get a listing of the current rules that looks similar to this:

Status: active

To               Action      From
--               ------      ----
22               ALLOW       Anywhere

Using IPv6 with UFW

If your VPS is configured for IPv6, ensure that UFW is configured to support IPv6 so that will configure both your IPv4 and IPv6 firewall rules. To do this, open the UFW configuration with this command:

sudo vi /etc/default/ufw

Then make sure “IPV6” is set to “yes”, like so:

IPV6=yes

Save and quit. Then restart your firewall with the following commands:

sudo ufw disable
sudo ufw enable

Now UFW will configure the firewall for both IPv4 and IPv6, when appropriate.

Set Up Defaults

One of the things that will make setting up any firewall easier is to define some default rules for allowing and denying connections. UFW’s defaults are to deny all incoming connections and allow all outgoing connections. This means anyone trying to reach your cloud server would not be able to connect, while any application within the server would be able to reach the outside world. To set the defaults used by UFW, you would use the following commands:

sudo ufw default deny incoming

and

sudo ufw default allow outgoing

Note: if you want to be a little bit more restrictive, you can also deny all outgoing requests as well. The necessity of this is debatable, but if you have a public-facing cloud server, it could help prevent against any kind of remote shell connections. It does make your firewall more cumbersome to manage because you’ll have to set up rules for all outgoing connections as well. You can set this as the default with the following:

sudo ufw default deny outgoing

Allow Connections

The syntax is pretty simple. You change the firewall rules by issuing commands in the terminal. If we turned on our firewall now, it would deny all incoming connections. If you’re connected over SSH to your cloud server, that would be a problem because you would be locked out of your server. Let’s enable SSH connections to our server to prevent that from happening:

sudo ufw allow ssh

As you can see, the syntax for adding services is pretty simple. UFW comes with some defaults for common uses. Our SSH command above is one example. It’s basically just shorthand for:

sudo ufw allow 22/tcp

This command allows a connection on port 22 using the TCP protocol. If our SSH server is running on port 2222, we could enable connections with the following command:

sudo ufw allow 2222/tcp

Other Connections We Might Need

Now is a good time to allow some other connections we might need. If we’re securing a web server with FTP access, we might need these commands:

sudo ufw allow www or sudo ufw allow 80/tcp sudo ufw allow ftp or sudo ufw allow 21/tcp

You mileage will vary on what ports and services you need to open. There will probably be a bit of testing necessary. In addition, you want to make sure you leave your SSH connection allowed.

Port Ranges

You can also specify port ranges with UFW. To allow ports 1000 through 2000, use the command:

sudo ufw allow 1000:2000/tcp

If you want UDP:

sudo ufw allow 1000:2000/udp

IP Addresses

You can also specify IP addresses. For example, if I wanted to allow connections from a specific IP address (say my work or home address), I’d use this command:

sudo ufw allow from 192.168.255.255

Denying Connections

Our default set up is to deny all incoming connections. This makes the firewall rules easier to administer since we are only selectively allowing certain ports and IP addresses through. However, if you want to flip it and open up all your server’s ports (not recommended), you could allow all connections and then restrictively deny ports you didn’t want to give access to by replacing “allow” with “deny” in the commands above. For example:

sudo ufw allow 80/tcp

would allow access to port 80 while:

sudo ufw deny 80/tcp

would deny access to port 80.

Deleting Rules

There are two options to delete rules. The most straightforward one is to use the following syntax:

sudo ufw delete allow ssh

As you can see, we use the command “delete” and input the rules you want to eliminate after that. Other examples include:

sudo ufw delete allow 80/tcp

or

sudo ufw delete allow 1000:2000/tcp

This can get tricky when you have rules that are long and complex.

A simpler, two-step alternative is to type:

sudo ufw status numbered

which will have UFW list out all the current rules in a numbered list. Then, we issue the command:

sudo ufw delete [number]

where “[number]” is the line number from the previous command.

Turn It On

After we’ve gotten UFW to where we want it, we can turn it on using this command (remember: if you’re connecting via SSH, make sure you’ve set your SSH port, commonly port 22, to be allowed to receive connections):

sudo ufw enable

You should see the command prompt again if it all went well. You can check the status of your rules now by typing:

sudo ufw status

or

sudo ufw status verbose

for the most thorough display.

To turn UFW off, use the following command:

sudo ufw disable

Reset Everything

If, for whatever reason, you need to reset your cloud server’s rules to their default settings, you can do this by typing this command:

sudo ufw reset

Conclusion

You should now have a cloud server that is configured properly to restrict access to a subset of ports or IP addresses.

porplague70

Restore pfSense From Backup Using The CLI (command line)

When all goes bad and you can’t get to the web interface of your Netgate pfSense, you’ll have no option but to try using the CLI (command line). This happened to me recently and this article explains what i did to recover.

A few worthy points:

  1. The pfSense configuration file (a single file) is stored in “/cf/conf/config.xml“.
  2. Backup configuration files are stored in “/cf/conf/backup/“.
  3. Copying the configuration file from the backup location over the top of the current configuration is effectively the restore process.

These are the steps to restore back to a previous state. I’m assuming the system wont boot as normal and therefore “single user” mode is needed.

  1. Boot the Netgate with the mini-USB cable connecting the Netgate appliance to your workstation.
  2. Very near the start of the booting process, there’s a prompt to boot with options. Select to boot into “single user” mode.
  3. When you get a prompt, remount the filesystem into read/write mode using “mount -u /cf”.
  4. Check the filesystem for errors and repair them with “fsck -yf /“.
  5. Locate and copy the restore file from the “/cf/conf/backup/” directory. Go back a few stages (not the latest file) based on the times of the backup files. Copy it with “cp /cf/conf/backup/config-1593242670.xml /cf/config/config.xml“.
  6. Remove the file “/tmp/config.cache” using “rm /tmp/config.cache“.
  7. Run the command “/etc/rc.reload_all start“.
  8. Reboot using “reboot“.

When the device reboots, it should be back-dated (in terms of the config) to the date of the restore file.

porplague70

Procedimento para Restaurar Backup Pfsense shell.

Copia e renomeia o backup para /conf/config.xml.

Depois disso, reboot.

porplague70

Problemas com drivers de rede realtek RTL 8111E

re0: <RealTek 8168/8111 B/C/CP/D/DP/E PCIe Gigabit Ethernet> port
0xe800-0xe8ff mem 0xfdfff000-0xfdffffff,0xfdff8000-0xfdffbfff irq 16 at
device 0.0 on pci2
re0: Using 1 MSI messages
re0: Chip rev. 0x2c800000
re0: MAC rev. 0x00000000
re0: Unknown H/W revision: 0x2c800000
device_attach: re0 attach returned 6

Baixe o modulo https://github.com/downloads/kelsen/modulos/if_re.ko
#copie para o diretório dos modulos
cp if_re.ko /boot/modules/

#carregue o modulo
kldload if_re.ko

Se tudo sair como esperado, a placa deverá ser reconhecida e então
configurada com ifconfig.
#carregar o modulo no boot
#edite /boot/loader.conf
#insira a linha
if_re_load=”yes”

achei aqui: http://forum.pfsense.org/index.php/topic,55563.msg299104.html

porplague70

Instalando Patch para pacotes extraoficiais

Instalando System Patch.

O System Patch é o pacote responsável por gerenciar os paches dentro do pfSense®, para instala-lo basta acessar o gerenciador de pacotes e busca-lo.

Acessando o System Patches

Configurando um patch

O procedimento abordado para essa configuração do patch também pode ser visto abaixo, ou vídeo-tutorial da ConexTI® no Youtube. https://www.youtube.com/embed/i_FjN6o_6CQ

Adicionando no Patch

Para adicionar um novo patch basta clicar em “Add New Patch”

Coloque alguma descrição para identificar o patch, e no campo “Patch Contents” deve ser posto o conteudo abaixo tambem encontrado neste link, deixe os outros parâmetros como na imagem a cima e em seguida, salve.

--- /etc/inc/pkg-utils.orig 2018-09-24 17:51:32.458825000 -0300
+++ /etc/inc/pkg-utils.inc  2018-09-24 17:51:54.387033000 -0300
@@ -388,7 +388,7 @@
    if ($base_packages) {
        $repo_param = "";
    } else {
-       $repo_param = "-r {$g['product_name']}";
+       $repo_param = "";
    }

    /*
@@ -485,7 +485,7 @@
                $err);
            if (!$base_packages &&
                rtrim($out) != $g['product_name']) {
-               continue;
+               //continue;
            }

            $pkg_info['installed'] = true;

Testando e aplicando

Como termino precisamos Teste(Test) e aplique(Apply) o novo patch.

Após esse procedimento os pacotes extraoficiais já poderão ser encontrados e disponíveis para instalação.

porplague70

script reboot se houver falha na rede.

crontab

*/5 * * * * /usr/bin/reset_net.sh

vi /usr/bin/reset_net.sh

!/bin/bash

HOSTS=”8.8.8.8″

COUNT=10

for myHost in $HOSTS
do
count=$(ping -c $COUNT $myHost | grep ‘received’ | awk -F’,’ ‘{ print $2 }’ | awk ‘{ print $1 }’)
if [ $count -eq 0 ]; then
# 100% failed
echo “Host : $myHost is down (ping failed) at $(date)” >> /var/log/log_controle_net.log
systemctl reboot -i;
else
echo “tudo ok $(date)” >> /var/log/log_controle_net.log
fi
done

porplague70

Solução para placas de rede Realtek (RTL8111/8168/8411) que não conectam

Segue mais uma dica para aqueles que estão perdendo a cabeça ao tentar fazer as placas RTL8111/8168/8411 funcionarem no Ubuntu e seus derivados como o Linuxmint.

Este tutorial foi testado nas placas com chip RTL8111/8168/8411, nos sistemas Kubuntu e Xubuntu 18.04LTS e Linux Mint 19.03.

Pode ser que funcione com outras placas da Realtek, teste e diga o resultado.

Faça o procedimento abaixo por sua conta e risco, afinal se você já tentou de tudo creio que nada tem a perder. Comigo funcionou perfeitamente.

Antes de tudo você precisa estar conectado a internet (não me xingue) use a opção de ancoragem do seu celular conetado ao USB do seu PC, ou algum Wirelles USB.

*7 passos.

1- sudo apt-get install linux-headers-generic build-essential dkms

2- wget http://ftp.us.debian.org/debian/pool/non-free/r/r8168/r8168-dkms_8.047.05-1_all.deb

3- sudo dpkg -i r8168*.deb

4- echo “blacklist r8169” | sudo tee -a /etc/modprobe.d/blacklist-r8169.conf

5- sudo modprobe -rfv r8169

6- sudo modprobe -v r8168

7- sudo service network-manager restart

Perfeito, agora é curtir o seu pc e partir para o abraço!