Home / 2015 / June

Monthly Archives: June 2015

Key Generation in Python

I’m creating a REST API for my current Django project, and I want a good psuedo-random way to generate alpha numeric API keys. Outlined is a simple method which I believe makes pretty good psuedo-random keys.

Like Session keys, API keys should be sufficiently unpredictable to be psuedo-random. To be unpredictable, no user variables (or timestamps) are encoded into the key.

Specifically, the key starts life as a 256bit number generated by the Mersenne Twister Pseudo Random Number Generator (PRNG).

>> str(random.getrandbits(256))
>>90035287577760653301955374895950037116738729760252440482985364146171806313429

Mersenne Twister itself is not considered cryptographically secure (it has been demonstrated that observing a sufficient number of iterates allows one to predict all future iterates).

To mitigate this problem, the 256bit number is cryptographically hashed using SHA-256.

>> hashlib.sha224( str(random.getrandbits(256)) ).hexdigest()
>> 654c6da8f3b0fd8fe819669daf07996738d21a53c02c731b0aee6373

The result is then Base64 encoded – which results in a string containing only lower and upper case alphabetical characters, and numbers – and also two special characters (usually ‘/’ and ‘+’).

A character-pair (eg: ‘aF’ or ‘zZ’) is then selected randomly (pseudo-randomly) from a pool of character-pairs; these are substituted (salted) for the non-alphanumeric characters left by the Base64 encoding.

The resulting string is a 38 character alphanumeric that is sufficiently large and unpredictable for an API key.

>> base64.b64encode(hashlib.sha256( str(random.getrandbits(256)) ).digest(), random.choice([‘rA’,’aZ’,’gQ’,’hH’,’hG’,’aR’,’DD’])).rstrip(‘==’)
>> mwkMqTWFnK0LzJHyfkeBGoS2hr2KG7WhHqSGX0SbDJ4

Fix phpmyadmin on Ubuntu

Your LAMP server not work with phpmyadmin? let’s go fix this problem, before you’ve LAMP server install, if still not install LAMP you can simply install via command

$ sudo apt-get install lamp-server^

What do you mean LAMP ?

LAMP stack is a group of open source software used to get web servers up and running. The acronym stands for Linux, Apache, MySQL, and PHP. Since the virtual private server is already running Debian, the linux part is taken care of. Here is how to install the rest.

when you type address in browser

http://localhost/phpmyadmin/

it show “Page not found”

Now see your “apache2.conf” file

Rasel Khan:~$ cat /etc/apache2/apache2.conf
# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.

# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#	/etc/apache2/
#	|-- apache2.conf
#	|	`--  ports.conf
#	|-- mods-enabled
#	|	|-- *.load
#	|	`-- *.conf
#	|-- conf-enabled
#	|	`-- *.conf
# 	`-- sites-enabled
#	 	`-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections which can be
#   customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
#   directories contain particular configuration snippets which manage modules,
#   global configuration fragments, or virtual host configurations,
#   respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
#   their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.


# Global configuration
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
Mutex file:${APACHE_LOCK_DIR} default

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5


# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf


# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
	Options FollowSymLinks
	AllowOverride None
	Require all denied
</Directory>

<Directory /usr/share>
	AllowOverride None
	Require all granted
</Directory>

<Directory /var/www/>
	Options Indexes FollowSymLinks
	AllowOverride None
	Require all granted
</Directory>

#<Directory /srv/>
#	Options Indexes FollowSymLinks
#	AllowOverride None
#	Require all granted
#</Directory>




# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^.ht">
	Require all denied
</FilesMatch>


#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i"" vhost_combined
LogFormat "%h %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i"" combined
LogFormat "%h %l %u %t "%r" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

Include /etc/phpmyadmin/apache.conf

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

I’ve include this one line, see below at last on the top

Include /etc/phpmyadmin/apache.conf

If you’ve not include this line edit your “apache2.conf” file, I’m using nano editor for file include

Rasel Khan:~$ sudo nano /etc/apache2/apache2.conf

After include this line, you should restart your server

Rasel Khan:~$ sudo service apache2 restart

Now try

http://localhost/phpmyadmin/

it’ll works fine !! 🙂

Fix Skype install problem on Ubuntu

Sometimes your Skype installation problem on Ubuntu, let’s go fix it

Step 1: Remove previous version.

sudo apt-get remove skype skype-bin:i386 skype:i386
sudo apt-get install sni-qt:i386

It is Important if you installed older version of Skype on your Ubuntu, Clear the old Skype folder before installing latest version. Then clear that by using:

rm -rf ~/.Skype

Step 2: Preparing to Installing Skype.

Users of 64-bit Ubuntu, should enable MultiArch if it isn’t already enabled by running the command

    sudo dpkg --add-architecture i386

Update repositories and “updates” list:

    sudo apt-get update

Optional, install GDebi (see below):

    sudo apt-get install gdebi #(read Why you need to install gdebi...)

Step 3: Installing Skype

Method 1: Download and install from file

wget download.skype.com/linux/skype-ubuntu-precise_4.3.0.37-1_i386.deb
sudo gdebi skype-ubuntu-precise_4.3.0.37-1_i386.deb

Method 2: Install Skype from Canonical Partner Repository

So add the Canonical Partner Repository to “updates” list by following the command:

sudo add-apt-repository "deb http://archive.canonical.com/ $(lsb_release -sc) partner"

Then install Skype via the Software-Center or via the Terminal.

sudo apt-get update && sudo apt-get install skype

Broadband connection set up in Ubuntu

If you’have installed Ubuntu 14.04 LTS alongside Windows Xp or Windows 7. Your broadband connection working ok in Windows Xp or 7, but sometimes it is not working in Ubuntu. Let’s go how can you solve this problem, Open your terminal and type ifconfig you’ll see all configuration in your network.

Rasel Khan:~$ ifconfig
eth0      Link encap:Ethernet  HWaddr e0:69:95:12:b0:4c  
          inet addr:10.0.1.86  Bcast:10.0.1.86  Mask:255.255.255.255
          inet6 addr: fec0::b:751e:ae5e:9810:845d/64 Scope:Site
          inet6 addr: fe80::e269:95ff:fe12:b04c/64 Scope:Link
          inet6 addr: 2002:2d74:f8a1:b:e269:95ff:fe12:b04c/64 Scope:Global
          inet6 addr: 2002:2d74:f8a1:b:751e:ae5e:9810:845d/64 Scope:Global
          inet6 addr: fec0::b:e269:95ff:fe12:b04c/64 Scope:Site
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:36202 errors:0 dropped:1 overruns:0 frame:0
          TX packets:14115 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:10454044 (10.4 MB)  TX bytes:2518480 (2.5 MB)
          Interrupt:20 Memory:fe400000-fe420000 

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:2182 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2182 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:115203 (115.2 KB)  TX bytes:115203 (115.2 KB)

Step-1: Open network connections by searching for it in the dash.

Now Click on the Add button.

Step-2: Choose the network type as DSL and then click create.

Step-3: Now type the username and password and save.

You can also choose to connect automatically in the general tab.

If still not working 🙁 , let’s go another way …

Step-1: Open your terminal simply type command sudo pppoeconf you’ll build step by step your network configuration !

Rasel Khan:~ sudo pppoeconf
[sudo] password for khan: 

Step-2: After type your valid password for sudo user then you’ll show for “dsl-provider” configuration..then type “” !

 If you continue with this program, the configuration file          │     
     │ /etc/ppp/peers/dsl-provider will be modified. Please make sure     │     
     │ that you have a backup copy before saying Yes.                     │     
     │                                                                    │     
     │ Continue with configuration?                                       │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                  <Yes>                     <No>        

Step-3: Change your network configuration settings via enter ““for configuration..

 Most people using popular dialup providers prefer the options      │     
     │ 'noauth' and 'defaultroute' in their configuration and remove the  │     
     │ 'nodetach' option. Should I check your configuration file and      │     
     │ change these settings where neccessary?                            │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                                                                    │     
     │                  <Yes>                     <No>     

Step-4: Enter your valid internet(Broadband) connection username (i.e my username “khancse” ) , then “” for continue.. ..

┌────────────────────┤ ENTER USERNAME ├────────────────────┐          
          │ Please enter the username which you usually need for the │          
          │ PPP login to your provider in the input box below. If    │          
          │ you wish to see the help screen, delete the username and │          
          │ press OK.                                                │          
          │                                                          │          
          │ username___khancse_____________________________________________ │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                          <Ok> 

Step-5: Enter your valid internet(Broadband) connection password, then Ok for continue.. .. .

┌────────────────────┤ ENTER PASSWORD ├────────────────────┐          
          │ Please enter the password which you usually need for the │          
          │ PPP login to your provider in the input box below.       │          
          │                                                          │          
          │ NOTE: you can see the password in plain text while       │          
          │ typing.                                                  │          
          │                                                          │          
          │ password________________________________________________ │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                          <Ok>     

Step-6: If you’ve entered valid information for username and password, then you’ll got
useable servers when the connection is established . Enter “” for configuration..

 USE PEER DNS ├─────────────────────┐          
          │                                                          │          
          │ You need at least one DNS IP address to resolve the      │          
          │ normal host names. Normally your provider sends you      │          
          │ addresses of useable servers when the connection is      │          
          │ established. Would you like to add these addresses       │          
          │ automatically to the list of nameservers in your local   │          
          │ /etc/resolv.conf file? (recommended)                     │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │               <Yes>                  <No>  

Step-7: Now need to byte allocation for pppoe clamp MSS, then “” for continue, (If you still get problems described above, try setting to number of byte in the dsl-provider file.)

LIMITED MSS PROBLEM ├───────────────────────┐     
     │                                                                    │     
     │ Many providers have routers that do not support TCP packets with a │     
     │ MSS higher than 1460. Usually, outgoing packets have this MSS when │     
     │ they go through one real Ethernet link with the default MTU size   │     
     │ (1500). Unfortunately, if you are forwarding packets from other    │     
     │ hosts (i.e. doing masquerading) the MSS may be increased depending │     
     │ on the packet size and the route to the client hosts, so your      │     
     │ client machines won't be able to connect to some sites. There is a │     
     │ solution: the maximum MSS can be limited by pppoe. You can find    │     
     │ more details about this issue in the pppoe documentation.          │     
     │                                                                    │     
     │ Should pppoe clamp MSS at 1452 bytes?                              │     
     │                                                                    │     
     │ If unsure, say yes.                                                │     
     │                                                                    │     
     │ (If you still get problems described above, try setting to 1412 in │     
     │ the dsl-provider file.)                                            │     
     │                                                                    │     
     │                  <Yes>                     <No>    

Step-8: Your PPPD is configured now, then “” for continue..

┤ DONE ├─────────────────────────┐          
          │                                                          │          
          │ Your PPPD is configured now. Would you like to start the │          
          │ connection at boot time?                                 │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │               <Yes>                  <No>                │          
          │                                              

Step-9: In this step ESTABLISH A CONNECTION with “dsl-provider”, then “” for continue…After complete all the steps you’ll got your connection !!

 ESTABLISH A CONNECTION ├────────────────┐          
          │                                                          │          
          │ Now, you can make a DSL connection with "pon             │          
          │ dsl-provider" and terminate it with "poff". Would you    │          
          │ like to start the connection now?                        │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │                                                          │          
          │               <Yes>                  <No>   

Check your “dsl-provider” file, you’ll show all configuration with your username, i’m using nano editor .

Rasel Khan:~ sudo nano /etc/ppp/peers/dsl-provider
[sudo] password for khan: 

# Minimalistic default options file for DSL/PPPoE connections

noipdefault
defaultroute
replacedefaultroute
hide-password
#lcp-echo-interval 30
#lcp-echo-failure 4
noauth
persist
#mtu 1492
#persist
#maxfail 0
#holdoff 20
plugin rp-pppoe.so eth0
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@user "khancse"
usepeerdns
user "khancse"

The network applet shows device not managed, but my internet connection works fine.
Enjoy 🙂

Fix WordPress Feed XML Parsing Errors

When you try to Export all content or rss feed in wordpress then it’ll show XML Parsing Error and not working with seo in your site and so was the WordPress source feed which showed “XML Parsing Error: XML or text declaration not at start of entity“. And all this while Google reader was correctly tracking our feed, while it was not loading in any web browser!

XML Parsing Error
Firefox showed this error on loading the feed

XML Parsing Error: XML or text declaration not at start of entity Location: http://www.quickonlinetips.com/archives/feed/ Line Number 2, Column 1: ^

Google Chrome revealed some more information

This page contains the following errors: error on line 2 at column 6: XML declaration allowed only at the start of the document Below is a rendering of the page up to the first error.

I found that it was most commonly caused by a Blank line before XML declaration

Basically this error arises if there is a whitespace before an XML declaration

<?xml ... ?>

appears in your feed. The blank line error means that the code has blank lines in it, which can be easily introduced in the WordPress php code by a plugin, theme, or any configuration file.

So basically I had to go looking for blank lines before PHP starting tag

<?php
and after the PHP closing tag
 ?>

I intended to use the ‘Fix RSS Feed WordPress plugin’ which promised to search all folders (except wp-admin and wp-includes directory) if the php file has blank lines in the head and tail line, and then delete blank lines. The plugin author writes that it will delete php files at only the beginning and end of the blank lines, and will not delete the blank lines between documents, so it will not affect the operation of the php programs.

Now, change your root directory where wp-config.php include, see below

Rasel Khan:~$ cd /var/www/project/wordpress
Rasel Khan:~$ ls
index.php    wp-activate.php     wp-comments-post.php  wp-content   wp-links-opml.php  wp-mail.php      wp-trackback.php
license.txt  wp-admin            wp-config.php         wp-cron.php  wp-load.php        wp-settings.php  xmlrpc.php
readme.html  wp-blog-header.php  wp-config-sample.php  wp-includes  wp-login.php       wp-signup.php

open your ‘index.php’ file via any editor, I’m using gedit editor

Rasel Khan:~$ sudo gedit index.php

Here ‘index.php’ file look

<?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );

Now create a new file called ‘fix-rss.php’ in ‘wp-config.php’ directory and copy the follwing code

<?php
function wp_xml_fix_rss($input) {
	$allowed = false;

	$found = false;

	foreach (headers_list() as $header) {
		if (preg_match("/^content-type:s+(text/|application/((xhtml|atom|rss)+xml|xml))/i", $header)) {
			$allowed = true;
		}

		if (preg_match("/^content-type:s+/i", $header)) {
			$found = true;
		}
	}

	if ($allowed || !$found) {
		return preg_replace("/As*/m", "", $input);
	} else {
		return $input;
	}
}

ob_start("wp_xml_fix_rss");

Finally include ‘fix-rss.php’ file in ‘index.php’, see below look like

<?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
include './fix-rss.php';
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );

It’ll be works ! 🙂
if any problem just comment here………