504 Gateway Timeout on Synology NAS

Looks familiar?

I want to move this blog to my own NAS because I have plenty enough bandwidth and with Cloudflare as reverse proxy it is secure enough also (and I like to hobby off course 😉 ).

I tried to use the Duplicator WordPress plugin to make a dump of my website and do a restore in the Synology Webstation. But during the database restore in step 2 every time I was getting a 504 gateway timeout after a minute (exactly 60 seconds).

What I could have done was a manual (ftp & database) copy and restore the files. But I was sure I was getting other errors in the future when I had to update WordPress or other plugins. So fixing this timeout issue was the only solution.

On different places on the internet, I found that I had change the Nginx site settings. So I put the timeout settings in the associated “/etc/nginx/conf.d/site.conf” and restart Nginx and restore the database Nginx was still was failing.

    proxy_connect_timeout 600s;
    proxy_send_timeout 600s;
    proxy_read_timeout 600s;
    send_timeout 600s;

Then I’ll try to put these lines in the “/etc/nginx/nginx.conf” but when I restart the nginx the settings were overwritten and my changes are gone.

Every time you restart, Nginx Synology make use of a file “/usr/syno/share/nginx/nginx.mustache” to create a new nginx.conf file. I change the lines in that file and *boom* everything was working 🙂

So TLDR;

sudo su -
vim /usr/syno/share/nginx/nginx.mustache

#add these lines
    send_timeout                  600s;
    proxy_connect_timeout         600s;
    proxy_send_timeout            600s;
    proxy_read_timeout            600s;

synoservice --restart nginx

If you want to see the current Nginx config

nginx -T 

Have fun 🙂

Create Azure Linux VM with worpress pre-installed

This is my first completed automated Linux Azure VM deployment. I like to share it with you.

There are 3 parts

  1. Create a keygen for ssh
  2. Powershell script
  3. Bash script

First start powershell and create a keypair with passphase

ssh-keygen -m PEM -t rsa -b 4096

Then place the bash script somewhere on your local computer

#! /bin/bash
apt-get update
apt-get install -y wordpress php libapache2-mod-php mysql-server php-mysql

echo "Alias /blog /usr/share/wordpress" >>/etc/apache2/sites-available/wordpress.conf
echo "<Directory /usr/share/wordpress>" >>/etc/apache2/sites-available/wordpress.conf
echo "    Options FollowSymLinks" >>/etc/apache2/sites-available/wordpress.conf
echo "    AllowOverride Limit Options FileInfo" >>/etc/apache2/sites-available/wordpress.conf
echo "    DirectoryIndex index.php" >>/etc/apache2/sites-available/wordpress.conf
echo "    Order allow,deny" >>/etc/apache2/sites-available/wordpress.conf
echo "    Allow from all" >>/etc/apache2/sites-available/wordpress.conf
echo "</Directory>" >>/etc/apache2/sites-available/wordpress.conf
echo "<Directory /usr/share/wordpress/wp-content>" >>/etc/apache2/sites-available/wordpress.conf
echo "    Options FollowSymLinks" >>/etc/apache2/sites-available/wordpress.conf
echo "    Order allow,deny" >>/etc/apache2/sites-available/wordpress.conf
echo "    Allow from all" >>/etc/apache2/sites-available/wordpress.conf
echo "</Directory>" >>/etc/apache2/sites-available/wordpress.conf

a2ensite wordpress
a2enmod rewrite 
reload apache2 
service apache2 reload
systemctl restart apache2

mysql -e "CREATE DATABASE wordpress;"
mysql -e "CREATE USER [email protected] IDENTIFIED BY '[email protected]';"
mysql -e "GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,ALTER ON wordpress.* TO [email protected];"
mysql -e "FLUSH PRIVILEGES;"

echo "<?php" >>/etc/wordpress/config-localhost.php
echo "define('DB_NAME', 'wordpress');">>/etc/wordpress/config-localhost.php
echo "define('DB_USER', 'wordpress');">>/etc/wordpress/config-localhost.php
echo "define('DB_PASSWORD', '[email protected]');">>/etc/wordpress/config-localhost.php
echo "define('DB_HOST', 'localhost');">>/etc/wordpress/config-localhost.php
echo "define('DB_COLLATE', 'utf8_general_ci');">>/etc/wordpress/config-localhost.php
echo "define('WP_CONTENT_DIR', '/usr/share/wordpress/wp-content');">>/etc/wordpress/config-localhost.php
echo "?>">>/etc/wordpress/config-localhost.php

service mysql start


publicip=$(dig +short myip.opendns.com @resolver1.opendns.com) && mv /etc/wordpress/config-localhost.php /etc/wordpress/config-$publicip.php

Then put the code in the Powershell ISE, change some variables and kickoff the script.

The things you may need to change:

  • script.sh location

New-AzResourceGroup -Name lxautodeploy -Location westeurope

# Create a subnet configuration
$subnetConfig = New-AzVirtualNetworkSubnetConfig `
  -Name "mySubnet" `
  -AddressPrefix 192.168.1.0/24

# Create a virtual network
$vnet = New-AzVirtualNetwork `
  -ResourceGroupName "lxautodeploy" `
  -Location "westeurope" `
  -Name "myVNET" `
  -AddressPrefix 192.168.0.0/16 `
  -Subnet $subnetConfig

# Create a public IP address and specify a DNS name
$pip = New-AzPublicIpAddress `
  -ResourceGroupName "lxautodeploy" `
  -Location "westeurope" `
  -AllocationMethod Static `
  -IdleTimeoutInMinutes 4 `
  -Name "mypublicdns$(Get-Random)"


# Create an inbound network security group rule for port 22
$nsgRuleSSH = New-AzNetworkSecurityRuleConfig `
  -Name "myNetworkSecurityGroupRuleSSH"  `
  -Protocol "Tcp" `
  -Direction "Inbound" `
  -Priority 1000 `
  -SourceAddressPrefix * `
  -SourcePortRange * `
  -DestinationAddressPrefix * `
  -DestinationPortRange 22 `
  -Access "Allow"

# Create an inbound network security group rule for port 80
$nsgRuleWeb = New-AzNetworkSecurityRuleConfig `
  -Name "myNetworkSecurityGroupRuleWWW"  `
  -Protocol "Tcp" `
  -Direction "Inbound" `
  -Priority 1001 `
  -SourceAddressPrefix * `
  -SourcePortRange * `
  -DestinationAddressPrefix * `
  -DestinationPortRange 80 `
  -Access "Allow"

# Create a network security group
$nsg = New-AzNetworkSecurityGroup `
  -ResourceGroupName "lxautodeploy" `
  -Location "westeurope" `
  -Name "myNetworkSecurityGroup" `
  -SecurityRules $nsgRuleSSH,$nsgRuleWeb

  # Create a virtual network card and associate with public IP address and NSG
$nic = New-AzNetworkInterface `
  -Name "myNic" `
  -ResourceGroupName "lxautodeploy" `
  -Location "westeurope" `
  -SubnetId $vnet.Subnets[0].Id `
  -PublicIpAddressId $pip.Id `
  -NetworkSecurityGroupId $nsg.Id

  # Define a credential object
$securePassword = ConvertTo-SecureString ' ' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("azureuser", $securePassword)

# Create a virtual machine configuration
$vmConfig = New-AzVMConfig `
  -VMName "myLXVM" `
  -VMSize "Standard_D2s_v3" | `
Set-AzVMOperatingSystem `
  -Linux `
  -ComputerName "myLXVM" `
  -Credential $cred `
  -DisablePasswordAuthentication | `
Set-AzVMSourceImage `
  -PublisherName "Canonical" `
  -Offer "UbuntuServer" `
  -Skus "18.04-LTS" `
  -Version "latest" | `
Add-AzVMNetworkInterface `
  -Id $nic.Id

# Configure the SSH key
$sshPublicKey = cat ~/.ssh/id_rsa.pub
Add-AzVMSshPublicKey `
  -VM $vmconfig `
  -KeyData $sshPublicKey `
  -Path "/home/azureuser/.ssh/authorized_keys"

New-AzVM `
  -ResourceGroupName "lxautodeploy" `
  -Location westeurope -VM $vmConfig

Get-AzPublicIpAddress -ResourceGroupName "lxautodeploy" | Select "IpAddress"



Invoke-AzVMRunCommand -ResourceGroupName "lxautodeploy" -Name 'myLXVM' -CommandId 'RunShellScript' -ScriptPath "script.sh" -Verbose

Now you can go to http://<publicip>/blog to access the new blog

You can access the server with ssh azureuser@<publicip>

Have fun with it!

Install Pihole on Synology with docker

Unfortunately, there isn’t a pihole addon in the Synology package center. But you can build your pihole in a docker container instead 🙂

The reason you must use docker-compose instead of the Synology docker package itself is that you want to bridge net NIC of your Synology and place the pihole direct in your network. You cannot do this with the GUI.

The steps:

  • Install docker with the package center
  • Activate SSH
  • Download de image pihole/pihole:latest
  • Login with ssh
  • type vi docker-compose.yaml
  • Paste the content from the docker-compose.yaml example into the vi
  • Change the IP adressen to your own network
  • Type :wr to save the file
  • Type :q to quit vi
  • Type “sudo docker-compose up”
  • Have fun!

Docker-compose.yaml Example

# Note: 192.168.123.xxx is an example network, you must update all these to match your own.

version: '2'

services:
  pihole:
    container_name: pihole
    image: pihole/pihole:latest
    hostname: pihole
    domainname: localhost             # <-- Update
    mac_address: d0:ca:ab:cd:ef:01
    cap_add:
      - NET_ADMIN
    networks:
      pihole_network:
        ipv4_address: 192.168.123.199   # <-- Update
    dns:
      - 127.0.0.1
      - 1.1.1.1
    ports:
      - 443/tcp
      - 53/tcp
      - 53/udp
      - 67/udp
      - 80/tcp
    environment:
      ServerIP: 192.168.123.199                 # <-- Update (match ipv4_address)
      VIRTUAL_HOST: pihole.localhost            # <-- Update (match hostname + domainname)
      WEBPASSWORD: "justarondompassword"        # <-- Add password (if required)
    restart: unless-stopped

networks:
  pihole_network:
    driver: macvlan
    driver_opts:
      parent: ovs_eth0
    ipam:
      config:
        - subnet: 192.168.123.0/24            # <-- Update
          gateway: 192.168.123.1              # <-- Update
          ip_range: 192.168.123.192/28        # <-- Update

When you want to update the docker container, all you have to do is:

sudo docker-compose down

and

sudo docker-compose up

A good article I used to figure everything out is: http://tonylawrence.com/posts/unix/synology/free-your-synology-ports/

Ubuntu Linux cannot ping FQDN

Because this is the fifth time I fixed this issue I write a blog about it…

Microsoft uses .local as the recommended root of internal domains, and serves them via unicast dns. Linux uses .local as the root of multicast dns. If you’re stuck on a broken MS network like this, reconfigure your linux multicast DNS to use a different domain like .alocal.

To do this, add a domain-name=.alocal line to the [server] section of /etc/avahi/avahi-daemon.conf, then restart avahi-daemon: sudo service avahi-daemon restart.

[server]
domain-name=.alocal

You may need to flush the DNS, mDNS and resolver cache, as well as restart your web browsers to clear their internal cache.

Source: http://www.lowlevelmanager.com/2011/09/fix-linux-dns-issues-with-local.html

Convert PFX to PEM and upload the certificate to Plesk

Export the Private Key:

# openssl pkcs12 -in filename.pfx -nocerts -out key.pem

Remove the password from the SSL certificate (unencrypted is needed for plesk):

# openssl rsa -in key.pem -out server.key

Export the certificate:

# openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem

Now upload the certificate:

ssl-thawte

And bind the certificate in your hosting settings:

SSL-PII

Clone HP ThinState Capture USB stick (or any other USB disk)

The ThinState USB disk is split into 2 partitions. And the second partition isn’t accessible in Windows so it was very hard to build a stick from scratch. There are a lot of Windows USB clone tools but because I had to clone the ThinState 16GB to a 8GB stick also, it was impossible to do it from my windows workstation. But when some things get more difficulty what do you do? Use Linux 🙂

The Easy way (same USB stick size or bigger):

$sudo dd if=/dev/sdb of=/dev/sdc bs=512

The “Hard” way (clone to smaller USB):

First resize the partitions with gparted to the minimum size. Then find out the last sector of the /dev/sdb2 (where sdb2 is my USB stick)

$sudo fdisk -u -l /dev/sdb

Output:

Disk /dev/sdb: 14,9 GiB, 16026435584 bytes, 31301632 sectors
Units: sectors of 1 * 512 = 512 bytes

Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: dos Disk identifier: 0x6a60ab98

Device     Boot   Start     End Sectors Size Id Type
/dev/sdb1 *       2048 2099199 2097152   1G b W95 FAT32
/dev/sdb2       2099200 14131199 12032000 5,8G 7 HPFS/NTFS/exFAT

Now use dd with sector 12032000 + 1.

dd if=/dev/sdb of=/home/myusername/usbimage.img count=12032001

and write the *.img file back to your new USB stick:

dd if=/home/myusername/usbimage.img of=/dev/sdb

Install chrome with Arch Linux

In Windows I like Firefox more than chrome because everything is already “Google”. But Google chrome has a nice stable and fast flash plugin built-in and so I need a chrome browser in Linux…. Because I’m testing Arch Linux (Antergos actually ) and Google don’t have arch packages I found a way to install it automatically for me with the AUR repository. $yaourt -S google-chrome More info about the yaourt (Yet AnOther User Repository Tool):

Using yaourt

You can install packages (including AUR packages) with

$ yaourt packagename

or

$ yaourt -Sa packagename

You can update your system including AUR packages with:

$ yaourt -Syua

Find spam script

THIS IS AN ORDINARY COPY/PAST FROM http://cbl.abuseat.org because I can’t find a source link and this is a nice article!

We have detected that this IP is NATting for, or is infected itself, with a Linux (or possibly some other Unix-like system such as FreeBSD) PHP spam mailing script. Occasionally Windows servers are infected as well.

We do not know how the malware got installed onto the machine, but we know a lot of what it does. The main thing we’ve seen it doing is sending staggering large volumes of email spam. But it can do a lot more than that, and that is the real danger.

NEW Of late some of these infections are facilitiated by a SSH Rootkit called “ebury”. See the link for more detail.

In most cases, this IP address would be that of a shared hosting environment. If you are a customer of this environment, you will almost certainly not be able to do anything about it, only the administrators of the hosting environment itself can. Please contact your administrators, and refer them to this page.

If the administrators are reluctant to do anything please try to convince them, because there is nothing you can do to fix this problem.

For the System Administrators

Your task is to find the current problem, fix it, and prevent it from happening again.

Finding the problem by network activity: Linux/FreeBSD etc

One way of finding the user that is infected and spewing spam is to use the “lsof” (list open files) utility. “lsof” is available for most versions of UNIX-like systems such as Linux as part of the official distribution, but may not be installed by default. So first, make sure you have it installed. On many systems such as Ubuntu, you can install it by:

sudo apt-get install lsof

Once lsof is installed, you can issue the following command

sudo lsof -i | grep smtp

You may see a number of lines, such as (example.com takes the place of your machine’s name):

sendmail- 18520 root  3u IPv4 3016693 0t0 TCP *:smtp (LISTEN)
sendmail   4401 mail 13u IPv4 8742322 0t0 TCP example.com:42177->mail1.hotmail.com:smtp (ESTABLISHED)
exim       6348 mail  3u IPv4 210565067 0t0 TCP *:smtp (LISTEN)
find       4403  foo 13u IPv4 8742322 0t0 TCP example.com:42176->mtain-dk.r1000.mx.aol.com:smtp (ESTABLISHED)

The first line, for example, is your sendmail mail software “LISTEN”ing (as userid root) for inbound email connections – this is normal. The second line is sendmail “caught” at the moment of sending an email (as userid “mail”) from your machine to a hotmail server – that is also perfectly normal. You may see similar lines with “exim” or “postfix” or “smtpd” or “qmail” instead of sendmail – all depending on what mail server you run – example – the third line is an Exim listener. The important thing that indicates that it’s normal is that the userid is “mail” or “mailman” or something like that – NOT an ordinary user.

The fourth line is a program called “find”, running under userid “foo” making a connection to an AOL server.

It’s examples like the fourth line you’re looking for – it tells you the userid of the infected user. In this case it also indicates that the infection is masquerading as the program “find”. There will often be more than one of these.

Simply killing these processes is NOT enough, because they will often restart on their own. You will need to find whether these are started by a cron job owned by that user, or, spawned through your web server, or started from a ssh login. Find and delete the program – often a PHP or Perl script. In some cases, however, the program deletes itself as soon as it starts. The “find” example above is a Linux binary executable that contains an encrypted perl script. Since this was first written, it now sometimes masquerades as “mail” or “ntpd”. Assume it could be anything. You will also need to find out how the script got installed on your machine – often through Joomla, WordPress, Cpanel or Plesk security holes, or ftp upload and secure it.

WARNING Just because you didn’t find a line like the “foo” line above doesn’t mean the machine is not infected! It just means that the machine is not sending email at the instant lsof was run. If you don’t see a line like the “foo” line, we suggest that you run the lsof command multiple times. Example:

while true
do
    sudo lsof -i | grep smtp
    sleep 10
done

Finding the problem by finding the script: Linux/FreeBSD

Try the findbot.pl program. It’s a relatively straight-forward Perl script that will find most of the malicious scripts that we are aware of. The beginning of the file contains instructions on how to use it. If you are not the administrator of the system, it will not work for you.

Many of these infections start themselves running, and then delete themselves from disk. Which means you won’t be able to find it. Check your ftp and SSH logs for suspicious files and logins. This is why it’s so important to prevent it happening again.

Finding the problem by network activity: Windows

The Windows environment is rather less developed for finding these things than UNIX-like systems. However, we can recommend the tcpview tool, so please see tcpview/tcpconn in our advanced section.

Finding the problem by logs: (Mostly) Linux/FreeBSD

Most of these scripts are quite good at hiding their presence. Some of them start up, and them remove the on-disk copy, so there’s nothing to see. None of them volunteer where they are, so samples don’t help. Most of these scripts bypass your mail server software, so there is nothing to see in the mail logs or queues.

However, they all do need to get on your system somehow, and that often leaves logs. If you can find those log records, often that will help you identify the infected user and find the malicious files (if they are still there).

Generally speaking, these are the ways malicious scripts get onto a system:

 

  • Web sites often make FTP or SSL available so their customers can upload content or log in to manage their web pages. If the customer’s computer is compromised with a keylogger, it means that the criminal can upload anything they want. You can usually see this activity in your FTP or SSL logs – look for uploads of .php or .pl files, lots of oddly named files, access from a large variety of IP addresses, etc. If you do find something like this, it’s important to get the user to change their password, and do virus scans of their computers.
  • Check your web server for large quantities of requests to the same PHP or CGI or Perl file, or POST commands, etc… This can reveal where the infection is, and often how it got there.
  • Most CMSes, in particular, Plesk, CPanel, WordPress and Joomla quite simply have severe security holes being found in them, seemingly daily, and hosted environments are often reluctant to keep up to date with their patching. You may never find a reasonable explanation of how the malicious software got there

 

Preventing it Happening Again

 

  • Make absolutely certain that ALL CMS software (Joomla, Cpanel, WordPress, Plesk etc) is kept up to date at all times. Do not let your users make any excuses for not doing so.
  • Make it impossible for such infections (and they will happen again) to spam the world by implementing the blocking of email sent direct from the machine without going through your mail server.Some of your customers may believe that they need to be allowed to do this. The best answer for them is to configure their software to relay it through the mail server software on the machine or to an external smart-host.

    For blocking: With Cpanel you can use ConfigServer Security Firewall (CSF). It’s free. CSF has the “SMTP_BLOCK” configuration option – turn it on.

    Basic Cpanel, there’s also “WHM SMTP Tweak” would should also help.

    The following is an equivalent for non-Cpanel installations – it permits local mail submission and blocks external mail submission:

    iptables -A OUTPUT -d 127.0.0.1 -p tcp -m tcp --dport 25 -j ACCEPT
    iptables -A OUTPUT -p tcp -m tcp --dport 25 -m owner --gid-owner mail -j ACCEPT
    iptables -A OUTPUT -p tcp -m tcp --dport 25 -m owner --gid-owner mailman -j ACCEPT
    iptables -A OUTPUT -p tcp -m tcp --dport 25 -m owner --uid-owner root -j ACCEPT
    iptables -A OUTPUT -p tcp -m tcp --dport 25 -j REJECT --reject-with icmp-port-unreachable
    

    The above permits users to send mail via a local mail server, permits local mail server software (running under userid root, or gid mail or mailman) to send email to the Internet, but prevents any ordinary user making direct SMTP connections to the Internet. You may have to adjust this for Qmail or Exim. Check which userids are used. Note that the iptables settings will probably be lost next time you reboot. The iptables commands should be installed into a system init script.

    If you’re using cPanel and APF, APF by default will wipe out iptables rules you enter manually leaving the server vulnerable. If you are using APF, you should make the above change via APF and that will take care of reissuing the commands upon reboot or reset.

  • Do you really need PHP script support? CGI support? PHP mail functions? Turn off the ones you don’t need. Some people, for example, turn off CGIs, and PHP “fsocketopen” or “exec” functions in the PHP ini files (either for the whole site, or individual environments), and manage to inhibit many infections.
  • Some of these scripts get installed into /tmp. If /tmp is a separate file system, you can stop it being used by malicious scripts by adjusting the /etc/fstab file to mount /tmp with the “noexec” and “nosuid” flags. This means that the O/S will not run programs that are in the /tmp directory nor treat them as setuid.
  • Turn off customer FTP if you don’t need it. Note that some CMS packages install FTP with anonymous FTP turned on by default. This is ALWAYS a bad idea, so make sure “anonymous login” is turned off.
  • It is necessary to force password changes on those users whose web sites have been compromised. If you can’t tell exactly which users have been compromised, it’s strongly recommended you change all passwords.