About Darian Brown

http://www.darian-brown.com

Posts by Darian Brown :

Successful SU For Nobody By Root?

Successful su for nobody by root?

If you are looking through you auth log files you may notice entries saying “session opened for user nobody”. What could this mean and is your server being compromised?

Feb 23 06:25:02 the-cave su[16451]: Successful su for nobody by root
Feb 23 06:25:02 the-cave su[16451]: + ??? root:nobody
Feb 23 06:25:02 the-cave su[16451]: pam_unix(su:session): session opened for user nobody by (uid=0)
Feb 23 06:25:02 the-cave su[16451]: pam_unix(su:session): session closed for user nobody
Feb 23 06:25:02 the-cave su[16453]: Successful su for nobody by root
Feb 23 06:25:02 the-cave su[16453]: + ??? root:nobody
Feb 23 06:25:02 the-cave su[16453]: pam_unix(su:session): session opened for user nobody by (uid=0)
Feb 23 06:25:03 the-cave su[16453]: pam_unix(su:session): session closed for user nobody

Session Opened For User Nobody

Any services that run as a daemon on the server need to be run by a user. Nobody is a system user that is used to run various services. Apache, MySQL, cron and other services will but run as the user nobody.

How Is It Initiated

When one of these services need to run a task, that task will be initiated and the process is then passed to user nobody which then completed the process.

PHP Ping Script Video Tutorial

Webucator, a provider of online and onsite business and technical training, contacted me and asked if they use my php ping script article as a basis for a new training video. The video would be added to their list of PHP courses. I allowed them to use the php ping script as part of their video and a few days later I was sent a link to the newly created php ping script video.

After watching the video Webucator created, I was was truly amazed and it had surpassed all my expectations. Webucator have managed to perfectly convert the written article into an easy to understand, fully comprehensive and simple to follow php tutorial video.

I was impressed with how much detail the above php video tutorial encompassed. The video covers each of the different php ping scripts, and perfectly explains how each of the php ping scripts work. They also highlighted the strengths and usefulness of the each script as well as demonstration a working version of each script.

The video also pays attention to vital parts of each script, such as:

  • Why you should escape arguments passed to the ping script.
  • The situations in which each ping script is most useful.
  • Which ping script you should be using if the website is blocking icmp packets.

Take a look at the video and check out their other training videos. It will be well worth your time.

Grant Privileges To User in MySQL

Overview

If you would like to add a user to MySQL and give them permissions to view on or multiple databases, then continue reading. It is a fairly simple process and can be very powerful in keeping your database secure as well as giving people the access to the database they need.

Login To MySQL Server

In order to run these sql commands (sql queries), login to your sql database so we can take a look at the format of the MySQL command.

mysql -u <user> -p

I recommend you don’t enter your password above as people viewing your bash history would see your password. Once you hit enter you will be prompted to enter your password.

Grant Privileges To User in MySQL

Now the format of the grant appears as follows

GRANT <privilege-type> ON <database> TO <user>@`<ip-or-domain>` IDENTIFIED BY '<new-password>'

Here is the breakdown of what each of the variables means.

  • privilege-type: type of privileges to give such as INSERT, DELETE, ALTER, DROP, ALL PRIVILEGES, etc.
  • database: the database/table combination your are giving the user access to (see below for examples).
  • user: username of your choice that the user will use to login to view their databases.
  • ip-or-domain: the location where the user is access the database FROM.
  • new-password: password of your choice that the user will use to login to view their databases.

 

MySQL GRANT Privileges Examples

Example 1: Gives the user `poweruser` full access to all databases and tables. The *.* means all databases and all tables.

GRANT ALL PRIVILEGES ON *.* TO poweruser@`1.2.3.4` IDENTIFIED BY 'some-pass';

 

Example 2: Create a user with INSERT, DELETE and UPDATE permissions to all tables under the exampledatabase database. They can also only login if they come from the location somedomain.example.com.

GRANT INSERT,DELETE,UPDATE ON exampledatabase.* TO `editoruser`@`somedomain.example.com` IDENTIFIED BY 'any-pass';

 

Example 3: Only give delete to a user and they can only access the reports database and the temptable table. The % for their location means they can access it from anywhere and not just a single ip or domain.

GRANT DELETE ON reports.temptable TO `cleanupuser`@`%` IDENTIFIED BY 'their-pass';

 

Example 4: Gives the root user full access but only from the same location as the database. So anyone outside of the server won’t be able to login. Useful if your website is running on the same server as the database and very secure.

GRANT ALL PRIVILEGES ON *.* TO `root`@`localhost` IDENTIFIED BY 'difficult-pass';

 

PHP Get File Extension Quickly

Overview

If you are looking for the quickest way to check a file extension in PHP, then you have reached the best article to read. Perhaps you need to get file extension in PHP of a file that has been uploaded or use php to check a file extension of an existing file on your website. In any case, the below function will show you how to do it in the least amount of code.

PHP Get File Extension Quickly

<?php

$filename = "/home/darian/any.file.name.jpeg";

// get the php file type
$extension = pathinfo($filename, PATHINFO_EXTENSION);

// display the extension: This will echo out ".jpeg"
echo $extension;

?>

How Does The Above Code Work

We use the php function pathinfo() which will take a path (such as “/home/darian/any.file.name.jpeg” in our example) and will return the information about that full path. For example, if we had to run the following code:

$path_info = pathinfo($filename);

It would output an array with information similar to this below

Array
(
    [dirname] => /home/darian
    [basename] => any.file.name.jpeg
    [extension] => jpeg
    [filename] => any.file.name
)

As you can see, the element extension contains the file extension. Now we can speed this function up even further by adding the flag PATHINFO_EXTENSION which tells the function to only return the file extension as a string rather than an array with all the additional information.

Quickest Way To Remove Empty Array Elements PHP

Overview

Here I will show you the quickest way to remove empty values from an array.
The first way is slow but the most logical way of approaching this. Luckily the second example is the quickest and also pretty simple way. Use the second way, trust me, you will love it.

The slow but simple way – don’t use

Here is the most straight forward way of doing this. It works but I will show you a quicker way afterwards.

<?php

// our massive array with set values and empty values
$array = array(...);

foreach( $array as $key => $value )
	if( $value == "" ) unset($array[$key]);

?>

Quickest Way To Remove Empty Array Elements PHP

And here is the quickest way I have found to remove empty array elements php. Below we fetch a list of keys from the array that is empty (using the php function array_keys) and then unset each of those values.

<?php

// our massive array with set values and empty values
$array = array(...);

// get the empty array keys using array_keys
$keys = array_keys($array,"");

// foreach empty key, we unset that entry
foreach ($keys as $k)
	unset($array[$k]);

?>

Simple yet surprisingly quick.

MySQL Copy Table From One Database To Another

Overview

So you are looking at transferring the data of on MySQL Table into another MySQL Table. Migrating data from database to another database table can be surprisingly easier than you would think.

MySQL Copy Table From One Database To Another

The following query will copy all rows from table_one into table_two. In order for this to work correctly, the number of columns must match. It doesn’t matter if the names of the columns are different, so long as the column count is the same.

INSERT INTO `table_two` SELECT * FROM `table_one`;

MySQL Copy Table With Different Number Of Columns

You can also copy data where the column count is different between the two tables. In order to achieve this, your SELECT will have to return the right number of columns as INSERT statement is expecting.
The exciting part of this is that you can filter which results get transferred by using normal MySQL “SELECT WHERE” syntax as you can see in the below example. In the example, we only transfer the records from table one that are LIKE ‘some value’ and limit the transfer to 20 results.

INSERT INTO `table_two` (`column_A`, `column_B`) SELECT `column_C`, `column_D` FROM `table_one` WHERE `column_name` LIKE '%some value%' LIMIT 20;

Important Note

In the above query, you will notice I select column_C and column_D but I insert it into column_A and column_B. This will work fine even thought the column names don’t match. As long as the column count is the same you will be fine. Assuming that you don’t have foreign key conflict or are missing required columns.

Simple as that.

CSS Button Sprite Example

What IS A CSS Button Sprite?

Let me start off by explaining what an image sprite is. A sprite is basically one larger image that is made up of many smaller images. The idea of sprites is that you only need to load one image and then apply it to a smaller div or A tag so only a portion of the large image shows. Then depending on the background position of the image, you will only see one of the smaller images. This tutorial will be useful if you want to create button sprites, menu sprites, sprite animations or any other type of sprites.
If you would like to see an example on using these sprites to create a sprite animation, check out the sprite animation tutorial.

CSS Button Sprite Example

Below is showing you a css button sprite. This article will show you how to create this button sprite.
 

Above is the finished example of what this tutorial will show you. Mouse over this sprite button image and see how it works and bear in mind that we are only using one image to create the rollover effect. The button is actually an A (anchor) tag that has a height 32px which is half of the image sprite height. This way, only the top half of the image shows which is the up state part of the image.

Why should you use css sprites?

Before images and css items can be displayed on your webpage, your browser must request the item such as javascript files, images, css files, etc. Each request takes time and your browser must wait for a response and then download the file for it to be displayed. So in short, the less items means less time to request and download items, meaning less time to load a page. So using sprites will increase the speed at which your website loads.

Button Sprite

Button Sprite

Above is the css button sprite image I made to create the above button sprite with it’s two states. Normal state when it is untouched and second state is the hover state for when we mouse over it. Notice that the one image contains both up and down states and then as we mouse over it, we use css to adjust the background position of the image sprite to make it appear that the button state is changing.

Now for the code to get this all working

CSS Code

<style>
/* css to style the button */
#rollover {
	background: #FFF url("images/sprite.png");
	width: 180px;
	height: 32px;
	display: block; /* can use inline-block instead of block */
}
/* hover is trigger when we mouse over the A (anchor) tag and adjust the
	background position of the sprite to make it appear the button is down */
#rollover:hover {
	background-position: 0 -32px;
}
</style>

HTML Code

Next the html A (anchor) tag we apply the rollover button style to.

<a href="#-" id="rollover"> </a>

Now when we mouse over, it will appear that the button is changing states. Image sprites aren’t only for buttons, but can be used for rollover menus, animations, or anything that has multiple display states.

Logrotate Set File Permissions

Overview

If you have ever wondered why your log files randomly change permissions each night. Logrotate could be up to its tricks. Similar to the other article I published on Why is apache randomly restarting which explains why logrotate could be causing apache to restart randomly.

Logrotate Set File Permissions

Each time logrotate runs its course, it will compress, rename and remove older files. Remember that a rename is essentially just a ‘move’ operation. This causes some of your log files to no longer exist (since then have been compressed and renamed). Luckily logrotate will attempt to recreate these files and will set some permissions for it.

Post Rotate

Once the logs are rotated, logrotate will execute any commands set in the post rotate part of the script. For example, my logrotate apache config tells it to restart apache.
It restarts apache so apache can recreates any missing log files. Then the permissions that the newly created log files get are determined by the config file for logrotate.

Example Logrotate Apache Config

/var/www/*/logs/*.log {
        weekly
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 640 root adm
        sharedscripts
        postrotate
                /etc/init.d/apache2 reload > /dev/null
        endscript
}

Choosing The Log Permissions

Edit the logrotate apache file which under Debian is usually found under:

vi /etc/logrotate.d/apache2

Inside this file and most logrotate config files, you will see an entry like this

create 640 root adm

This basically tells logrotate to create any missing files, with the permissions of 640 (640 being the standard unix permisson bits) and root as the user with adm as the group.

Simple as that!

Why is Apache Restarting Randomly

Overview

If your apache seems to restart randomly, it can be confusing and difficult to find the issue. I noticed apache on one of my servers was restarting at what seemed like random times.

Why is Apache Restarting Randomly

In my case, Logrotate was to blame and was the cause of the issue. Each time logrotate runs, it will compress, rename and recreate your log file. Furthermore, while rotating your logs it will also remove older logs. Similar to the follow up of this article explaining how to permissions for files that that logrotate creates.

Since the logs files are renamed, it will result in some of your log files to be ‘missing’ since a rename is essentially a ‘move’ operation.

Time To Recreate Apache Log Files

Now that the log files have been renamed, it will recreate the log files. Once the new log files have been created, apache needs to restart so apache can a file pointer to the newly created log files. Logrotate will achieve this by restarting apache, at which point apache will recreate the missing log files.

Example Apache Log Rotate

Here is an example of a logroate apache config. See the section on ‘postrotate’, this is the reason it is restarting apache after each log rotate.

/var/www/*/logs/*.log {
        weekly
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 640 root adm
        sharedscripts
        postrotate
                /etc/init.d/apache2 reload > /dev/null
        endscript
}

PHP Header Force Download Of Files

Overview

In apache, the file type will usually determine how the file is handled. It can opened and displayed in the browser or download, etc. For example, images, css, javascript, php, html (and other types) files are executed and displayed within the browser whereas PDF, ZIP, EXE and other unknown file types will be downloaded by the browser. Usually this behaviour is suitable however we may want to change how certain file types are handled and then force an Image or PHP script file to be downloaded.

PHP Header Force Download Of Files

The below PHP Header code will force any file to be downloaded rather than just being displayed in a browser. You can use this code to force PDF download or to force an Image to download or force download of a javascript file rather than having these file types displayed or executed by the browser.

PHP Header Code To Force File Download

<?php

/* The name of the file we want to force a download */
$filename = 'somefile.html';

/* set our content type to match the file we are downloading */
header("Content-Type: text/html");
/* Tell the browser how big the file is going to be */
header("Content-Length: ".filesize($filename)."\n\n");
/* force the file to be downloaded */
header("Content-Disposition: attachment; filename=$filename");

/* echo out the contents of the file */
echo file_get_contents($filename);

Important Note

Remember that since we are sending headers, we need to make sure that there is no output sent to the browser before the headers are sent. Also, the file mime type should match the file type, such as a mime-type of image/png for PNG files and application/pdf to force a PDF file to download.

Note that you can force the download to have a different name by changing the filename for the Content-Disposition header to the filename of your choice.
For a more complete list of file mime-types, you should visit my article on list of file mime-types. If you would like to learn to to determine the mime-type based on the file extensions, check out this article.