Ubuntu Postgres Account Coin Miner Hacking

When I accidentally typed the top command on the Ubuntu server, I found a strange process consuming a lot of CPU.

Suspicious file searched by md5: 8f96e8b4e9d26884c776c1b42a70bae5

https://otx.alienvault.com/indicator/file/5e5fd0bc5f1bd663d7ccc2695c2b56bd382df3c7fdac605eb0ce3c0d5df24dc4

Below is the resolution process

This process looks suspicious. Paths and filenames like /tmp/./.kGX8ucb are generally not formats used by normal software. This could be part of malware or hacking. Here are some steps to quickly take action in this situation.

  1. Terminate the suspicious process: You can forcibly terminate the process. Use the command kill -9 3785242 to kill the process.
  2. Delete the suspicious file: After terminating the process, delete the /tmp/./.kGX8ucb file. Execute rm /tmp/./.kGX8ucb.
  3. Check for other suspicious processes: To check if other suspicious processes are running, use a command like ps aux | grep tmp to see if there are other processes running in the /tmp directory.
  4. System check: It is advisable to perform additional security checks to confirm whether the system has been infected.
    • Examine the system using rootkit detection tools like rkhunter or chkrootkit.
    • Check system logs (/var/log/auth.log or /var/log/syslog) for any suspicious activity.
  5. Check network connections: Use the command netstat -tulnp to check the network connections and verify if there are any strange processes connected to the external network.
  6. Patch and update: Ensure that your system is up to date and apply all possible security patches. Use sudo apt update && sudo apt upgrade to update the packages.
  7. Change passwords: It is also important to change the passwords of all user accounts on the server to prevent possible account hijacking.

Depending on the situation, you might consider backing up and reinstalling the system.

4o

My question:

Can I lock a specific account? The postgres account

ChatGPT’s response:

Yes, you can restrict access to specific user accounts such as the postgres account by locking it in Ubuntu. Here are some ways to lock the account.

1. Lock the account (set to unusable)

You can lock the account using the passwd command.

bash code copysudo passwd -l postgres

This command changes the password of the postgres account to a locked state, making it impossible to log in with that account.

2. Change shell to /bin/false or /sbin/nologin

If you want to make login completely impossible, you can also change the shell of the account. For example, setting the shell of the postgres account to nologin will prevent that account from logging in.

bash code copysudo usermod -s /sbin/nologin postgres

Or

bash code copysudo usermod -s /bin/false postgres

This command prevents the postgres user from accessing the shell when attempting to log in.

3. Set account expiration

You can restrict usage by expiring the account itself.

bash code copysudo usermod -e 1 postgres

This command makes the postgres account expired, making it impossible to log in anymore.

4. Check processes and services, then take action

If the postgres account has been exploited, it may be related to processes or services running within the system, so it’s important to check and terminate those processes with the following command.

bash code copyps aux | grep postgres

Using this command, you can check the processes running under the postgres account and forcibly terminate any suspicious processes.

bash code copysudo kill -9 <PID>

With the above methods, you can effectively lock the postgres account.

How to log out the account immediately

Yes, you can immediately log out the postgres account and terminate all processes of that account. You can forcibly terminate all sessions running under the postgres account using the following command.

1. Check processes of the postgres account

First, check the processes running under the postgres account.

bash code copyps -u postgres

This command will show a list of all processes running under the postgres account.

2. Force terminate all processes of the postgres account

The following command will immediately terminate all processes running under the postgres account.

bash code copysudo pkill -u postgres

This command forcibly terminates all processes that the postgres account is running. This will log out all sessions that are running under that account.

3. Additional checks

After termination, check the processes again to see if the postgres account is still running.

bash code copyps -u postgres

Through this process, you can immediately log out the postgres account.

Can I view the login information of the postgres account in Ubuntu?

To check the login history of a specific account (e.g., postgres) in Ubuntu, you can use some log files and commands. The login history is typically stored in /var/log/wtmp and /var/log/auth.log.

1. Using the last command

You can check the login history of users on the system using the last command.

bash code copylast postgres

This command will show all the records of logins by the postgres account. This includes login and logout times, locations from which the logins occurred (e.g., IP addresses).

2. Check the auth.log file

The /var/log/auth.log file records authentication-related events. This includes records of user login attempts, both successful and failed. You can filter for login-related information for the postgres account using the grep command.

bash code copysudo grep 'postgres' /var/log/auth.log

Executing this command will allow you to see information about login attempts related to the postgres account, whether successful or failed.

3. Using the journalctl command

On systems using systemd, you can use the journalctl command to check for login events related to the postgres account.

bash code copysudo journalctl _COMM=postgres

This command will display all logs related to the postgres service or account. You can identify login attempts or related activities here.

4. Check the /var/log/wtmp file

The wtmp file is a binary file that stores the records of all logins, logouts, and system reboots. The last command refers to this file by default. To check the wtmp file directly:

bash code copylast -f /var/log/wtmp | grep postgres

This command will display the login/logout records related to the postgres account from the wtmp file.

You can use these commands to check the login information for the postgres account, which can help identify suspicious login activity.

Strange files keep appearing, but is it possible to analyze them? It seems like hacking tools.

If suspicious files are being created on your Ubuntu system, you can analyze those files to determine whether they are malware (hacking tools). You can follow several methods to analyze files. Here are some steps you can take.

1. Check basic information about the file

First, you can check the basic properties of the file to determine what type it is, who created it, and when it was created.

bash code copyls -l /path/to/suspicious_file

This command displays the file’s owner, permissions, creation time, and more.

bash code copyfile /path/to/suspicious_file

This command checks the file type. For example, you can determine whether it is a binary file or a script file.

2. Generate a hash value for the file (integrity check)

You can generate a hash value to verify the file’s integrity or to search for a similar file on other systems. By creating hash values such as MD5 or SHA256, you can check if that file is present in malware databases.

bash code copymd5sum /path/to/suspicious_file
sha256sum /path/to/suspicious_file

You can use these hash values to verify the file with online services like VirusTotal.

3. Use online malware scanning tools (such as VirusTotal)

You can also directly upload the files to check for malware. Services like VirusTotal analyze files using multiple antivirus engines.

  1. Download the suspicious file and upload it to VirusTotal via a secure network.
  2. Alternatively, you can enter the hash value of the file into VirusTotal to check if it has been analyzed before.

4. Inspect the contents of the file with the strings command

Even for binary files, you can use the strings command to check for human-readable text information within the file. This can help you find clues of malware.

bash code copystrings /path/to/suspicious_file

This command will display text within the file (e.g., URLs, commands, etc.). You can identify URLs or scripts that might indicate malware.

5. Check file usage with the lsof command

You can use the lsof command to check which processes are currently using the file.

bash code copylsof /path/to/suspicious_file

This command shows the processes or network connections that have the suspicious file open. If this file is in use by a malicious process, you can terminate that process and isolate the file.

6. Check network activity of the file

If the file is running, you can check for network activity. Use netstat or ss to determine if malware is sending data externally.

bash code copynetstat -tulnp

This command checks for currently open network connections to look for suspicious connections. You can also confirm if the suspicious file is connecting to an external server.

7. Use malware sandbox analysis tools

If you want to perform more specialized malware analysis, you can use sandbox analysis tools. These tools run the file in a safe environment to track its behavior. An open-source sandbox tool is Cuckoo Sandbox.

  • Cuckoo Sandbox runs suspicious files in a virtual environment to observe the actions the file performs.

8. Use antivirus tools like ClamAV

You can use the open-source antivirus program ClamAV to scan your system in Ubuntu.

To install and scan with ClamAV:

bash code copysudo apt update
sudo apt install clamav
sudo freshclam  # Update virus database
sudo clamscan -r /path/to/directory

This command scans the specified directory or file and detects malware.

9. Remove execution permissions and delete the file

If a file is confirmed to be malware or is suspicious, you can remove its execution permissions, isolate it, or delete it.

To remove execution permissions:

bash code copychmod -x /path/to/suspicious_file

To delete the file:

bash code copyrm /path/to/suspicious_file

Summary

  1. Check the basic information of the file (ls, file).
  2. Generate a hash value for the file and check it with online tools (VirusTotal).
  3. Use the strings command to inspect text contents of the file.
  4. Check if the file is in use with the lsof command.
  5. Check network connections (netstat, ss).
  6. Analyze file behavior using sandbox tools (Cuckoo Sandbox).
  7. Scan the system with antivirus tools like ClamAV.
  8. If confirmed as a malicious file, remove execution permissions and delete it.

This procedure allows you to verify whether suspicious files are malware and take appropriate action.

It seems to be Trojan:Linux/CoinMiner.K, what should I do?

Trojan:Linux/CoinMiner.K is a Trojan that mines cryptocurrency on Linux systems. This Trojan utilizes the resources of the infected system to mine cryptocurrency, which can degrade system performance and lead to excessive power consumption. To remove it and secure the system, follow the steps below.

1. Terminate suspicious processes

The cryptocurrency mining Trojan may run processes with names like coinminer, xmrig, minerd. Check and terminate all suspicious processes that are running.

bash code copyps aux | grep -i 'coinminer\|xmrig\|minerd'

Find the PID of the suspicious process using the command above and terminate it with the command below.

bash code copysudo kill -9 <PID>

2. Delete files

This Trojan often creates executable files in the /tmp directory or hidden directories. Check /tmp, /var/tmp, and hidden files in the user’s home directory and delete any suspicious files.

bash code copysudo rm -rf /tmp/* /var/tmp/*

3. Check user accounts

If the Trojan was installed with root privileges, there is a possibility that a malicious user account has been added to allow access to the system. Use the following command to check for suspicious user accounts and delete them.

bash code copysudo cat /etc/passwd
sudo userdel -r <username>

4. Check scheduled tasks (Crontab)

Trojan tasks are often added to cron jobs to ensure they run persistently after infection. Check for suspicious tasks registered in cron and remove them.

  • Check user-specific crontab:bash code copysudo crontab -l sudo crontab -u postgres -l
  • Check system cron:bash code copysudo cat /etc/crontab sudo ls /etc/cron.*

If there are any suspicious jobs, delete them using the following command.

bash code copysudo crontab -e

5. Perform a full system scan with ClamAV

By installing ClamAV, you can scan the entire system and remove malicious files.

bash code copysudo apt update
sudo apt install clamav
sudo freshclam  # Update virus database
sudo clamscan -r --remove /  # Full system scan and remove infected files

6. Check and block suspicious network connections

Trojan may connect to an external server to perform operations. Check network connections using the netstat command and block any suspicious IP addresses.

bash code copysudo netstat -tulnp

If any suspicious IP address is found, you can block it using iptables.

bash code copysudo iptables -A OUTPUT -d <suspicious IP address> -j DROP

7. Check system logs

To track traces of penetration and activity, check /var/log/auth.log, /var/log/syslog, etc.

bash code copysudo cat /var/log/auth.log
sudo cat /var/log/syslog

8. Update packages and security patches

Update all packages to the latest version to block any security vulnerabilities in the system.

bash code copysudo apt update && sudo apt upgrade -y

9. Change passwords

Change the passwords of all user accounts to minimize the possibility of external intrusion.

10. Additional protective measures

For security, set up security groups and consider reinstalling the OS after backup if necessary.

If suspicious activity persists even after these measures, it is advisable to back up and reset the system as infection may still exist.

How to delete the postgres account, the database, and all related data?

To completely delete the PostgreSQL account, database, and all related data, perform the steps below in order. This process will delete the PostgreSQL server and all data files, so caution is necessary.

1. Stop the PostgreSQL service

First, stop the PostgreSQL server.

bash code copysudo systemctl stop postgresql

Alternatively, you can use the command below depending on the service name.

bash code copysudo service postgresql stop

2. Delete the postgres account

Delete the system user account postgres created during PostgreSQL installation. Deleting this account will also delete any files owned by this account.

bash code copysudo userdel -r postgres

The -r option will delete the home directory and files owned by the postgres account as well.

3. Delete PostgreSQL data directory and log files

All databases and data for PostgreSQL are typically stored in the /var/lib/postgresql/ directory. After deleting PostgreSQL, remove this directory to delete the database files.

bash code copysudo rm -rf /var/lib/postgresql/

Moreover, if PostgreSQL log files are in /var/log/postgresql/, you can also delete those log files.

bash code copysudo rm -rf /var/log/postgresql/

4. Uninstall PostgreSQL software

Uninstall PostgreSQL package to remove all related files.

Remove PostgreSQL on Ubuntu/Debian-based systems

bash code copysudo apt-get --purge remove postgresql*

The --purge option removes settings files associated with PostgreSQL as well.

Remove PostgreSQL on CentOS/RHEL-based systems

bash code copysudo yum remove postgresql*

5. Check and delete remaining configuration files

Configuration or related files of PostgreSQL may still reside in /etc/postgresql/. If this directory exists, delete it.

bash code copysudo rm -rf /etc/postgresql/

6. Verify PostgreSQL removal from the system

Check if PostgreSQL has been completely removed. If the psql command does not work, PostgreSQL has been successfully removed.

bash code copypsql

If PostgreSQL-related files or processes are still found, please check and delete each directory again.

Following these steps will completely remove all data, user accounts, and database files related to PostgreSQL.

Note

https://si.mpli.st/dev/2018-04-15-cryptominer-inside-postgres

Ultimately, in my case, I deleted the postgres account, the db, deleted all related files, and ran clamscan on the entire computer, removing even the suspicious files found in tmp, changed passwords, and strengthened the firewall.

Adding HTTPS Certificate to Ubuntu Apache Server – Free

To apply HTTPS to an Apache web server, it is necessary to install an SSL certificate and change the Apache settings. HTTPS is a protocol that enhances security between clients and servers by encrypting data. This process covers how to obtain an SSL certificate and apply it to the server.

The following are the general steps to set up HTTPS:

1. Prepare SSL Certificate

An SSL certificate is required to set up HTTPS. There are several methods to obtain a certificate, including the following:

  • Let’s Encrypt: Provides free SSL certificates.
  • Commercial SSL Certificate: Purchase paid certificates from providers such as Comodo, DigiCert, GlobalSign, etc.

This description covers how to obtain an SSL certificate using the free option Let’s Encrypt.

2. Install Certbot (When using Let’s Encrypt SSL)

To obtain an SSL certificate from Let’s Encrypt, install Certbot. Certbot is a tool that automates the issuance and renewal of certificates.

Installing Certbot on Ubuntu/Debian:

bash code copysudo apt update
sudo apt install certbot python3-certbot-apache

Installing Certbot on CentOS/RHEL:

bash code copysudo yum install epel-release
sudo yum install certbot python3-certbot-apache

3. Set Up HTTPS on Apache (Using Certbot)

Using Certbot, you can automatically obtain an SSL certificate and modify the Apache settings.

Automate SSL Certificate Issuance and Apache Configuration with Certbot:

bash code copysudo certbot --apache

When you run the above command, Certbot will automatically obtain the certificate and modify the Apache configuration file to enable HTTPS. During the process, you will be prompted to enter your domain name and decide whether to apply SSL.

4. Manual Apache Configuration (When Manually Installing SSL Certificate)

To manually install the SSL certificate, you need to modify the Apache configuration file.

1) Activate SSL Module:

On systems based on Ubuntu or Debian, you need to activate the mod_ssl module.

bash code copysudo a2enmod ssl

On CentOS, you can install the mod_ssl package to activate the SSL module.

bash code copysudo yum install mod_ssl

2) Modify Virtual Host File:

Modify the Apache virtual host configuration file to apply HTTPS. Typically, you modify the configuration file located in the /etc/apache2/sites-available/ directory.

Example:

bash code copysudo nano /etc/apache2/sites-available/your-domain.conf

In the your-domain.conf file, add the following HTTPS configuration:

apache code copy<VirtualHost *:443>
    ServerName your-domain.com
    DocumentRoot /var/www/html

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/your-domain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/your-domain.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/your-domain.com/chain.pem

    <Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Reference the file paths for the certificates provided by Let’s Encrypt. For commercial certificates, the paths must be changed to those of the issued certificates.

3) Verify Port 443 Settings:

Since SSL communication uses port 443, you need to ensure that Apache is listening on this port.

Check the /etc/apache2/ports.conf file for the following entry:

apache code copyListen 443

On CentOS, similar settings can be applied by modifying the /etc/httpd/conf.d/ssl.conf file.

5. Restart Apache

Once the configuration is complete, restart Apache to apply the changes.

Ubuntu/Debian:

bash code copysudo systemctl restart apache2

CentOS/RHEL:

bash code copysudo systemctl restart httpd

6. Automatic SSL Certificate Renewal (When Using Let’s Encrypt)

Let’s Encrypt certificates are valid for 90 days, so it is necessary to configure automatic renewal. Certbot provides an automatic renewal script that can be registered in Crontab.

Open Crontab:

bash code copysudo crontab -e

You can add the following line to set it up to attempt Certbot renewal every day at dawn:

bash code copy0 3 * * * certbot renew --quiet

Conclusion

This process allows you to apply HTTPS to Apache. Using Let’s Encrypt, you can obtain an SSL certificate for free and handle automatic configuration and renewal easily through Certbot.

Understanding Python Data Types and NumPy Arrays: From Basics

Understanding Python Data Types and NumPy Arrays: From Basics to Advanced

Python provides various data types to effectively manage and manipulate data. Additionally, it offers a powerful library called NumPy for efficient handling of numeric data. In this course, we will explore the basic data types in Python along with NumPy arrays.

1. Basic Data Types in Python

Python offers a variety of data types, allowing developers to manipulate data in different ways. Here, we will examine a few commonly used basic data types.

  • Integer (int): Stores integer values. For example, a = 10 stores the integer 10 in the variable a.
  • Floating-Point (float): Stores real numbers and can include a decimal point. For example, pi = 3.14 stores 3.14 in the variable pi.
  • String (str): Stores text data and is enclosed in single (' ') or double quotes (" "). Example: name = 'Alice'.
  • List (list): A mutable sequence that can store multiple values in order. Example: numbers = [1, 2, 3, 4].
  • Tuple (tuple): Similar to a list, but once created, a tuple cannot be modified. Example: point = (10, 20).
  • Dictionary (dict): Stores data in key-value pairs. Example: student = {'name': 'John', 'age': 25}.

2. NumPy Arrays

NumPy is a Python library that provides high-performance multidimensional array objects and various functions to handle them. It plays an essential role in almost all Python codes for scientific computing and numerical analysis.

Creating NumPy Arrays

import numpy as np

# Create a 1-dimensional array
arr1 = np.array([1, 2, 3, 4, 5])
print("1-dimensional array:", arr1)

# Create a 2-dimensional array
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print("2-dimensional array:\n", arr2)

Basic Array Operations

NumPy arrays provide convenient mathematical operations.

# Operations on array elements
result = arr1 + 10
print("Adding 10 to each element:", result)

# Operations between arrays
result = arr1 * 2
print("Multiplying each element by 2:", result)

NumPy vectorizes these operations, allowing them to be performed quickly over the entire array. This enables much faster processing of large amounts of numeric data compared to Python’s built-in lists.

3. Conclusion

In this course, we introduced the basic data types in Python and NumPy arrays. Basic data types like integers, floating-point numbers, strings, lists, tuples, and dictionaries are useful for storing and manipulating various data. Additionally, we learned how to use NumPy arrays for more efficient processing of numeric data.

Since NumPy plays a crucial role in data science and machine learning, it will be very beneficial to continue learning how to use it. Try to familiarize yourself with different data types and functions by using them directly!

Using Dynamic Objects in Python (Adding Attributes Dynamically Without Declaring a Class)

There is a way to dynamically add attributes without declaring an object in Python. A representative method is using `types.SimpleNamespace`. However, if you want to use the basic `object`, you need to declare a class. Here is a summary of how to use `types.SimpleNamespace` and how to use the basic `object`.

### Method 1: Using `types.SimpleNamespace`

Using `types.SimpleNamespace`, you can dynamically add attributes to an object without declaring a class:

Python Data Types – Pandas DataFrame

Pandas DataFrame

Pandas is a library widely used for data analysis in Python, and among its features, DataFrame is a two-dimensional structure consisting of rows and columns. A DataFrame can store and manipulate data in a format similar to an Excel spreadsheet, making it very useful for data analysis tasks.

import pandas as pd

# Create a DataFrame
data = {
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 30, 35],
    "City": ["New York", "Los Angeles", "Chicago"]
}
df = pd.DataFrame(data)
print(df)

Key Features of DataFrame

1. Creating a DataFrame

A DataFrame can be created from various data structures, such as dictionaries, lists, and Numpy arrays. For example, you can create a DataFrame using a dictionary.

data = {
    "Product": ["Apple", "Banana", "Cherry"],
    "Price": [100, 200, 300]
}
df = pd.DataFrame(data)
print(df)

2. Accessing Columns and Rows in a DataFrame

To access columns or rows in a DataFrame, you can use the loc or iloc methods. loc accesses based on labels, while iloc accesses based on integer indices.

# Access a column
print(df["Product"])

# Access a row (using loc)
print(df.loc[0])

# Access a row (using iloc)
print(df.iloc[1])

3. Adding and Removing Data

You can add new columns or rows to a DataFrame or delete existing data. To add a new column, you write as follows.

# Adding a new column
df["Discounted Price"] = df["Price"] * 0.9
print(df)

To delete a row, use the drop() method.

# Deleting a row
df = df.drop(1)
print(df)

4. Data Analysis Functions

Pandas provides various functions useful for data analysis. For example, the describe() function provides basic statistical information about the DataFrame.

print(df.describe())

Additionally, you can use functions like mean() and sum() to calculate the average or sum of a specific column.

average_price = df["Price"].mean()
print("Average Price:", average_price)

5. Filtering a DataFrame

You can filter data in a DataFrame based on specific conditions. For example, to select only products priced at 150 or more, write as follows.

filtered_df = df[df["Price"] >= 150]
print(filtered_df)

6. Sorting a DataFrame

To sort a DataFrame based on a specific column, use the sort_values() method.

# Sort in descending order by price
sorted_df = df.sort_values(by="Price", ascending=False)
print(sorted_df)

Summary

  • Variables are spaces for storing data, and when values are assigned, their data type is automatically determined.
  • You can use the type() function to check the data type of a variable.
  • Python variables use dynamic typing, allowing different types of values to be assigned to the same variable.
  • You can assign values to multiple variables at once or assign the same value to several variables.
  • You can use functions like int(), float(), and str() to convert data types.
  • Pandas DataFrame is a two-dimensional data structure consisting of rows and columns and is very useful for data analysis.
  • A DataFrame can be created in various forms such as dictionaries or lists, and you can access columns and rows as well as add and delete data.
  • You can efficiently analyze data using filtering, sorting, and statistical functions of a DataFrame.

Variables and Pandas DataFrames are essential tools for handling data in Python. Understand and apply them well to achieve effective data processing!