How to Secure Your Apache Server

1.Enable automatic updates

Given that the LAMP stack is based on Linux and that the entire open-source community is working to enhance it, it is also deemed secure. All security updates and patches are accessible as an automatic unattended install on an Ubuntu VPS as soon as they are released in the Ubuntu repos, so make sure you configure your system to automatically install them if you are concerned about security.If you don’t enable this option on your server and don’t manually install the latest upgrades and patches, you’re placing your server at risk of being hacked.

Install the unattended-upgrades package to enable automatic unattended upgrades.

sudo apt-get install unattended-upgrades

Edit the /etc/apt/apt.conf.d/50unattended-upgrades file to specify which package categories should be upgraded automatically.

2. Configure firewall

Another very important aspect of overall security is having a properly set firewall. ufw is Ubuntu’s default firewall configuration tool, and it’s turned off by default. You can use the following commands to enable ufw:

sudo ufw enable

Allow essential services like OpenSSH and Apache to be accessed:

sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 443

It’s simple to grant access to other services. Simply change the port number in the samples above to the port number of the service you wish to enable access to, and you’re done. Even if the machine is rebooted, the firewall rules will remain active.

3. Disable unused services

If you have active services which you are not using, you can simply disable them. For example, if you have service like Dovecot up and running on your server and you are not using it at all, stop and disable the service using the following commands:

sudo systemctl stop dovecot.service
sudo systemctl disable dovecot.service

4. Install Fail2ban

Fail2ban is a service that scans log files for excessive login failures and blocks the IP address that is displaying malicious behaviour. If you don’t use two-factor or public/private authentication techniques on services like OpenSSH, this service comes in handy. Run the following command to install Fail2ban:

sudo apt-get install fail2ban

Make a copy of the default configuration file so you can make modifications without worrying about system updates overwriting them:

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Edit the jail.local file:

sudo nano /etc/fail2ban/jail.local

The [sshd] block should look something like this:

[sshd]

enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 5
bantime = 600

To make the modifications take effect, save the file and restart Fail2ban:

sudo systemctl restart fail2ban.service

Enable Fail2ban on system boot:

sudo systemctl enable fail2ban.service

5. Hide Apache sensitive information

The default Apache setup exposes a great deal of sensitive data that can be used against the service. It’s critical to keep this information secret, therefore make a configuration file for your new settings:

sudo nano /etc/apache2/conf-available/custom.conf

Copy and paste the following text:

ServerTokens Prod
ServerSignature Off
TraceEnable Off
Options all -Indexes
Header unset ETag
Header always unset X-Powered-By
FileETag None

If it isn’t already enabled, enable the Apache headers module:

sudo a2enmod headers

Enable the following settings:

sudo a2enconf custom.conf

To make the modifications take effect, restart Apache:

sudo systemctl restart apache2.service

6. Install and enable mod_security

Mod security is a web application firewall (WAF) that may be added to Apache as a separate module. It can be used to protect a web server from a variety of threats, including SQL injections, session hijacking, cross-site scripting, and malicious user agents. Run the instructions following to install and enable mod security:

sudo apt-get install libapache2-modsecurity2
sudo a2enmod security2

You should setup the module and enable the OWASP ModSecurity Core Rule Set after it has been installed (CRS).

sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

Then, open the /etc/modsecurity/modsecurity.conf file and edit/add the following settings:

SecRuleEngine On
SecResponseBodyAccess Off
SecRequestBodyLimit 8388608
SecRequestBodyNoFilesLimit 131072
SecRequestBodyInMemoryLimit 262144

Save and close the file. Remove the current CRS and download the OWASP CRS by using the following commands:

sudo rm -rf /usr/share/modsecurity-crs
sudo git clone https://github.com/SpiderLabs/owasp-modsecurity-crs.git /usr/share/modsecurity-crs
cd /usr/share/modsecurity-crs
sudo mv crs-setup.conf.example crs-setup.conf

Edit the security2.conf file in /etc/apache2/mods-enabled/security2.conf. It should resemble the following:

<IfModule security2_module>
	SecDataDir /var/cache/modsecurity
	IncludeOptional /etc/modsecurity/*.conf
	IncludeOptional "/usr/share/modsecurity-crs/*.conf"
	IncludeOptional "/usr/share/modsecurity-crs/rules/*.conf
</IfModule>

Finally, to make the modifications take effect, restart Apache:

sudo systemctl restart apache2.service

7. Install and enable mod_evasive

Mod evasive is an Apache module that can prevent DoS (Denial of Service), DDoS (Distributed Denial of Service), and brute-force assaults on the web server. Run the following command to install mod evasive on your server:

sudo apt-get install libapache2-mod-evasive

Open the default configuration file /etc/apache2/mods-enabled/evasive.conf and edit the settings to look like those below:

<IfModule mod_evasive20.c>
	DOSPageCount        5
	DOSSiteCount        50
	DOSPageInterval     1
	DOSSiteInterval     1
	DOSBlockingPeriod   600
	DOSLogDir           "/var/log/mod_evasive"
</IfModule>

The file should be saved and closed. Make a folder for the log files:

sudo mkdir /var/log/mod_evasive
sudo chown -R www-data: /var/log/mod_evasive

Restart Apache:

sudo systemctl restart apache2.service

Tagged : /

Linux security

User accounts

  • Since the beginning of the course, all the examples presented were run
  • using a user account.
  • A user account consists of a username and a password. This identifies the
  • user on the system and, hence, maintains security and accountability.
  • Linux also creates groupsfor each user account. A group may contain one or
  • more users, all of them sharing the same permissions.
  • The system administrator account, sometimes called the superuser, is the
  • root. This is the most important account on the system. It must be owned by
  • as a few users as possible because of the vast powers it provides.

The /etc/passwd file

  • This is one of the most important and highly protected system file. It contains various information about the user accounts on the system.
  • Each user account information is contained on a single line. A colon (:) is used to separate different fields from each other. Let’s have a quick look at each one in turn:
    • Username: the string that the user uses for identification. It is a friendly name that is chosen by the system administrator (root) to identify the user. By convention, it is all lowercase characters, it may contain numbers (but cannot start with one), special characters dash (-), udnerscore (_), and – in some distros – the dollar sign ($) at the end.
    • Password: a secret group of characters that should be known only to it’s owner. The /etc/passwd file places an x in this field, indicating that the encrypted password is stored in /etc/shadow file (more on that later).

UID and GID

  • UID: it is short for user id. This is a unique number that identifies the user account on the system. As a matter of fact, Linux security system does not care about the username of the user account; it works by examining the its UID to provide the appropriate permissions and access rights. Since there are user accounts that are reserved for system accounts, those are assigned UID numbers from 0 (which is the root account) up till 500 (they reach 1000 in some systems). The higher numbers are assigned to normal (non-system) user accounts.
  • GID: short for group id, it is the unique number that identifies a group account. A group contain one or more users that share similar access rights. The main purpose of the existence of groups is to provide certain users with access to specific files and directories while preventing others. Think of a directory on which a team of users are working. Putting those users in a group ensures that all of them will have the same permissions.

The comment and the home directory

  • The comment field normally includes the user’s real name. For example, when a username is jdoe, the real name in the comment could be John Doe. It may also contain other personal information like the phone number, address and others.
  • The home directory field contains the path to the user’s home directory. Only the user is the owner of his/her home directory. At the command line, a home directory can be referred to as tilde ~. For example, cd ~ will make you navigate to your home directory.

The default shell

  • We have mentioned before that bash is not the only shell available for Linux. There are other shells that are available for Linux like ksh, zsh, tsh and so on. The shell field contains the path to the binary file of the specific shell. For example, /bin/bash.
  • The default shell is a matter of choice. A user can change hi/her default shell.
  • Since all users (including system accounts) must have a default shell. But system accounts – by nature – do not (and should not) have login access to the system. Accordingly, the default shell of such accounts is set to /sbin/nologin. Setting the default shell to /bin/nologin prints a friendly message explaining that logins with this account are not available. Setting it to /bin/false denies login without displaying that message.

The /etc/shadow file

  • You might think that a file named /etc/passwd should be the one containing the hashed passwords of the users on the system.
  • Actually this was the case long ago. But for security reasons, and since /etc/passwd file must be readiable by all users on the system to be able to authenticate them, the hashed password was removed from that file and placed in a more secured file: /etc/shadow .This file has higher level of protection and access restrictions.
  • It contains the following information:
    • The salt: this is a random input that helps make the password more protected
    • The hash: the result of an irreversible mathematical operation. It is performed on the password and the salt combined. To authenticate a user, a hash is computed for the entered password, with the salt input added to it. If both hashes are identical the user is authenticated.
    • Password history: these are some variables that help increase user security. For example, the password must be changed after a specific number of days (configured by the system administrator).

/etc/shadow fields

  • The username: this is the username of the user and not the UID. It is what links /etc/passwd with /etc/shadow
  • The password: the salted hash of the user password. If this field contains as asterisk or an exclamation mark, this means that the account is locked.
  • Last password change: this is the date of the last password change. The UNIX timestamp is used here. UNIX timestamp is a date/time measurement method. It is the amount of time that passed since POSIX time (1/1/1970 at midnight). This field contains the number of days that passed since POSIX time.
  • The number of days till a password can be changed. This is another security measure that prevents users from changing their passwords (as per policy) and then quickly setting it back to the original one.
  • The number of days before a user must change the current password. This is sometimes referred to as password age.
  • The number of warning days before a password expires. During those days, a warning message will be displayed to the users whose account will expire soon.
  • Days between expiration and deactivation: if configured, the account can be deactivated after it’s expired. The difference is that when the account expires, the password is not erased and the account can be activated again by the system administrator or by the user logging in and changing the password. But if the account is deactivated, the password is deleted and only the system administrator can reactivate the account.
  • Expiration date: the date when the account expires, expressed as the number of days since POSIX time.
  • Special flag: this field is currently not used. It is reserved for future use.
  • Notice that some day fields may contain either -1 or 9999, which effectively means that the relevant feature is disabled
Tagged : /

Complete Referance of Blade in Laravel

What is Blade?

Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates.

Blade template files use the .blade.php file extension and are typically stored in the resources/views directory

Blade Template

Displaying Data – You may display data that is passed to your Blade views by wrapping the variable in curly braces.

Blade’s {{ }} echo statements are automatically sent through PHP’s htmlspecialchars function to prevent XSS attacks.

Example:- {{$name}}

Calling Function – You may also echo the results of any PHP function by wrapping the function name in curly braces.

Example:- {{ time( ) }}

Note – You can put any PHP code you wish inside of a Blade echo statement.

Comment

Blade also allows you to define comments in your views. However, unlike HTML comments, Blade comments are not included in the HTML returned by your application.

{{– This comment will not be present in the rendered HTML –}}

Conditional Directives

If Directive

If.. Else.. Directive

If… elseif… else… Directive

Empty Directive

Authentication Directives

Auth Directive

Guest Directive

Tagged : /

Complete Referance of Controller in Laravel

Controllers

Controllers can group related request handling logic into a single class. Instead of defining all of your request handling logic as Closures in route files, you may wish to organize this behavior using Controller classes.

Controllers are stored in the app/Http/Controllers directory.
Controller extends the base Controller class included with Laravel.

Defining Controller Class

Run Command:- php artisan make:controller

Example:- php artisan make:controller AboutController

Path:- app/Http/Controllers/AboutController.php

Creating Route for Controller Class

Path of Controller :- app/Http/Controllers/AboutController.php

Path of Route:- routes/web.php

Syntax:- Route::get(‘uri’, [ControllerName::class, ‘method_name’]);

Passing Data from Controller to View

Path of Controller :- app/Http/Controllers/AboutController.php

Path of Route:- routes/web.php

Path of View:- resources/views/aboutme.blade.php

Multiple Methods inside Controller

Path of Controller :- app/Http/ControllersAboutController.php

Path of Route:- routes/web.php

Path of aboutme blade file:- resources/views/aboutme.blade.php

Path of aboutyou blade file:- resources/views/aboutyou.blade.php

Single Action Controller

If you would like to define a controller that only handles a single action, you may place a single __invoke method on the controller.

Run Command:- php artisan make:controller ShowAbout –invokable

Path of Controller :- app/Http/Controllers/ShowAboutController.php

Path of Route:- routes/web.php

Path of aboutme blade file:- resources/views/aboutme.blade.php

Tagged : /

Complete Reference of view in Laravel

What is View?

Views contain the HTML served by your application and separate your application logic from your presentation logic. Views are stored in the resources/views directory.

Creating View

resources/views/aboutme.blade.php

Create Route for View

Syntax:-

Route::get(‘uri’, function(){return view(‘view_name’)});

Example:-

Route::get(‘about', function () {
    return view(‘aboutme');
});

If your route only needs to return a view, you may use the Route::view method.
Syntax:- Route::view(‘uri’, ‘view_name’);
Example:- Route::view(‘about’, ‘aboutme’)

How to add placeholder to select2.js

Single select placeholders

<select class="js-example-placeholder-single js-states form-control">
  <option></option>
</select>

$(".js-example-placeholder-single").select2({
    placeholder: "Select a state",
    allowClear: true
});

Multi-select placeholders

<select class="js-example-placeholder-multiple js-states form-control" multiple="multiple"></select>
$(".js-example-placeholder-multiple").select2({
    placeholder: "Select a state"
});

Using placeholders with AJAX

Select2 supports placeholders for all configurations, including AJAX. You will still need to add in the empty <option> if you are using a single select.

When using Select2 in single-selection mode, the placeholder option will be passed through the templateSelection callback if specified. You can use some additional logic in this callback to check the id property and apply an alternative transformation to your placeholder option:

$('select').select2({
  templateSelection: function (data) {
    if (data.id === '') { // adjust for custom placeholder values
      return 'Custom styled placeholder text';
    }

    return data.text;
  }
});
Tagged : /

How to redirect non-www URLs to www?

To redirect your website from non-www to www, add the following lines in your website’s .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]

Replace yourdomain.com with your actual domain name.