Dhiraj's Blogs Born to code

17Apr/120

Android APP Lock By-Pass

Posted by PralhadC

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.

14Apr/120

0wn!ng using xp_cmdshell

Posted by Dhiraj Ranka

Background

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?

Impact

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.

Why?

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.

Usage

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

GO

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

RECONFIGURE

GO

-- To enable the feature.

EXEC sp_configure 'xp_cmdshell', 1

GO

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

RECONFIGURE

GO

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

Usage:

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.

Example:

USE master;

xp_cmdshell 'dir'

Output

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

Solution

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

GO

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

RECONFIGURE

GO

-- To disable the feature.

EXEC sp_configure 'xp_cmdshell', 0

GO

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

RECONFIGURE

GO

Conclusion

Use best practices

xp_cmdshell { 'command_string' } [ , no_output ]
14Apr/120

Change Registered User in Windows

Posted by Dhiraj Ranka

Background

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.

Solution

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

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion

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.

Tagged as: No Comments
11Mar/120

Run Code by impersonating user privilege

Posted by Dhiraj Ranka

Background

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.

Problem

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"

Solution

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;

	[DllImport("advapi32.dll")]
	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
				undoImpersonation();
			}
			else
			{
				// 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)
					{
						CloseHandle(token);
						CloseHandle(tokenDuplicate);
						return true;
					}
				}
			}
		}
		if (token != IntPtr.Zero)
			CloseHandle(token);
		if (tokenDuplicate != IntPtr.Zero)
			CloseHandle(tokenDuplicate);
		return false;
	}

	private void undoImpersonation()
	{
		impersonationContext.Undo();
	}
}

Reference

How to implement impersonation in an ASP.NET application

http://support.microsoft.com/kb/306158#3

8Mar/120

Using Directory Services for LOCAL SYSTEM

Posted by Dhiraj Ranka

Background

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.

Problem

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.

Solution

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;
	try
	{
		DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username));
		directoryEntry.Invoke("ChangePassword", new object[] { oldpassword.Text.ToString(), newpassword.Text.ToString() });
		directoryEntry.CommitChanges();
		isSuccess = true;
	}
	catch (Exception ex) { output.Text = ex.Message.ToString(); }
	return isSuccess;
}

Reference

Using directory services and Visual C#
http://support.microsoft.com/kb/306273

Creating DirectoryEntry Component Instances
http://msdn.microsoft.com/en-us/library/x8wxt72e%28vs.71%29.aspx

LDAP Query Basics
http://technet.microsoft.com/en-us/library/aa996205%28v=exchg.65%29.aspx

Other way to reset user password
http://www.codeproject.com/Articles/18602/Reset-Windows-Administrator-Account-Password-in-C

2Mar/120

Runtime Error SharePoint 2010

Posted by Dhiraj Ranka

Background

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.

Problem

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

Solution

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

Conclusion

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.

24Jan/120

Capture DataGridView cell’s KeyPress event

Posted by Dhiraj Ranka

Background

It was a challenge for me to achieve this. So I took it and completed successfully. The question is what was the challenge.The challenge was to capture the KeyPress event of DataGridView Cell.

Problem

How would you achieve this? We can just simply use DataGridView's KeyPress event and move on. Then how would you do it.

Solution

To achieve this we have handle the EditingControlShowing event of the DataGridView which gives us the inner control that current column is holding, so that we can access the desired column of the grid and subscribe the KeyPress event of the editing control. There are following types of columns in DataGridView

  • DataGridViewButtonColumn
  • DataGridViewCheckBoxColumn
  • DataGridViewComboBoxColumn
  • DataGridViewImageColumn
  • DataGridViewTextBoxColumn
  • DataGridViewLinkColumn

We will see how to access DataGridViewTextBoxColumn and add KeyPress event to the same.

void dgvDemo_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
	TextBox txt = e.Control as TextBox;
	if (txt != null)
	{
		txt.KeyPress += new
KeyPressEventHandler(txt_KeyPress);
	}
}

void txt_KeyPress(object sender, KeyPressEventArgs e)
{
	MessageBox.Show(e.KeyChar.ToString());
}

Now that was pretty easy, now in case if you want to do it for a particular column then you can access either with column index or with column name.

With column index

int index = dgvDemo.CurrentCell.ColumnIndex;

With column name

string colName = dgvDemo.CurrentCell.OwningColumn.Name;

This would be very useful when accessing the EditingControl so that we can decide the proper type of the control.

Happy coding :)

16Jan/121

Set ComboBox Item color

Posted by Dhiraj Ranka

Background

Not sure when this is useful, but its handy code to have when developing windows forms applications. The need can arise when we have to color code the data that we are displaying like status, severity, types, etc. As title describes we are going to set the fore ground color every ComboBox item in Windows Forms Application.

Let's Start Coding

Create a Windows Forms Application project

Add a ComboBox on Form.

Most importantly set the ComboBox's DrawMode property to OwnerDrawVariable - if not, we will not be able to see our drawings!

Fill the combobox using following code

private void Form1_Load(System.Object sender, System.EventArgs e)
{
	string col = null;
	foreach (string c in System.Enum.GetNames(typeof(System.Drawing.KnownColor)))
	{
		col = c;
		ComboBox1.Items.Add(Color.FromName(col));
	}
}

Then add DrawItem evet definition for combobox and add following code to it.

private void cmbExpTypes_DrawItem(object sender, DrawItemEventArgs e)
{
	if (e.Index < 0)
	{
		e.DrawBackground();
		e.DrawFocusRectangle();
		return;
	}
	// set default color
	Color CurrentColor = Color.Red;

	// get a square using the bounds height
	Rectangle SizeRect = new Rectangle(2, e.Bounds.Top + 2, e.Bounds.Width, e.Bounds.Height - 2);

	Brush ComboBrush = Brushes.Blue;

	// call these methods first
	e.DrawBackground();
	e.DrawFocusRectangle();

	// change brush color if item is selected or you can add you own condition based on item values
	if (e.State == System.Windows.Forms.DrawItemState.Selected)
	{
		ComboBrush = Brushes.White;
	}
	else
	{
		ComboBrush = Brushes.Blue;
	}

	// draw a rectangle and fill it
	//e.Graphics.DrawRectangle(new Pen(CurrentColor), SizeRect);
	//e.Graphics.FillRectangle(new SolidBrush(CurrentColor), SizeRect);

	// draw a border
	//SizeRect.Inflate(1, 1);
	//e.Graphics.DrawRectangle(Pens.Black, SizeRect);

	// draw the item with same and text specified color name
	e.Graphics.DrawString(cmbExpTypes.Items[e.Index].ToString(), cmbExpTypes.Font, ComboBrush, e.Bounds.X, e.Bounds.Y);
}

You can also set the background color as well, I have commented the code of the same.

16Jan/120

Visual Studio is not debugging

Posted by Dhiraj Ranka

Background

It was a very normal day of development for me. As we know that luck does not favors us always, so for me as well. I was doing some coding on my project and wanted to debug the code for one of the windows form. And suddenly Visual Studio stopped debugging when I wanted to step through the code.

Why with me?

This was my first reaction when you believe that you are doing everything right.

Problem

Next step was to identify the problem or issue which was causing this. No matter how many times I will build the solution, the problem was still persisted. And I was getting following error all day long.

"The breakpoint will not currently be hit. No symbols have been loaded for this document"

Error-While-Debugging

Error-While-Debugging

Following are the options that I have tried

  1. Deployed assembly to GAC manually
  2. Build to Solution for so many times
  3. Googled about the same and but no luck
  4. Following certain steps like adding some keys in app.config
  5. Trying some tricks in Visual Studio 2010 itself.

    Configuration-Manager

    Configuration-Manager

  6. Trying to change the options in Visual Studio for debugging.

    Debug-Options

    Debug-Options

But nothing helped at all.

So, finally I have decided to solve this on own. Worst thing that I thought of trying is creating an empty solution and adding all the projects and files manually. But then I didn't panic that much :)

Solution

If all the options are not solving the problem then what exactly is the solution. You guys won't believe it that the solution was so simple. Here it goes

    1. Stop the debugger
    2. Close the Visual Studio
    3. Close the Application
    4. Shift + Del all the files in the obj and bin folders
    5. Restart the Visual Studio
    6. Rebuild the project
    7. Debug now, it will work 100%!

      Conclusion

      By this way Visual Studio will create all the files which were present in the debug directory. This will create the necessary .pdb files again and your breakpoint(s) will surely hit :)

      Happy coding!!!

      13Jan/120

      Enabling Session State in SharePoint 2010

      Posted by Dhiraj Ranka

      Background

      Don't know when this will be needed, but whenever required it important to know that how do we enable Session State in SharePoint 2010. Basically after enabling this we would be able to use session variables in our SharePoint 2010 application and Web Services.

      Let's Get Cracking

      In order to enable this first thing that we have to do is edit our web.config file. Add the following entry in httpModules section

      <httpModules>
          <add name="Session" type="System.Web.SessionState.SessionStateModule" />
      </httpModules>

      This is not it, next steps are more important. Go to your web application and this Session State module to IIS 7.x managed pipeline.

      1. Go to Run and type inetmgr
        Run-IIS

        Run-IIS

      2. Select your Web Application in left tree and double click Modules under IIS section in Feature View pane.

        Select-WebApplication-Modules

        Select-WebApplication-Modules

      3. Click on "Add Managed Module..." from Actions pane

        Add-Managed-Module

        Add-Managed-Module

      4. In Add Managed Module dialog enter "Session State" or any other name of your choice and select following item from "Type" drop down.

        Select-Managed-Module-Name-And-Type

        Select-Managed-Module-Name-And-Type

        System.Web.SessionState.SessionStateModule, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
      5. Finally to be on safer side restart the IIS.

        Restart-IIS

        Restart-IIS

      After all this session state will be enabled in your web application or web service.

      Example

      Add page in your SharePoint project and add "EnableSessionState" attribute in page directive and set its value to "True"

      In code behind add this code to add a session variable and value for the same and display the value of session variable in label.

      if (Session.Count <= 0)
      {
      	Session.RemoveAll();
      	Session.Add("LongOp", "on");
      }
      
      lbl.Text = Session[0].ToString();

      Happy SharePointing :)