Showing posts with label Debian. Show all posts
Showing posts with label Debian. Show all posts

Saturday, April 22, 2017

Hosting Multiple Websites on a Single IP Address

It is not too difficult to host multiple websites on a single server and a single IP address. Here is how to do it with Apache server, based on article1, article2, and article3. I am assuming that you already have a server setup with apache2. If not, please refer to this tutorial for instructions.

The first step is to create virtual hosts where each virtual host serves each different website. For example, assume you want to serve domain names: hi.com and hello.com. You will need to create two virtual hosts, so that one will serve hi.com while the other will serve hello.com.

On Ubuntu or Debian, apache default server configuration files are in /etc/apache2 directory, while web server directory is /var/www.

First, copy the default configuration file and create two virtual host config files:
$ sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/hi.conf
$ sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/hello.conf

Next, edit /etc/apache2/sites-available/hi.conf similar to below:
 <VirtualHost *:80>
    ServerName hi.com
    ServerAlias www.hi.com
    DocumentRoot /var/www/hi
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>


Note that you must create /var/www/hi directory that contains files to serve for hi.com.

Similarly, edit /etc/apache2/sites-available/hello.conf in the same manner.
 <VirtualHost *:80>
    ServerName hello.com
    ServerAlias www.hello.com
    DocumentRoot /var/www/hello
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>


Again, you will need to create /var/www/hello directory that will serve visitors to hello.com.

Next, enable the new virtual host configuration files:
$ sudo a2ensite hi.conf 
$ sudo a2ensite hello.conf 

Next, reload apache2 so that the change takes effect
$ sudo service apache2 reload

If you want to test these out, refer to this excellent article for more details.


These steps up to here will complete the setup for the server side. Now, it is time to setup your domain name configurations.

To direct any visitor who enters hi.com or hello.com to your virtual hosts, you will need to add A Record. Take a look at this article for more details.

Essentially, create A Record for hi.com and hello.com to direct to your server's IP address, and apache server will then take care of directing visitors of hi.com to your hi.com virtual host, and visitors of hello.com to the virtual host of hello.com that you have set up above.

*** Note: make sure not to enable forwarding of your domain name to your server. That was my first attempt, and it did not work. You will need to set up A Record instead in order for your apache server to point to appropriate virtual host.

Sunday, November 13, 2016

How to Determine Target Architecture from Library or Executable Files

To determine the target architecture of a library file or executable file, simply type in
$ objdump -x <file> | grep architecture

For example, you could do
$ objdump -x a.out | grep architecture
architecture: i386:x86-64, flags 0x00000012:

So, we now know that it is for x64 architecture!

By the way, if you don't have objdump, you could get it for Debian
$ sudo apt-get install binutils
or for Mac OS X
$ brew install binutils && alias objdump=gobjdump

Wednesday, November 2, 2016

Install Latest Version of OpenCV on Debian from Sources

Here is how to install the latest OpenCV version on Debian from sources. If you are looking for tutorials on Mac OS X, you may want to check out this post.

Before doing anything, make sure to install necessary packages:
$ sudo apt-get install -y build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev

By the way, if you are not sure how to setup sudo in Debian, please take a look here.

Now, download the latest sources from its official Github repository. This will take some time.
$ git clone https://github.com/opencv/opencv.git

Else, you may want to just check out Linux component from here.

Create release folder and run cmake:
$ mkdir opencv/release && cd opencv/release
$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_EXAMPLES=YES ..

For more OpenCV cmake options, take a look here starting at line 171. If you would like to be able to debug the OpenCV library, you will need to compile with debug symbols. This post explains how to do so.

Now, we are ready to compile and install:
$ make -j $(nproc)
$ sudo make install

Let's test and see if you can link the library. Create test.cpp file with the following:
#include <opencv2/core.hpp>
#include <iostream>
using namespace cv;
int main() {
Mat test(3,2,CV_8UC1); 
std::cout << test << std::endl;

return 0;
}

Compile and run:
$ g++ test.cpp $(pkg-config --libs opencv)
$ ./a.out
./a.out: error while loading shared libraries: libopencv_shape.so.3.1: cannot open shared object file: No such file or directory

OK. This is because ldconfig hasn't been updated.
$ sudo ldconfig
$ ./a.out
[ 10,  60;
  71,   0;
   0,   0]

Enjoy!

How to Install VirtualBox Guest Additions on Debian

VirtualBox Guest Additions provides many features, yet it may not be easy to install on Debian system. Here is how to install Guest Additions on Debian guest machine.

In the guest Debian system, insert Guest Additions image by selecting Devices->Insert Guest Additions CD Image from VirtualBox menu. This will insert the image into the guest machine. 

The Debian system will automatically mount the image to /media/cdrom folder. Let's run it:
$ su -
Password:
# cd /media/cdrom
# ./VBoxLinuxAdditions.run
-su: ./VBoxLinuxAdditions.run: Permission denied

This is rather interesting. Permission denied even for root. By the way if you want to run sudo command instead of su in Debian, refer to this tutorial.

The reason for this is actually because the Guest Additions image has been mounted with noexec flag.

# mount | grep cdrom
/dev/sr0 on /media/cdrom0 type iso9660 (ro,nosuid,nodev,noexec,relatime,user)

As clearly seen, the Guest Additions CD image has been mounted with noexec flag set. That is why you couldn't run it even as root. Let's mount it again without noexec flag.

# cd / && mount -t iso9660 /dev/sr0 /media/cdrom
mount: /dev/sr0 is write-protected, mounting read-only
# mount | grep cdrom
/dev/sr0 on /media/cdrom0 type iso9660 (ro,relatime)

OK. The Guest Additions image has been mounted successfully. Let's run the install script;
# /media/cdrom/VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 5.1.8 Guest Additions for Linux...........
VirtualBox Guest Additions installer
Copying additional installer modules ...
Installing additional modules ...
vboxadd.sh: Building Guest Additions kernel modules.
Failed to set up service vboxadd, please check the log file
/var/log/VBoxGuestAdditions.log for details.

Well, let's examine the log file:
# cat /var/log/VBoxGuestAdditions.log
vboxadd.sh: failed: Look at /var/log/vboxadd-install.log to find out what went wrong.
vboxadd.sh: failed: Please check that you have gcc, make, the header files for your Linux kernel and possibly perl installed..

As the log file states, we need to install some necessary packages first, because it needs to compile the Guest Additions from sources.
# apt-get update
# apt-get install -r gcc make linux-hearders-$(uname -r)

Finally, we are ready to install Guest Additions:
# /media/cdrom/VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 5.1.8 Guest Additions for Linux...........
VirtualBox Guest Additions installer
Removing installed version 5.1.8 of VirtualBox Guest Additions...
Copying additional installer modules ...
Installing additional modules ...
vboxadd.sh: Building Guest Additions kernel modules.
vboxadd.sh: Starting the VirtualBox Guest Additions.

You may need to restart the the Window System (or just restart the guest system)
to enable the Guest Additions.
# reboot

You may want to reboot for this to take effect. Enjoy virtual Debian system!

Saturday, October 29, 2016

How to Disable Annoying Paste Function of Mouse Middle Button

If there is one thing I really hate about my current GNOME desktop environment is its default paste function mapped to the mouse middle button. This is simply so annoying that I was looking for a way to get rid of this. After some trials, I have found one that actually works very well, and I would like to share it with anyone who is also having this problem. This post is based on this and this.

First, install xinput package if already not installed.
$ sudo apt-get install -y xinput

Next, list input devices and look for your mouse:
$ xinput list | grep 'id='
⎡ Virtual core pointer                     id=2 [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer               id=4 [slave  pointer  (2)]
⎜   ↳ Microsoft Microsoft® Nano Transceiver v1.0 id=11 [slave  pointer  (2)]
⎜   ↳ Microsoft Microsoft® Nano Transceiver v1.0 id=12 [slave  pointer  (2)]
⎣ Virtual core keyboard                   id=3 [master keyboard (2)]
    ↳ Virtual core XTEST keyboard             id=5 [slave  keyboard (3)]
    ↳ Power Button                             id=6 [slave  keyboard (3)]
    ↳ Video Bus                               id=7 [slave  keyboard (3)]
...


OK, so it tells me what input devices are connected. Under Virtual core pointer, I see my Microsoft Mouse, which is mapped to 11 and 12. In my case, it was the first device:
$ xinput get-button-map 11
3 2 1 5 4 6 7 8 9 10 11 12 13

The second number represents mapping of the middle button, so I simply disable it by setting it to 0:
$ xinput set-button-map 11 3 0 1

That's it. I now confirm that the middle mouse button no longer functions! Well, I want to keep it this way all the time, so I created a script
$ echo "xinput set-button-map 11 3 0 1" > ~/disable_middle.sh
$ chmod u+x ~/disable_middle.sh

I made it execute every time GNOME starts up by creating diable-middle-button.desktop file in ~/.config/autostart/ folder with the following
[Desktop Entry]
Type=Application
Exec=~/disable_middle.sh
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en_US]=disable-middle-button
Name=disable-middle-button
Comment[en_US]=
Comment=


Now, your mouse middle button will be disable every time you start up GNOME!

Wednesday, October 26, 2016

Solution to "error while loading shared libraries"

I was trying to run a  simple executable that makes use of opencv library, and I encountered an error:
$ ./a.out
./a.out: error while loading shared libraries: libopencv_shape.so.3.1: cannot open shared object file: No such file or directory

I was certainly able to locate the file manually in the proper directory:
$ find / -name libopencv_shape.so.3.1
/usr/local/lib/libopencv_shape.so.3.1

Very interesting. This is probably because I manually compiled and installed opencv3.1.0 from sources. In any case, here is the solution.

First, we need to look for the shared library path. The system dynamic linker locations are specified in /etc/ld.so.conf file, which probably includes .conf files in /etc/ld.so.conf.d/ folder. Each of the .conf files in the folder specifies the system dynamic linker locations, such as /lib/x86_64-linux-gnu.

Also, one can define the shell-variable LD_LIBRARY_PATH to include the directory of the shared library file that needs to be linked.

My case? It was a subtle. I certainly had the library folder included in one of the config files:
$ cat /etc/ld.so.conf.d/libc.conf
# libc default configuration
/usr/local/lib

Yet, I was still getting the error. Why? That's because I needed to manually load config:
$ sudo ldconfig

I guess make install command of opencv did not automatically do this. For more info, please take a look at this document. You also might be interested in loading one-time shared library files without neither of the methods above, from here.

Saturday, October 15, 2016

How to Follow a Symbolic Link All the Way

You may have heavily nested symbolic links, and here is how to find its final destination. For example, if you are looking for the java executable:

$ readlink -f $(which java)

That's it!

Saturday, October 8, 2016

How to Setup a Home Web Server on Debian Jessie

Here is how to setup a home web server on Debian Jessie.

First, install apache web server. This will serve html files.
$ sudo apt-get install -y apahce2

If you haven't configured sudo, please take a look at this post to see how to configure sudo in Debian.

Next, install php5. This will server php files.
$ sudo apt-get install -y php5 libapache2-mod-php5

Now, your default server root directory is /var/www/html. You can add your html and php files here for your server to serve.

Finally, you probably may want to serve html files that embed php code in it. To do this, you need to edit /etc/apache2/mods-enabled/php5.conf file and add the following lines:
<FilesMatch ".+\.html$">
   SetHandler application/x-httpd-php
</FilesMatch>

To reload the config file, restart the server:
$ sudo service apache2 restart

Now, create /var/www/html/test.html file with the following code:
<html>
    <body>
        <h1>HTML file with PHP Code</h1>
        <?php
        echo "This code is run by PHP server";
        ?>
    </body>
</html>

In your web browser, go to http://SERVER_IP_ADDRESS/test.html
You should see the following text if your server is properly configured:
HTML file with PHP Code
This code is run by PHP server

By the way, if you want to override the config setting with .htaccses file, you need to edit
/etc/apache2/apache2.conf file and edit to
<Directory /var/www/>
    Options FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Enjoy your web server!


Saturday, October 1, 2016

How to Reverse Mouse Scroll Direction in Debian and Ubuntu

This post is based on here.

To reverse mouse scroll direction, in case you like natural scrolling direction, edit /usr/share/X11/xorg.conf.d/10-evdev.conf file and add the line highlighted in green:
...
Section "InputClass"
        Identifier "evdev pointer catchall"
        MatchIsPointer "on"
        MatchDevicePath "/dev/input/event*"
        Option "ButtonMapping" "1 2 3 5 4 6 7 8"
        Driver "evdev"
EndSection
...

Restart X11 to take effect!

Thursday, September 15, 2016

How to Open up Ports for Web Server with IPTABLES

I have a personal VPN server that I also want to setup as a web server. The VPN server is configured with iptables to drop all other connections, including TCP 80 (HTTP) and TCP 443 (HTTPS). So, here is how to open up those two ports.

Edit /etc/iptables.rules and insert two lines (green) as shown below:
...
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m conntrack --ctstate INVALID -j DROP
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -j REJECT
-A INPUT -p icmp -j ACCEPT
-A INPUT -p udp --dport 67:68 --sport 67:68 -j ACCEPT
-A INPUT -p tcp --dport 22 -j ACCEPT
-A INPUT -p udp -m multiport --dports 500,4500 -j ACCEPT
-A INPUT -p udp --dport 1701 -m policy --dir in --pol ipsec -j ACCEPT
-A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
-A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
-A INPUT -p udp --dport 1701 -j DROP
-A INPUT -j DROP
-A FORWARD -m conntrack --ctstate INVALID -j DROP
...

Your iptables.rules configuration is probably different from mine, but just make sure to add the two lines in green. Just make sure that these two lines should be inserted before the lines with DROP.

Next, reload the iptable
$ sudo iptables-restore < /etc/iptables.rules

That's it!

How to Extract Attachments from Gmail and Save to Files

This is a follow-up post from my previous post on how to retrieve messages from Gmail.

In order to save attached files, you just need to modify ~/.procmailrc file to read something like:
# First Recipe
:0HB
* ^(From).*(SOMEBODY)
* filename=
* ^Content-Disposition: attachment;
| munpack -q -C /WHERE/TO/SAVE

# Second Recipe
:0
/dev/null

The first recipe will filter out those mails from SOMEBODY with attachment(s) and save the file(s) to /WHERE/TO/SAVE folder. Make sure that you have mpack installed on the system:
$ sudo apt-get install -y mpack

The second recipe will simply discard all messages afterward. Therefore, nothing but the attachments will be saved locally.

Tuesday, September 13, 2016

How to Retrieve Emails from Gmail Periodically and Save as Files in Linux

In this tutorial, I will go over my own attempt to automate a process for fetching gmail and saving as files. This post is heavily based on the tutorial here with some modifications.

IMPORTANT:
In order for this to work, you will need to enable POP in Gmail setting.

You will also need to go to Google Account Security page and disable 2-step verification and turn on the option that allows less secure app.


First, install some necessary software:
$ sudo apt-get install -y fetchmail procmail openssl ca-certificates

Next, create ~/.fetchmailrc file and edit it with the following content
poll pop.gmail.com
with proto POP3
user "GMAIL_USERNAME@gmail.com"
there with password "YOUR_PASSWORD"
is "LINUX_USERNAME" here
mda "/usr/bin/procmail -f %F -d %T"
options
no keep
ssl
sslcertck
sslcertpath /etc/ssl/certs

Note that LINUX_USERNAME should be exactly what you would get from the following command:
$ echo $USER

Since your password is saved as a plain text, you will need to make sure to set read/write flags only for the owner:
$ chmod 600 ~/.fetchmailrc

Now, we need to configure procmail. Create ~/.procmailrc file and edit it with the following content:
# Environment variable assignments
PATH=/bin:/usr/bin:/usr/local/bin
VERBOSE=off                   # Turn on for verbose log
MAILDIR=$HOME/Mail            # Where Procmail recipes deliver
LOGFILE=$HOME/.procmaillog    # Keep a log for troubleshooting.
# Recipes
:0:
* ^(From).*(SOMEBODY)
$MAILDIR/SOMEBODY

This configuration will have procmail filter out any mails from SOMEBODY and save the message by appending to the file ~/Mail/SOMEBODY. Make sure to create the folder where it will be saved to:
$ mkdir ~/Mail

What about any other messages? They should be saved to path pointed by $MAIL, which we will need to specify. Edit ~/.bashrc to append the following line:
MAIL=/var/spool/mail/$USER && export MAIL

Let the change take effect immediately
$ source ~/.bashrc

Well, looks good. Let's test out. Run
$ fetchmail
2 messages for xxx@gmail.com at pop.gmail.com (3998 octets).
reading message xxx@gmail.com@gmail-pop.l.google.com:1 of 2 (3383 octets) flushed
reading message xxx@gmail.com@gmail-pop.l.google.com:2 of 2 (615 octets) flushed
You have new mail in /var/spool/mail/linuxnme

If your message is sent from SOMEBODY, it will be saved into ~/Mail/SOMEBODY file. If not, it will be saved to /var/spool/mail/$USER file. Open up these files and see if you are receiving the messages.

Finally, to schedule fetchmail every 5 minute, do the following:
$ crontab -e

Append the following line:
*/5 * * * * /usr/bin/fetchmail &> /dev/null

By the way, if you want fetching to run system-wise, edit /etc/crontab file instead.

Monday, August 22, 2016

VirtualBox: Share Files between Mac OS X Host and Windows Guest

VirtualBox supports Shared Folders feature so that one can access files directionally between the host and guest systems. In this post, I will go over how to share files between VirtualBox Windows guess and Mac OS X host.




First, open up VirtualBox, and select your Windows virtual machine. Click on the Settings icon to open up the settings window, and click on Shared Folders tab. 




On the right hand side, click on a small button that reads Adds new shared folder. On the drop down menu for Folder Path, choose Other...




Finally, simply choose the folder in your host system (i.e., Mac OS X) which will be shared with the guest system (i.e., Windows). Check Auto-mount option.




Now, the setting is complete. Fire up your virtual machine, and you should be able to see your shared drive as a network drive when you open up My Computer window. The shared drive address should be \\vboxsrv

Saturday, April 2, 2016

How to Use SUDO in Debian

If you are a long time Ubuntu user who wants to try out Debian for fun, like myself, you may encounter
$ sudo apt-get install vim
-bash: sudo: command not found

This is because by default Debian doesn't come with sudo package. What you will need to do then is to use su command
$ su
Password: [root password]

You should now be able to login as root. Let's install sudo package first
# apt-get install sudo -y

Looks all good. Let's log out root and try sudo again
# exit
exit
$ sudo apt-get install vim
[sudo] password for xxx:
xxx is not in the sudoers file.  This incident will be reported.

OK this is a bit scary. The incident has been logged to/var/spool/mail/xxx file.
Well, how do we then add a user to become a sudoer? First, login as root again and then you run the following
$ su
# adduser xxx sudo
where xxx is the username that you'd like to add to the sudo group.

When done, you will need to re-login with xxx in order for this to take effect. Let's just reboot the system.
# reboot

After the reboot, you should be able to now type in sudo command to do administrative tasks
$ sudo apt-get install vim

By the way, in case you are wondering how to disable local root login in Debian system, just like Ubuntu, this is what you'll need to run the following command as a sudo user
$ sudo passwd -dl root

To enable root account, you will need to
$ sudo passwd root

Thursday, February 18, 2016

Setup SSH Login Email Alert on Ubuntu 14.04 or Debian

Anytime one enables ssh server, the machine will be at great risk from random attempts all around the world. It may be wise to setup an alert mail when someone logs into the machine remotely. In this post, we will look into how to do so.

I will make use of mail.mailutils program to send emails out here, but there are many other alternative mail out packages.
$ sudo apt-get install -y mailutils postfix
When prompted with postfix configuration, just choose the default setting, which is Internet Site.

Next, create a bash script file that will be executed when someone logs in remotely. In this example, I will place it in the /etc/ssh directory.
$ sudo vim /etc/ssh/ssh_alert.sh

Add the following content to the file
#!/bin/bash
# replace with sender's email address
sender="sender_address@some_mail.com"
# replace with recipient's email address
recipient="recipient_address@some_mail.com"
time=$(date)
if [ "$PAM_TYPE" != "close_session" ]; then
# replace with host name
host="ubuntu-server"
subject="SSH Login: $PAM_USER from $PAM_RHOST on $host at $time"

message="SSH login $PAM_USER from $PAM_RHOST at $time on $host"
echo "$message" | mail.mailutils -r "$sender" -s "$subject" "$recipient"
fi

Next, enable execute
$ sudo chmod u+x /etc/ssh/ssh_alert.sh

Now, we need to make sure that the script actually works. To do so, simply run it
$ sudo /etc/ssh/ssh_alert.sh

If you see a message saying that the email was sent successfully, then you can set it up so that a ssh remote login will execute the script and allow the remote login only if the email was successfully sent. To see whether the execution returns successful, type in
$ echo $?
The output of 0 means successful.

When the mail out is successful, open up /etc/pam.d/sshd
$ sudo vim /etc/pam.d/sshd

Add the following line to /etc/pam/sshd
session required pam_exec.so seteuid /etc/ssh/ssh_alert.sh

That's it. You should now receive the email when someone logs into the server through ssh.

Saturday, October 10, 2015

Enable vim Coloring, Auto Indentation, Line Numbering, Search Highlighting

If you are using vim as your main editor, you may like to enable some syntax coloring and auto indentation when programming. Here is how you can do it.


Install vim on Ubuntu first. Ubuntu only ships with vi, not vim, so install vim
$ sudo apt-get install vim


Next, set the vim preference so that it loads up every time vim is executed
$ vim ~/.vimrc
This will open up the .vimrc file on your home directory that will be executed whenever vim is loaded up.


To edit the file, press i keystroke, which will switch to the insert mode. Write out
syntax on 
set nu
filetype plugin indent on
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
set hlsearch


To save, press ESC keystroke, and enter
:wq
which will write (w) the file and quit (q).


That's it. syntax on turn on syntax coloring, set nu will turn on line numbering, and the last line filetype plugin indent on will turn on automatic indentation, which is quite handy when programming.


Let's write helloworld program in c using vim
Create helloworld.c file in the home directory by running the following commands in terminal
$ cd ~
$ vim helloworld.c


When the vim opens up, press i keystroke again to switch to insert mode
Enter the c code
#include <stdio.h>
int main () {
     printf("Hello World!\n");
     return 0;
}
Notice the auto indentation feature!



Again, press ESC key, and enter the following to save and quit vim
:wq


Let's compile using gcc and run it
$ gcc helloworld.c
$ ./a.out


Great to see it works well. Note that the default compiled binary from gcc is a.out. In order to execute the file in the current directory, you simply enter.
$ ./<binary_file_name>


** If you are a Mac OS X user ***
To install vim on Mac OS X, you will first install homebrew and run
$ brew install vim

Also, if you are using a non-Apple keyboard, you probably want to change the configuration of the backspace by appending the following line to ~/.vimrc
set backspace=indent,eol,start