Archive | Code RSS feed for this section

export MySQL query to csv | php | kippo password db

12 Jan

I thought it a good idea to generate a user/pass database based on my kippo installation seeing as it is a target for multiple bruteforce databases from multiple attackers. Below is the SQL Statement i use to generate the data.

SELECT DISTINCT username, password from auth where password <> "" ORDER BY username ASC

Now, I wanted a way to get this via my website and present it as a download to those interested. Tried a few code examples via google and couldn’t get the majority of them to work. After some digging and fiddling I eventually managed to get my kippo data out into .csv file which is automatically sent back to the web session and presented to the client for download.

  // establish database connection
  $conn = mysql_connect( 'MYSQL_HOST', 'MYSQL_USERNAME', 'MYSQL_PASSWORD' ) or die( mysql_error( ) );
  mysql_select_db( 'MYSQL_DATABASE', $conn ) or die( mysql_error( $conn ) );
  // execute sql query
  $query = sprintf( 'SELECT * FROM MYSQL_TABLE' );
  $result = mysql_query( $query, $conn ) or die( mysql_error( $conn ) );
  // send response headers to the browser
  // following headers instruct the browser to treat the data as a csv file called export.csv
  header( 'Content-Type: text/csv' );
  header( 'Content-Disposition: attachment;filename=export.csv' );
  // output header row (if atleast one row exists)
  $row = mysql_fetch_assoc( $result );
  if ( $row )
    echocsv( array_keys( $row ) );
  // output data rows (if atleast one row exists)
  while ( $row )
    echocsv( $row );
    $row = mysql_fetch_assoc( $result );
  // echocsv function
  // echo the input array as csv data maintaining consistency with most CSV implementations
  // * uses double-quotes as enclosure when necessary
  // * uses double double-quotes to escape double-quotes 
  // * uses CRLF as a line separator
  function echocsv( $fields )
    $separator = '';
    foreach ( $fields as $field )
      if ( preg_match( '/\\r|\\n|,|"/', $field ) )
        $field = '"' . str_replace( '"', '""', $field ) . '"';
      echo $separator . $field;
      $separator = ',';
    echo "\r\n";

Defending against SQL Injection Attack in PHP | any version

12 Jan

Internet Security is a very sensitive issue and many websites have vulnerabilities which are easily exploitable. One such vulnerability is SQL Injection, in which the attacker can literally execute any kind of query in your database, even gain administrator privileges and if things are even worse, then he may also gain access to your system and execute any command. No wonder how dangerous this vulnerability is, but it has a very easy fix. I’d like to introduce you with a small function escape(), I’ve written for sanitizing data while querying the database, which will disable SQL Injection attacks in PHP, irrespective of the PHP version you use.

function escape($input)
if (!get_magic_quotes_gpc()) {
$input = addslashes($input);
return $input;


By default the Magic GPC Quotes feature of PHP is turned ON. So it will automatically sanitize any data it receives from $_GET and $_POST by placing slashes before any ‘, ” or \ characters. However, as of PHP 5.0+, this feature is deprecated and hence relying on it is highly discouraged. Instead, use the addslashes() function which does the same thing. So the function I wrote will basically identify whether the Magic GPC feature is turned ON, if it is, then it will simply return the query as it is, else it will call the addslashes() method on the query. So simple !
However, there’s a more “secure” version of it. But this one is not suitable for large-scale systems as it requires an extra-connection to the MySQL server.

function escape($input)
if (get_magic_quotes_gpc()) {
$input = stripslashes($input);
return mysql_real_escape_string($input);


You can use the above function as follows :

Find out all the form variables that you receive in your PHP code i.e. all the occurrences of $_GET and $_POST and whenever you use then, use


instead of just $_POST[‘var’]. Similary for $_GET variables also.

For example, suppose you have stored the mysql query like :

$query=”SELECT * FROM `users` WHERE `username`=’$username’ AND `password`=’$password’”;

To secure the above code, use this code instead :

$query=”SELECT * FROM `users` WHERE `username`=’$username’ AND `password`=’$password’”;

or, by writing it in a single line only :

$query=”SELECT * FROM `users` WHERE `username`=’”.escape($username).”‘ AND `password`=’”.escape($password).”‘”;

This simple thing will completely disable any kind of SQL Injection attacks in your website or web-application, irrespective of the PHP version you use. However, beware of other attacks !

github | code repository | version control

4 Jan

Many people consider Git to be too confusing or complex to be a choice for version control. Yet Git considers to grow in adoption, and many interesting things have grown up around it. This document is geared for someone wanted to get started with Git, often coming from a Subversion background. For most basic needs this document will cover 70 to 90 percent of your use.

Getting Started

To use Git you will have to setup a repository. You can take an existing directory to make a Git repository, or create an empty directory.

To make your current directory a Git repository we simply run init.

git init

To make a new directory that is a Git repository we just specify a directory.

git init newrepo

From here on out we’ll assume that you are in the root of the Git repository unless otherwise noted.

Adding New Files

So we have a repository, but nothing in it. You can add files with the add command.

git add filename

To add everything in your directory try git add ..

Committing a Version

Now that we’ve added these files, we want them to actually be stored in the Git repository. We do this by committing them to the repository.

git commit -m "Adding files"

If you leave off the -m you will be put into an editor to write the message yourself.

Editing Files

When you’ve made changes to some files, you can run git status to see what will happen on commit. You’ll notice a list of modified files, and a message:

no changes added to commit (use "git add" and/or "git commit -a")

So running git commit will do nothing unless you explicitly add files to the commit with git add. If you’re looking for the commit command to automatically commit local modifications we use the -a flag.

git commit -a -m "Changed some files"

Or if you’d like to have only certain files, but still not run git add we pass specific files.

git commit -m "change some files" file1 file2

Do note that -a will not cause new files to be committed, only modified.

Publishing Your Repository

To put your repository on a server we’ll start by making a “bare” repository, and upload it to a server.

cd /tmp
git clone --bare ~/your/repo/path project.git
scp -r project.git ssh://

Now if we have a couple of commits and want to push it up to that location:

git push ssh://

If you dislike typing the URI each time we can take advantage that a cloned project remembers where it came from.

cd ..
git clone ssh:// project

Now git push will push to the URI it was cloned from. You can do this manually by editing .git/config in your repository.

Get Upstream Changes

If you’re already setup for push as above:

git pull

Will bring changes down and merge them in. To pull from a non-default location just specify the URI.

git pull
More Than Five Minutes

You’ll have noticed that Git thinks in “commits.” These are uniquely identified by a hash. You can see the history and the hashes with git log. Each commit involves modifications, new files, and files being removed. add will put a file in a commit. git reset HEAD will remove everything from the planned commit, but not change files.


If you want to remove a file from the repository, removing it from future commits we use rm.

git rm file
Branching and Merging

Branches are done locally and are fast. To create a new branch we use the branch command.

git branch test

the branch command does not move us into the branch, just create one. So we use the checkout command to change branches.

git checkout test

The first branch, or main branch, is called “master.”

git checkout master

While in your branch you can commit changes that will not be reflected in the master branch. When you’re done, or want to push changes to master, switch back to master and use merge.

git checkout master
git merge test

And if you’re done with the branch you can delete with the branch command and pass the -d flag.

git branch -d test
Traveling Through Time

You can quickly very previous states of the repository using the checkout command again.

git checkout HASH

Uncommited changes will travel with you. Return to the preset with git checkout master as with normal branches. If you commit while in the past a branch is automatically created and your changes will have to be merged forward.

Sweeping Changes Under the Rug for Later

When moving between branches your local changes move with you. Sometimes you want to switch branches but not commit or take those changes with you. The Git command stash lets you put changes into a safe store.

git stash

You can retreive by passing an arguement of apply or pop.

git stash apply

The difference between apple and pop is simple. apply will take a stash state and apply it, but preserve that state in the stash. pop will take the stash state, apply it, and remove it from the stash. git stash clear empties the contents of the stash.

VBScript for querying eDirectory

16 Dec

So i needed a way to lookup values in an Excell Spreadsheet against a Novell IDM Value (eDirectory Tree). Below follows the code for searching for values in Column A and if present in eDirectory than put a value in Column B to that effect :

(Note: Im using 389 and not 636, code needs adjusting for SSL connectivity. Also, replace all <value> with values specific to your environment) 

Lastly, be carefull of the strain that a large query (100000’s) of comparison records against your eDir Tree can cause. Ideally, you’d want to store this in a Hashtable/ADORecordset and than search locally, but this is a quick and dirty meathod.


Public Sub CheckEmail()
‘Option Explicit
‘On Error Resume Next
Dim val As String
Dim rng As Range
Dim i As Integer

‘ADO Constants
Const adOpenStatic = 3
Const adLockOptimistic = 3
‘The value below required for the connection string to read a text file
Const adCmdText = &H1
Const objectExists = -2147019886
Const failToOpenObject = -2147016646
Const InvalidUseOfNull = 94
Set objConnection = CreateObject(“ADODB.Connection”)
objConnection.Provider = “ADsDSOObject”
objConnection.Open “Active Directory Provider”, “CN=<username>,o=<container>”, “<password>”
Set objCommand = CreateObject(“ADODB.Command”)
objCommand.ActiveConnection = objConnection
count = 1
Set rng = Range(“A1:A2146”)
For i = rng.Rows.count To 1 Step -1
    val = rng.Cells(i, 1).Value
   objCommand.CommandText = _
    “LDAP://<server>/OU=<ou>,O=<container>>;” & _
        “(&(objectClass=AUCoreIdentityAUX)(mail=” & val & “));” & _
    Set objRecordset = objCommand.Execute
    If objRecordset.EOF Then
        Cells(i, 2).Value = “no”
        ‘MsgBox “No records returned for the current objCommand.CommandText :” & vbCrLf & objCommand.CommandText
          Cells(i, 2).Value = “yes”
    End If

End Sub

java | get file shares \\domain\netlogin\{scripts}

6 Dec

My current project has recently required that i be able to report on the Network UNC shares consumed by each Active Directory OU. Not easy to accomplish when your domain is in excess of 110 OU’s and 10k+ users.

This will be a two part example : (update to complete second part)

1. What i have to start with is a list of network login scripts for all users in a given AD OU. How i got this data is irrelevant for now (still compiling java).

2. Here : is a little .jar file that will ask for a NetBIOS Domain Name (NONE canonical), Server (forced target for specific/local Domain Controller for the lookups) and login script. It than iterates through the script and extracts all NET USE statements with PERSISTENT on and dumps into a lsUNCshares.csv.

You can run it as a batch by putting

for /F “eol=; tokens=1 delims=,” %%A in (lscriptlist.txt) do @”java.exe” -jar GetScriptUNCs.jar %%A > %%AResults.csv

in a run.cmd batch file in the same directory as the .jar. Edit a lscriptlilst.txt with the output of all login scripts you want to check and run it.

Bang. A list of all UNC Shares for all login scripts in a file.

Shoutout goes to Carl Billings for assistance with this code segment.

{Source Included}