5/13/2016

Airmon-ng: The script can be used to enable monitor mode on wireless interfaces.

Airmon-ng

Description

This script can be used to enable monitor mode on wireless interfaces. It may also be used to go back from monitor mode to managed mode. Entering the airmon-ng command without parameters will show the interfaces status.

Usage

usage: airmon-ng [channel] or airmon-ng
Where:
  • indicates if you wish to start or stop the interface. (Mandatory)
  • specifies the interface. (Mandatory)
  • [channel] optionally set the card to a specific channel.
  • “check” will show any processes that might interfere with the aircrack-ng suite. It is strongly recommended that these processes be eliminated prior to using the aircrack-ng suite. “check kill” will check and kill off processes that might interfere with the aircrack-ng suite. For “check kill” see

Usage Examples

Typical Uses

Check status and/or listing wireless interfaces

~# airmon-ng
PHY Interface Driver  Chipset

phy0 wlan0  ath9k_htc Atheros Communications, Inc. AR9271 802.11n

Checking for interfering processes

When putting a card into monitor mode, it will automatically check for interfering processes. It can also be done manually by running the following command:
~# airmon-ng check
Found 5 processes that could cause trouble.
If airodump-ng, aireplay-ng or airtun-ng stops working after
a short period of time, you may want to kill (some of) them!

  PID Name
  718 NetworkManager
  870 dhclient
 1104 avahi-daemon
 1105 avahi-daemon
 1115 wpa_supplicant
Killing interfering processes
This command stops network managers then kill interfering processes left:
~# airmon-ng check kill
Killing these processes:

  PID Name
  870 dhclient
 1115 wpa_supplicant

Enable monitor mode

Note: It is very important to kill the network managers before putting a card in monitor mode!
~# airmon-ng start wlan0
Found 5 processes that could cause trouble.
If airodump-ng, aireplay-ng or airtun-ng stops working after
a short period of time, you may want to kill (some of) them!

  PID Name
  718 NetworkManager
  870 dhclient
 1104 avahi-daemon
 1105 avahi-daemon
 1115 wpa_supplicant

PHY Interface Driver  Chipset

phy0 wlan0  ath9k_htc Atheros Communications, Inc. AR9271 802.11n
  (mac80211 monitor mode vif enabled for [phy0]wlan0 on [phy0]wlan0mon)
  (mac80211 station mode vif disabled for [phy0]wlan0)
As you can see, it created a monitor mode interface called wlan0mon and it notified there are a few process that will interfere with the tools.

Disable monitor mode

~# airmon-ng stop wlan0mon
PHY Interface Driver  Chipset

phy0 wlan0mon ath9k_htc Atheros Communications, Inc. AR9271 802.11n
  (mac80211 station mode vif enabled on [phy0]wlan0)
  (mac80211 monitor mode vif disabled for [phy0]wlan0mon)
Don't forget to restart the network manager. It is usually done with the following command:
service network-manager start

Madwifi-ng driver monitor mode

This describes how to put your interface into monitor mode. After starting your computer, enter “iwconfig” to show you the current status of the wireless interfaces. It likely looks similar the following output.
Enter “iwconfig”:
 lo        no wireless extensions.
 
 eth0      no wireless extensions.
 
 wifi0     no wireless extensions.
 
 ath0      IEEE 802.11b  ESSID:""  Nickname:""
           Mode:Managed  Channel:0  Access Point: Not-Associated   
           Bit Rate:0 kb/s   Tx-Power:0 dBm   Sensitivity=0/3  
           Retry:off   RTS thr:off   Fragment thr:off
           Encryption key:off
           Power Management:off
           Link Quality:0  Signal level:0  Noise level:0
           Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
           Tx excessive retries:0  Invalid misc:0   Missed beacon:0
If you want to use ath0 (which is already used):
airmon-ng stop ath0
And the system will respond:
 Interface       Chipset         Driver
 
 wifi0           Atheros         madwifi-ng
 ath0            Atheros         madwifi-ng VAP (parent: wifi0) (VAP destroyed)
Now, if you do “iwconfig”:
System responds:
 lo        no wireless extensions.
 
 eth0      no wireless extensions.
 
 wifi0     no wireless extensions.
You can see ath0 is gone.
To start ath0 in monitor mode: airmon-ng start wifi0
System responds:
 Interface       Chipset         Driver
 
 wifi0           Atheros         madwifi-ng
 ath0            Atheros         madwifi-ng VAP (parent: wifi0) (monitor mode enabled)
Now enter “iwconfig”
System responds:
 lo        no wireless extensions.
 
 eth0      no wireless extensions.
 
 wifi0     no wireless extensions.
 
 ath0      IEEE 802.11g  ESSID:""  
        Mode:Monitor  Frequency:2.452 GHz  Access Point: 00:0F:B5:88:AC:82   
        Bit Rate=2 Mb/s   Tx-Power:18 dBm   Sensitivity=0/3  
        Retry:off   RTS thr:off   Fragment thr:off
        Encryption key:off
        Power Management:off
        Link Quality=0/94  Signal level=-96 dBm  Noise level=-96 dBm
        Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
        Tx excessive retries:0  Invalid misc:0   Missed beacon:0
You can see ath0 is in monitor mode. Also make sure the essid, nickname and encryption have not been set. The access point shows the MAC address of the card. The MAC address of the card is only shown when using the madwifi-ng driver. Other drivers do not show the MAC address of the card.
If ath1/ath2 etc. is running then stop them first prior to all the commands above:
 airmon-ng stop ath1
You can set the channel number by adding it to the end: airmon-ng start wifi0 9

Usage Tips

Confirming the Card is in Monitor Mode

To confirm that the card is in monitor mode, run the command “iwconfig”. You can then confirm the mode is “monitor” and the interface name.
For the madwifi-ng driver, the access point field from iwconfig shows your the MAC address of the wireless card.

Determining the Current Channel

To determine the current channel, enter “iwlist channel”. If you will be working with a specific access point, then the current channel of the card should match that of the AP. In this case, it is a good idea to include the channel number when running the initial airmon-ng command.

BSSIDs with Spaces, Special Characters

See this FAQ entry on how to define your BSSID if it has spaces, quotes, double quotes or special characters in it.

How Do I Put My Card Back into Managed Mode?

It depends on which driver you are using. For all drivers except madwifi-ng:
airmon-ng stop 
For madwifi-ng, first stop ALL interfaces:
airmon-ng stop athX
Where X is 0, 1, 2 etc. Do a stop for each interface that iwconfig lists.
Then:
wlanconfig ath create wlandev wifi0 wlanmode sta
For mac80211 drivers, nothing has to be done, as airmon-ng keeps the managed interface alongside the monitor mode one (mac80211 uses interface types rather than modes of operation). If you no longer need the monitor interface and want to remove it, use the following:
airmon-ng stop monX
X is the monitor interface number - 0 unless you run multiple monitoring interfaces simultaneously.

Usage Troubleshooting

General

Quite often, the standard scripts on a linux distribution will setup ath0 and or additional athX interfaces. These must all be removed first per the instructions above. Another problem is that the script set fields such as essid, nickname and encryptions. Be sure these are all cleared.

Airmon-ng says the interface is not in monitor mode

~# airmon-ng stop wlan0mon
PHY Interface Driver  Chipset

phy0 wlan0mon ath9k_htc Atheros Communications, Inc. AR9271 802.11n

You are trying to stop a device that isn't in monitor mode.
Doing so is a terrible idea, if you really want to do it then you
need to type 'iw wlan2mon del' yourself since it is a terrible idea.
Most likely you want to remove an interface called wlan[0-9]mon
If you feel you have reached this warning in error,
please report it.
It most likely mean the interface mode was changed from monitor to managed mode by a network manager. In this case, when stopping monitor mode, this is not a problem.

My interface was put in monitor mode but tools says it is not

It usually means the interface was put in monitor mode prior to killing network managers. And the network manager put the card back in managed mode.
Refer to the documentation above to kill network managers and put it back into monitor mode.

Interface athX number rising (ath0, ath1, ath2.... ath45..)

The original problem description and solution can be found in this forum thread.
Problem: Every time the command “airmon-ng start wifi0 x” is run, a new interface is created as it should, but there where two problems. The first is that for each time airmon-ng is run on wifi0 the interface number on ath increases: the first time is ath1, the second ath2, the third ath3, and and so on. And this continues so in a short period of time it is up to ath56 and continuing to climb. Unloading the madwifi-ng driver, or rebooting the system has no effect, and the number of the interface created by airmon-ng continues to increase.
The second problem is that if you run airmon-ng on wifi0 the athXX created does not show as being shown as in Monitor mode, even though it is. This can be confirmed via iwconfig.
All these problem related to how udev assigns interface names. The answer is in this ticket: http://madwifi-project.org/ticket/972#comment:12Thanks to lucida. The source of the problem comes from the udev persistent net rules generator.
Each distro is different… So here is a solution specifically for Gentoo. You should be able to adapt this solution to your particular distribution.
Gentoo 2.6.20-r4 Udev 104-r12 Madwifi 0.9.3-r2 Aircrack-ng 0.7-r2
Solution:
Change the file /etc/udev/rules.d/75-persistent-net-generator.rules
From: KERNEL==“eth*|ath*|wlan*|ra*|sta*…….. To: KERNEL==“eth*|Ath*|wlan*|ra*|sta*…….
In other words, you just capitalize the a. ath* becomes Ath*. Save the file.
Now delete the file /etc/udev/rules.d/70-persistent-net.rules.
Remove the driver and insert back.
Removing ath also works: KERNEL==“eth*|wlan*|ra*|sta*….
This is also on Gentoo, both 2.6.19-gentoo-r5 and 2.6.20-gentoo-r6
For Ubuntu, see this Forum posting. The modified version of /etc/udev/rules.d/75-persistent-net-generator.rules is:
 # these rules generate rules for persistent network device naming
 
 ACTION=="add", SUBSYSTEM=="net", KERNEL=="eth*|Ath*|wlan*|ra*|sta*" \
NAME!="?*", DRIVERS=="?*", GOTO="persistent_net_generator_do"
 
 GOTO="persistent_net_generator_end"
 LABEL="persistent_net_generator_do"
 
 # build device description string to add a comment the generated rule
 SUBSYSTEMS=="pci", ENV{COMMENT}="PCI device attr{vendor}:$attr{device}($attr{driver})"
 SUBSYSTEMS=="usb", ENV{COMMENT}="USB device 0x$attr{idVendor}:0x$attr{idProduct}($attr{driver})"
 SUBSYSTEMS=="ieee1394", ENV{COMMENT}="Firewire device $attr{host_id})"
 SUBSYSTEMS=="xen", ENV{COMMENT}="Xen virtual device"
 ENV{COMMENT}=="", ENV{COMMENT}="$env{SUBSYSTEM} device ($attr{driver})"
 
 IMPORT{program}="write_net_rules $attr{address}"
 
 ENV{INTERFACE_NEW}=="?*", NAME="$env{INTERFACE_NEW}"
 
 LABEL="persistent_net_generator_end"

Interface ath1 created instead of ath0

This troubleshooting tip applies to madwifi-ng drivers. First try stopping each VAP interface that is running (“airmon-ng stop IFACE” where IFACE is the VAP name). You can obtain the list from iwconfig. Then do “airmon-ng start wifi0”.
If this does not resolve the problem then follow the advice in this thread.

Why do I get ioctl(SIOCGIFINDEX) failed?

If you get error messages similar to:
  • Error message: “SIOCSIFFLAGS : No such file or directory”
  • Error message: “ioctl(SIOCGIFINDEX) failed: No such device”

Error message: "wlanconfig: command not found"

If you receive “wlanconfig: command not found” or similar then the wlanconfig command is missing from your system or is not in the the path. Use locate or find to determine if it is on your system and which directory it is in.
If it is missing from your system then make sure you have done a “make install” after compiling the madwifi-ng drivers. On Ubuntu, do “apt-get install madwifi-tools”.
If it is not in a directory in your path then move it there or add the directory to your path.

airmon-ng shows RT2500 instead of RT73

See this entry under installing the RT73 driver.

Error "add_iface: Permission denied"

You receive an error similar to:
 Interface       Chipset         Driver
 
 wlan0                   iwl4965 - [phy0]/usr/sbin/airmon-ng: line 338: /sys/class/ieee80211/phy0/add_iface: Permission denied
                               mon0: unknown interface: No matching device found
                               (monitor mode enabled on mon0)
or similar to this:
 wlan0   iwlagn - [phy0]/usr/local/sbin/airmon-ng: 856: cannot create /sys/class/ieee80211/phy0/add_iface: Directory nonexistent
 Error for wireless request "Set Mode" (8B06) :
  SET failed on device mon0 ; No such device.
 mon0: ERROR while getting interface flags: No such device
This means you have an old version of airmon-ng installed. Upgrade to at least v1.0-rc1. Preferably you should upgrade to the latest SVN version. See the installation page for more details. Also, don't forget you need to be root to use airmon-ng (or use sudo).

check kill fails

Distros from now on are going to adopt 'upstart' which is going to replace the /sbin/init daemon which manages services and tasks during boot.
Basically do:
 service network-manager stop
 service avahi-daemon stop
 service upstart-udev-bridge stop
and then proceed with greping and killing the pids of dhclient and wpa_supplicant.
This is the only way to kill ALL of the potentially problematic pids for aireplay-ng permanently. The trick is the kill the daemons first and then terminate the 'tasks'.

SIOCSIFFLAGS: Unknown error 132

If you have an output similar to:
# airmon-ng start wlan0
Interface Chipset  Driver
wlan0  Broadcom b43 - [phy0]SIOCSIFFLAGS: Unknown error 132
    (monitor mode enabled on mon0)
It indicates that RF are blocked. It needs to be enabled by using the switch on your laptop and/or using the following command:
rfkill unblock all
Source: http://www.aircrack-ng.org/doku.php?id=airmon-ng

How and Why to Sniff Smartphone Network Traffic

How and Why to Sniff Smartphone Network Traffic

by Ben Gross

Smartphone Network Connection Monitoring

Tools for monitoring and modifying connections between web browsers and web servers are essential for debugging, testing, optimizing performance, and assessing vulnerabilities of web-based applications and native applications. Developers, security professionals, and anyone with an interest in gaining insight into the lower levels of web traffic commonly use these tools.
There are many mature options for monitoring connections from desktop machines. Unfortunately, there are fewer tools to monitor connections on smartphones and these tools often require more complex configurations, as the monitoring software must run on a separate device. In this article, I present an overview of tools and methods for monitoring network connections on Smartphones including devices based on Apple’s iOS–iPhone, iPod Touch, iPad), Google’s Android OS, BlackBerry OS, and Symbian. This article focuses on inspecting HTTP and HTTPS traffic, although many of the tools and techniques described work equally well to analyze other protocols.
This article is the first part in a series: The articles in the series include:
  • An overview of the tools and techniques for monitoring smartphone network connection
  • Pros, cons, and limitations for monitoring smartphone network connections
  • Network monitoring for security analysis and self-defense

Why Monitoring is Useful

Potential use cases for monitoring HTTP and HTTPS traffic–the two primary protocols of the Web:
  • Inspecting network traffic often simplifies debugging AJAX XMLHttpRequest requests, compressed content encoding, and cookies.
  • Network connection details such as number of HTTP requests, DNS lookups, cache hits are also valuable for optimizing web application performance.
  • Many tools allow modifying requests and responses to simulate valid and invalid user input when testing applications for vulnerability analysis in addition to monitoring.
  • Network monitoring is an effective way to verify that a smartphone application securely handles user authentication and identify any inappropriate transmission of personally identifiable information such as unique identifiers and location.
  • Inspecting and modifying network traffic is essential for security analysis. For example, searching for Cross Site Scripting (XSS), SQL injection, and path traversal vulnerabilities.

Types of Monitoring Tools

Common network monitoring tools come in four major varieties: browser-based development tools, general purpose packet sniffers and network protocol analyzers, specialized HTTP/HTTPS sniffers, and specialized web proxies for debugging and security analysis.
Each type of tool has advantages and disadvantages, but there is no requirement to use a single type and combinations of tools may offer more power and flexibility. This list is in no way comprehensive, there are many specialized and hybrid tools for monitoring connections.
Two LiveCD Linux distributions contain a large number of tools optimized for penetration testing a subset of which is useful for network connection monitoring. BackTrack Linux is a very well-regarded distribution. AppSecLive the OWASP Live CD Project–soon to be known as the OWASP Web Testing Environment (WTE)–is another respected collection.
See the Top 100 Network Security Tools from SecTools.org provides a larger list.

Configurations for Monitoring

I’ll talk more about the constraints and pros and cons for each option in the second piece of this article, but briefly here are several potential configurations for monitoring.
  • Simulators allow the simplest configurations where the simulator and the monitoring software run on the same machine and share a common network interface.
  • Web proxies are a convenient option as all modern browsers supported them and only require a small change in the browser settings rather than a change in the network configuration.
  • Ad-hoc networks combined with internet connection sharing are one method to gain access to traffic. If the network monitoring host is located between the mobile device and the internet, it will typically require two network interfaces, usually one wired and one wireless.
  • Network hubs are one method to work around the problems with common switched network configurations.

Limitations for Monitoring

There are significant constraints for monitoring network connections. I’m specifically talking about WiFi-based traffic and not cellular traffic. Monitoring cellular traffic is substantially more complicated and requires specialized equipment. In nearly every case, all important web-related traffic will travel over WiFi if the cellular data connection is disabled on the device.
Limited software is one constraint. For example, there is currently no way to run Webkit Web Inspector, Firebug or LiveHTTPHeaders directly on a Smartphone. Limited networking options is adds another constraint as well as added complexity to the monitoring configuration. Typically, smartphones must communicate over wireless connections rather than wired connections, which eliminates some options for monitoring network traffic. Most modern network hardware is switched, which further limits the ability to access the traffic, even when an access point is plugged into a wired network. Additionally, wireless access points protected by WPA/WPA2 encryption employ per-user keys difficulties in sniffing are similar to switched networks.
Finally, monitoring connections encrypted with SSL/TLS also requires more complex configurations. The most straightforward option involves adding a new Certificate Authority to the trusted list in the browser. This effectively creates a man-in-the-middle attack for the browser that allows decryption of the HTTPS traffic. The browser will produce a series of warning messages, but it will be possible to view the encrypted traffic.
Credit:  Ben Gross, PhD

2/12/2016

Xibo Client Player Development


Xibo contains a WSDL that explains the interactions between the player and CMS, and should also provide a Schema for the XLF (the layout XML sent to the player).
I totally agree with you that everyone should be able to make their own client - that would be great. However 99% of the user base have no interest in making their own client, all they want to do is download and use a solution that works and is free (cheap).
That is the ethos Xibo was born with and why we have developed the .NET and Pyclient players - unfortunately the Pyclient player didn't work out and the .NET player is built on ageing technology (I started coding it in 2006!).
What we want is a new client that can run cross platform and has an understanding of XMDS and XLF that rivals the current offerings.
I take your points about building signage that runs within a web page - Xibo started out as a .HTA application in 2004, which we of course abandoned due to all the problems you mentioned. However, Chrome Packaged Apps is a long way from a simple webpage and I have yet to see a better proposition for a client that could integrate well with the way Xibo functions (native content augmented with web content).
We have looked at:
  • Air
  • Python-QT
  • C++
  • WPF
I am happy to work with you on the XMDS specification (the WSDL is a great starting point) and the XLF schema. We will be looking to enhance both XMDS and the XLF schema to support things like monitor control, interactivity, etc, so we will need a detailed map of the current situation before we start anyway.

2/04/2016

Querying MySQL with Node.js

Querying MySQL with Node.js

Node.js is slowly making inroads in normal web development routines. There are a number of modules available for Node to work with almost any requirement you imagine, although the stability of many of them is open to question. Although I’ll surely not switch my development practices to Node from PHP any time soon; for many tasks Node would be a perfect match. For example for one site I use a CRON job to regularly sync remote data to MySQL. Node with its support for asynchronous requests may possibly help me make the data syncing faster.

The following post is a quick look at the MySQL module for Node. There are currently two modules for connecting with MySQL – db-mysql and node-mysql. In this post we will be using node-mysql. Unlike db-mysql, you don’t need to install specialized MySQL client software to work with node-mysql.
I’m assuming you have Node.js installed on your system. If not you can quickly get started at the Node.js site.

Installing node-mysql

The latest version is a alpha release, however despite the fact that it is tagged as ‘alpha’ this is the recommended version to use for new developments as there are many changes to the core API as and these will be carried on to the future versions. Using npm is the best way to install the module.
npm install mysql@2.0.0-alpha3
Once the alpha version becomes stable you will need to download using the normal module name, but till then use the above command.
npm install mysql

Running your first MySQL query

We will be using a WordPress database as an example to grab post titles from the ‘wp_posts’ table. The complete code is shown below.
var mysql = require('mysql');
 
var connection = mysql.createConnection(
    {
      host     : 'localhost',
      user     : 'your-username',
      password : 'your-password',
      database : 'wordpress',
    }
);
 
connection.connect();
 
var queryString = 'SELECT * FROM wp_posts';
 
connection.query(queryString, function(err, rows, fields) {
    if (err) throw err;
 
    for (var i in rows) {
        console.log('Post Titles: ', rows[i].post_title);
    }
});
 
connection.end();
You could also pass the connection options as one single string rather than as an object.
var connection = mysql.createConnection('mysql://user:pass@host/wordpress');
The query results are returned as an array of objects with each row representing a single object in the array. So we need to iterate through the array to print all post titles. The object for a single row is shown below.
{ ID: '21',
  post_author: '1',
  post_date: Fri Feb 27 2009 03:44:07 GMT+0530 (India Standard Time),
  post_date_gmt: Fri Feb 27 2009 03:44:07 GMT+0530 (India Standard Time),
  post_content: 'sample content',
  post_title: 'web scrape',
  post_category: 0,
  post_excerpt: '',
  post_status: 'publish',
  comment_status: 'open',
  ping_status: 'open',
  post_password: '',
  post_name: 'web-scrape',
  to_ping: '',
  pinged: '',
  post_modified: Fri Feb 27 2009 03:44:07 GMT+0530 (India Standard Time),
  post_modified_gmt: Fri Feb 27 2009 03:44:07 GMT+0530 (India Standard Time),
  post_content_filtered: '',
  post_parent: '0',
  guid: 'http://localhost/wp/wordpress/?p=21',
  menu_order: 0,
  post_type: 'post',
  post_mime_type: '',
  comment_count: '0' },
Where we can access each field (post_title shown here) as below.
rows[i].post_title
The ‘query’ method of the connection object requires a callback function which will be executed whenever either one of the three events fires – error, fields, results, here denoted by the parameters err, fields and rows respectively. Here the callback is registered as a anonymous function.
The above code with the callback defined as an anonymous function will return the results as a single data stream. However if there are a large number of rows in the table and you want to process each row as it arrives rather then wating to collect all the rows you can change the code to the following.
var mysql = require('mysql');
 
var connection = mysql.createConnection(
    {
      host     : 'localhost',
      user     : 'your-username',
      password : 'your-password',
      database : 'wordpress',
    }
);
 
connection.connect();
 
var query = connection.query('SELECT * FROM wp_posts');
 
query.on('error', function(err) {
    throw err;
});
 
query.on('fields', function(fields) {
    console.log(fields);
});
 
query.on('result', function(row) {
    console.log(row.post_title);
});
 
connection.end();
Note that each row is written to the console as it arrives. If you need to process the row for some purpose before getting the next row, you will have to pause the query and resume after some processing is done. But beware it is showing inconsistent results with some errors thrown in on my side.
query.on('result', function(row) {
    connection.pause();
    // Do some more processing on the row
    console.log(row);
    connection.resume();
});

Escaping query values

To avoid SQL injection you can escape user data before running the query. There are two methods. One using the ? operator is shown below.
.
.
connection.connect();
 
var key = '_edit_lock'; 
var queryString = 'SELECT * FROM wp_postmeta WHERE meta_key = ?';
 
connection.query(queryString, [key], function(err, rows, fields) {
    if (err) throw err;
 
    for (var i in rows) {
        console.log(rows[i]);
    }
});
 
connection.end();
The other using the connection.escape() method is given below.
.
.
connection.connect();
 
var key = '_edit_lock'; 
var queryString = 'SELECT * FROM wp_postmeta WHERE meta_key = ' + 
                   connection.escape(key);
 
connection.query(queryString, function(err, rows, fields) {
    if (err) throw err;
 
    for (var i in rows) {
        console.log(rows[i]);
    }
});

Closing of connections

Your connection to the MySQL server may close unexpectedly due to an error or you may close it explicitly. If it closes due to some error then you will need to handle that and reopen it if required. The 'close' event is fired when a connection is closed, so we need to handle that.
connection.on('close', function(err) {
  if (err) {
    // Oops! Unexpected closing of connection, lets reconnect back.
    connection = mysql.createConnection(connection.config);
  } else {
    console.log('Connection closed normally.');
  }
});
The connection.config object holds the current connections details which you can use to reconnect back to the MySQL server. Printing the object to the console returns the following.
{ host: 'localhost',
  port: 3306,
  socketPath: undefined,
  user: 'sam',
  password: 'some-pass',
  database: 'wordpress',
  insecureAuth: false,
  debug: undefined,
  typeCast: true,
  maxPacketSize: 0,
  charsetNumber: 33,
  clientFlags: 193487 }

Production usage

So will I be using Node.js for my next project? Absolutely not! The whole Node ecosytem is still standing on shifting sands – Module API’s are changing faster than I can complete a single project. So until the entire thing stabilizes and we have good support tools to make Node development easier, I’d stick to my old and trusted languages. Even then, I’d be using Node.js for specific tasks along with PHP rather than building entire sites using Node alone. But as it usually happens in tech, my last sentence may sound reserved and cautious 3 years from now when probably we will be building entire sites using Node.js.

CREDIT: http://www.codediesel.com/nodejs/querying-mysql-with-node-js/