Ads

Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Wednesday, September 30, 2015

Code Study - Tic-Tac-Toe in ASP



The coding is only for tutorial purpose. This is the simple Tic-Tac-Toe game written in ASP.

Option Explicit


' -- Set up images to use ---
Const IMGx = "x.jpg"
Const IMGo = "o.jpg"
Const IMGblank = "blank.jpg"

' -- Set up game States ---
Const END_Not_Yet = 0
Const END_You_Win = 1
Const END_Computer_Win = 2
Const END_Tie = 3

' Read in board or Initialise
Dim Gameboard
Dim wl1,wl2,wl3,wl4,wl5,wl6,wl7,wl8

If Session("GameBoard") & "" = "" OR Request("PlayAgain") = "Yes" Then
PlayAgain
end if

GameBoard = Split(Session("GameBoard"),"_")


function GameState()

wl1 = GameBoard(0) & GameBoard(1) & GameBoard(2)
wl2 = GameBoard(0) & GameBoard(3) & GameBoard(6)
wl3 = GameBoard(0) & GameBoard(4) & GameBoard(8)
wl4 = GameBoard(1) & GameBoard(4) & GameBoard(7)
wl5 = GameBoard(3) & GameBoard(4) & GameBoard(5)
wl6 = GameBoard(6) & GameBoard(7) & GameBoard(8)
wl7 = GameBoard(2) & GameBoard(5) & GameBoard(8)
wl8 = GameBoard(6) & GameBoard(4) & GameBoard(2)

if wl1="XXX" or wl2="XXX" or wl3="XXX" or wl4="XXX" or wl5="XXX" or wl6="XXX" or wl7="XXX" or wl8="XXX" Then
GameState = END_You_Win
elseif wl1="OOO" or wl2="OOO" or wl3="OOO" or wl4="OOO" or wl5="OOO" or wl6="OOO" or wl7="OOO" or wl8="OOO" Then
GameState = END_Computer_Win
elseif Instr ( wl1 & wl5 & wl6 ,"B" ) = 0 then
GameState = END_Tie
else
GameState = END_Not_Yet
end if

end function


Function Suggest()

If wl1 = "XXB" or wl1 = "OOB" Then
Suggest = 2
elseif wl1 = "XBX" or wl1 = "OBO" Then
Suggest = 1
elseif wl1 = "BXX" or wl1 = "BOO" Then
Suggest = 0
elseif wl2 = "XXB" or wl2 = "OOB" Then
Suggest = 6
elseif wl2 = "XBX" or wl2 = "OBO" Then
Suggest = 3
elseif wl2 = "BXX" or wl2 = "BOO" Then
Suggest = 0
elseif wl3 = "XXB" or wl3 = "OOB" Then
Suggest = 8
elseif wl3 = "XBX" or wl3 = "OBO" Then
Suggest = 4
elseif wl3 = "BXX" or wl3 = "BOO" Then
Suggest = 0
elseif wl4 = "XXB" or wl4 = "OOB" Then
Suggest = 7
elseif wl4 = "XBX" or wl4 = "OBO" Then
Suggest = 4
elseif wl4 = "BXX" or wl4 = "BOO" Then
Suggest = 1
elseif wl5 = "XXB" or wl5 = "OOB" Then
Suggest = 5
elseif wl5 = "XBX" or wl5 = "OBO" Then
Suggest = 4
elseif wl5 = "BXX" or wl5 = "BOO" Then
Suggest = 3
elseif wl6 = "XXB" or wl6 = "OOB" Then
Suggest = 8
elseif wl6 = "XBX" or wl6 = "OBO" Then
Suggest = 7
elseif wl6 = "BXX" or wl6 = "BOO" Then
Suggest = 6
elseif wl7 = "XXB" or wl7 = "OOB" Then
Suggest = 8
elseif wl7 = "XBX" or wl7 = "OBO" Then
Suggest = 5
elseif wl7 = "BXX" or wl7 = "BOO" Then
Suggest = 2
elseif wl8 = "XXB" or wl8 = "OOB" Then
Suggest = 2
elseif wl8 = "XBX" or wl8 = "OBO" Then
Suggest = 4
elseif wl8 = "BXX" or wl8 = "BOO" Then
Suggest = 6
else
Suggest = -1
end if

end function


sub yourChoice(Position)

if Session("State") = "Dead" Then
ReportEnded
Else
If GameBoard(Position) <> "B" Then
ReportTaken
else
GameBoard(Position) = "X"
end if
end if
end sub


sub ReportTaken()
Response.Write "

That square is already occupied. Please select another square.

"
end sub

sub ReportEnded()
Response.Write "

The game has already ended. To play a new game click the Play Again button.

"
end sub



sub myChoice()
Dim NewMove

NewMove = Suggest()

While NewMove = -1
Randomize
NewMove=int(rnd*9)
If GameBoard(NewMove) <> "B" Then
NewMove = -1
End If
wend

GameBoard(NewMove) = "O"
end sub




sub ProcessBoard()

If Session("State") = "Alive" Then

Select Case GameState()
Case END_You_Win
Response.Write "

You won, congratulations!

"
Session("you") = Session("you") + 1
Session("State") = "Dead"

Case END_Computer_Win
Response.Write "

Gotcha! I win!

"
Session("computer") = Session("computer") + 1
Session("State") = "Dead"

Case END_Tie
Response.Write "

We tied.

"
Session("ties") = Session("ties") + 1
Session("State") = "Dead"

end Select

End If

end sub


sub playAgain()
Session("GameBoard") = "B_B_B_B_B_B_B_B_B"
Session("State") = "Alive"
end sub


sub Display(CellNum)

If GameBoard(CellNum) = "B" Then
Response.Write "
"
Response.Write ""
Response.Write ""
Response.Write "
"
elseif GameBoard(CellNum) = "O" Then
Response.Write ""
elseif GameBoard(CellNum) = "X" Then
Response.Write ""
end if

end sub


' Main Code
If Request("Pressed") & "" <> "" Then

YourChoice(Request("Pressed"))

ProcessBoard
If GameState() = END_Not_Yet Then
myChoice
End If
ProcessBoard

' Save Game State
Session("GameBoard") = Join(GameBoard,"_")

End If
%>








Welcome to Tic-Tac-Toe! You play as the X's and the computer is the O's. Select the square you want to put your X into by clicking them. You cannot occupy a square that is already occupied. The first player to get three squares in a row wins. Good Luck!!


















<% Display(0) %><% Display(1) %><% Display(2) %>
<% Display(3) %><% Display(4) %><% Display(5) %>
<% Display(6) %><% Display(7) %><% Display(8) %>






>You
>Computer
>Ties








Thursday, December 25, 2014

Network Security Hack - Protect your network with Linux's powerful firewalling features

Linux has long had the capability for filtering packets, and it has come a long way since the early days in terms of both power and flexibility. The first generation of packet-filtering code was called ipfw (for "IP firewall") and provided basic filtering capability. Since it was somewhat inflexible and inefficient for complex configurations, ipfw is rarely used now. The second generation of IP filtering was called IP chains. It improved greatly on ipfw and is still in common use. The latest generation of filtering is called Netfilter and is manipulated with the iptables command. It is used exclusively with the 2.4.x and later series of kernels. Although Netfilter is the kernel component and iptables is the user-space configuration tool, these terms are often used interchangeably.

An important concept in Netfilter is the chain , which consists of a list of rules that are applied to packets as they enter, leave, or traverse through the system. The kernel defines three chains by default, but new chains of rules can be specified and linked to the predefined chains. The INPUT chain applies to packets that are received and are destined for the local system, and the OUTPUT chain applies to packets that are transmitted by the local system. Finally, the FORWARD chain applies whenever a packet will be routed from one network interface to another through the system. It is used whenever the system is acting as a packet router or gateway, and applies to packets that are neither originating from nor destined for this system.
The iptables command is used to make changes to the Netfilter chains and rulesets. You can create new chains, delete chains, list the rules in a chain, flush chains (that is, remove all rules from a chain), and set the default action for a chain. iptables also allows you to insert, append, delete, and replace rules in a chain.
Before we get started with some example rules, it's important to set a default behavior for all the chains. To do this we'll use the -P command-line switch, which stands for "policy":

# iptables -P INPUT DROP

# iptables -P FORWARD DROP

This will ensure that only those packets covered by subsequent rules that we specify will make it past our firewall. After all, with the relatively small number of services that will be provided by the network, it is far easier to explicitly specify all the types of traffic that we want to allow, rather than all the traffic that we don't. Note that a default policy was not specified for the OUTPUT chain; this is because we want to allow traffic to proceed out of the firewall itself in a normal manner.

With the default policy set to DROP, we'll specify what is actually allowed. Here's where we'll need to figure out what services will have to be accessible to the outside world. For the rest of these examples, we'll assume that eth0 is the external interface on our firewall and that eth1 is the internal one. Our network will contain a web server (192.168.1.20), a mail server (192.168.1.21), and a DNS server (192.168.1.18)—a fairly minimal setup for a self-managed Internet presence.

However, before we begin specifying rules, we should remove filtering from our loopback interface:
# iptables -P INPUT -i lo -j ACCEPT

# iptables -P OUTPUT -o lo -j ACCEPT
Now let's construct some rules to allow this traffic through. First, we'll make a rule to allow traffic on TCP port 80—the standard port for web servers—to pass to the web server unfettered by our firewall:
# iptables -A FORWARD -m state --state NEW -p tcp \

 -d 192.168.1.20 --dport 80 -j ACCEPT
And now for the mail server, which uses TCP port 25 for SMTP:
# iptables -A FORWARD -m state --state NEW -p tcp \

 -d 192.168.1.21 --dport 25 -j ACCEPT
Additionally, we might want to allow remote POP3, IMAP, and IMAP+SSL access as well:

POP3
# iptables -A FORWARD -m state --state NEW -p tcp \

 -d 192.168.1.21 --dport 110 -j ACCEPT

IMAP
# iptables -A FORWARD -m state --state NEW -p tcp \

 -d 192.168.1.21 --dport 143 -j ACCEPT

IMAP+SSL
# iptables -A FORWARD -m state --state NEW -p tcp \

 -d 192.168.1.21 --dport 993 -j ACCEPT
Unlike the other services, DNS can use both TCP and UDP port 53:
# iptables -A FORWARD -m state --state NEW -p tcp \

-d 192.168.1.21 --dport 53 -j ACCEPT

Since we're using a default deny policy, it makes it slightly more difficult to use UDP for DNS. This is because our policy relies on the use of state tracking rules, and since UDP is a stateless protocol, there is no way to track it. In this case, we can configure our DNS server either to use only TCP, or to use a UDP source port of 53 for any response that it sends back to clients that were using UDP to query the nameserver.

If the DNS server is configured to respond to clients using UDP port 53, we can allow this traffic through with the following two rules:
 
# iptables -A FORWARD -p udp -d 192.168.1.18 --dport 53 -j ACCEPT

# iptables -A FORWARD -p udp -s 192.168.1.18 --sport 53 -j ACCEPT

The first rule allows traffic into our network destined for the DNS server, and the second rule allows responses from the DNS server to leave the network.

You may be wondering what the -m state and --state arguments are about. These two options allow us to use Netfilter's stateful packet-inspection engine. Using these options tells Netfilter that we want to allow only new connections to the destination IP and port pairs that we have specified. When these rules are in place, the triggering packet is accepted and its information is entered into a state table.

Now we can specify that we want to allow any outbound traffic that is associated with these connections by adding a rule like this:
 
# iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

The only thing left now is to allow traffic from machines behind the firewall to reach the outside world. To do this, we'll use a rule like the following:
 
# iptables -A FORWARD -m state --state NEW -i eth1 -j ACCEPT

This rule enters any outbound connections from the internal network into the state table. It works by matching packets coming into the internal interface of our firewall that are creating new connections. If we were setting up a firewall that had multiple internal interfaces, we could have used a Boolean NOT operator on the external interface (e.g., -i ! eth0). Now any traffic that comes into the firewall through the external interface that corresponds to an outbound connection will be accepted by the preceding rule, because this rule will have put the corresponding connection into the state table.

In these examples, the order in which the rules were entered does not really matter. Since we're operating with a default DENY policy, all our rules have an ACCEPT target. However, if we had specified targets of DROP or REJECT as arguments to the -j option, then we would have to take a little extra care to ensure that the order of those rules would result in the desired effect. Remember that the first rule that matches a packet is always triggered as the rule chains are traversed, so rule order can sometimes be critically important.
It should also be noted that rule order can have a performance impact in some circumstances. For example, the rule shown earlier that matches ESTABLISHED and RELATED states should be specified before any of the other rules, since that particular rule will be matched far more often than any of the rules that will match only on new connections. By putting that rule first, it will prevent any packets that are already associated with a connection from having to traverse the rest of the rule chain before finding a match.

To complete our firewall configuration, we'll want to enable packet forwarding. Run this command:
 
# echo 1 > /proc/sys/net/ipv4/ip_forward

This tells the kernel to forward packets between interfaces whenever appropriate. To have this done automatically at boot time, add the following line to /etc/sysctl.conf:
net.ipv4.ip_forward=1

If your system doesn't support /etc/sysctl.conf, you can put the preceding echo command in one of your startup rc scripts, such as /etc/rc.local. Another useful kernel parameter is rp_filter, which helps prevent IP spoofing. This enables source address verification by checking that the IP address for any given packet has arrived on the expected network interface. 

This can be enabled by running the following command:
 
# echo 1 > /proc/sys/net/ipv4/conf/default/rp_filter

Much like how we enabled IP forwarding, we can also enable source address verification by editing /etc/sysctl.conf on systems that support it, or else put the changes in your rc.local. To enable rp_filter in your sysctl.conf, add the following line:
 
net.ipv4.conf.all.rp_filter=1

To save all of our rules, we can either write all of our rules to a shell script or use our Linux distribution's particular way of saving them. 
We can do this in Red Hat by running the following command:
# /sbin/service iptables save

This will save all currently active filter rules to /etc/sysconfig/iptables. To achieve the same effect under Debian, edit /etc/default/iptables and set enable_iptables_initd=true.

After doing this, run the following command:
# /etc/init.d/iptables save_active
When the machine reboots, your iptables configuration will be automatically restored.

Happy Hacking!!

Monday, October 20, 2014

Cisco LAN Switching - Configuring SNMP

Switches should be configured so that management stations can gather information via the Simple Network Management Protocol (SNMP). SNMP is used to gather statistics, counters, and tables in the Management Information Base (MIB) of a device.
The SNMP framework consists of three parts:
  • SNMP manager
  • SNMP agent
  • MIB
The SNMP manager is a host that monitors the activities of network devices using SNMP. The SNMP manager is typically referred to as the Network Management Station (NMS). The SNMP agent is software running on the device being monitored by the SNMP manager. A MIB is a virtual storage area for network management information consisting of collections of managed objects. MIBs are written in the SNMP MIB module language as defined in RFCs 2578, 2579, and 2580. SNMP agents can be configured to allow read-only or read-write access to the device. Management stations like CiscoWorks use the read-only functions of the agent to monitor the device, and can use the read-write functions of the agent to make changes to the device configuration. SNMP uses passwords called community strings to grant access to the SNMP agent. Access to the agents can be further limited via SNMP access lists.

 SNMP MIB information for each Cisco device can be found on Cisco.com.

You should configure SNMP on each Cisco device to be monitored by NMS. A sample SNMP configuration is shown on SW1 in Example
Example:  Sample SNMP Configuration on SW1
SW1#config t

Enter configuration commands, one per line.  End with CNTL/Z.



SW1(config)#access-list 10 permit 10.10.10.2

SW1(config)#snmp enable

SW1(config)#snmp-server community alpha ro 10

SW1(config)#snmp-server community beta rw 10

SW1(config)#snmp-server contact John Smith (555)789-2653

SW1(config)#snmp-server location Denver Data Center

SW1(config)#snmp enable traps

SW1(config)#snmp trap-source lo0


After SNMP is configured on SW1, the statistics can be viewed using the show snmp command, as shown in as
Example :Output of show snmp Command on SW1
SW1#show snmp

Chassis: SAD050814BH

Contact: John Smith (555)789-2653

Location: Denver Data Center

0 SNMP packets input

    0 Bad SNMP version errors

    0 Unknown community name

    0 Illegal operation for community name supplied

    0 Encoding errors

    0 Number of requested variables

    0 Number of altered variables

    0 Get-request PDUs

    0 Get-next PDUs

    0 Set-request PDUs

0 SNMP packets output

    0 Too big errors (Maximum packet size 1500)

    0 No such name errors

    0 Bad values errors

    0 General errors

    0 Response PDUs

    0 Trap PDUs



SNMP logging: disabled
 
Happy Reading!! 

Monday, September 15, 2014

Wireless Hack - Scan and Exploit Vulnerable Hosts on WLAN

This is an active phase of your attack. When the fourth step is reached, you should have gathered a large amount of helpful data that makes penetrating wireless peers, gateways, and sniffable wired-side hosts an easy task. Perhaps no penetration is needed, because you have already collected or cracked user passwords flowing across the network. Using the data gathered, you can select the most suitable hosts for a further attack aimed at obtaining administrator or root privileges on these hosts. At this stage you can perform active OS fingerprinting, port scanning, and banner grabbing to determine vulnerable services for further exploitation. Remember the golden rule of fingerprinting: Use several available techniques and analyze the results. The options include the following:
  • nmap -O
  • thcrut discover (uses improved nmap fingerprinting methodology)
  • Ettercap (press f/F over a host)
  • xprobe
  • xprobe2 (yes, this is a different tool)
  • induce-arp.pl (ARP-based OS fingerprinting)
  • sing (basic ICMP fingerprinting)
  • sprint and sprint-lite
  • tools that do fingerprinting via specific services if present (ldistfp, lpdfp telnetfp)
  • other tools available in the vast scope of the Internet
As to port scanning itself, nmap is everyone's all-time favorite. What kind of "hacking book" does not describe how to run nmap? Without going into the port scanning depths, here are our recommendations:
  • First try the zombie/idle scan with -sI. It might not work.
  • Check out the protocol scan (-sO). Try to do fingerprinting with -sO.
  • Proceed with -sN (null). Many firewalls and IDSs would not detect it (e.g., ipchains logging).
  • You can follow with -sF to be sure, but avoid Xmas (-sX).
  • If you haven't captured any useful data from these scans, the host is likely to be some form of Microsoft Windows. Use the half-connect scan (-sS).
Because we are on (W)LAN, there is another tool to consider: the Ghost Port Scan. Ghost Port Scan uses ARP poisoning to spoof both IP and MAC addresses of the scanning host on the LAN. The scanner is able to find IP addresses not in use on the LAN the attacker's host is connected to. Such a feature is used when no source IPs have been specified. The aim of this function is to avoid a potential DoS that could be caused by ARP poisoning. The scanner is quite flexible:


arhontus:~# ./gps

Ghost Port Scan version 0.9.0 by whitehat@altern.org

(gps.sourceforge.net)

Usage: ./gps -d target [-s host1[,host2/host3..]] [-t scan_type]

     [-v] [-r scan_speed] [-p first_port-last_port] [-k 0 | 1]

     [-e ping_port]  [-f t | o] [-i interface] [-S mac | ip]

     [-w window_size]

 -d target             :target host's IP/name

 -s host1[,host2/host3]:list of hosts we pretend to be

                      (use '/' to specify IP ranges)

 -t scan_type        :stealth scan mode (default: syn)

           (syn | xmas | null | fin | ack | rand | fwrd)

 -r scan_speed       :packet rate (default: insane)

           (insane | aggressive | normal | polite |

           paranoid)

 -p first-last ports :port range to scan (default: 1-1024)

 -k 0 | 1            :scan well-known ports (default: 1)

 -e ping_port          :target port for a TCP ping (default: 80)

 -v                  :verbose (use twice for more verbose)

 -f t | o              :fragment IP datagrams (default: no frag)

           (t: tiny frags | o: frag overlapping)

 -i interface        :network interface to use

 -S mac | ip         :spoofing level (IP or ethernet/MAC;

           default: mac)

 -w window_size        :size of the emission window (default: 256

           packets)


To grab banners the old-fashioned way, you can use telnet or netcat. However, your time (important on wireless) and effort can be saved if you use the following:
  • nmap+V (nmap patched by Saurik; try the -sVVV flag) or the latest version of nmap with novel banner fingerprinting -sV or -A flags
  • amap
  • THCrut
  • arb-scan
  • banshee (features command execution against the IP addresses scanned)
  • grabbb (very fast)
  • A variety of banner grabbers from the Men in Grey (MIG) group (very fast, but not necessarily accurate)
  • "Script kiddie" banner grabbers for the "hole of the month" (usually fast; probably started from banner grabbers for wu-ftpd versions)
As a security consultant, you can always use automated multipurpose security evaluation tools such as Nessus, but a real Black Hat is unlikely to employ these tools for stealth preservation reasons. Choose the tools you like for time-saving and personal reasons. Keep a large collection of exploit code and a long list of default passwords and dictionaries on your penetration testing laptop to save more time by avoiding browsing SecurityFocus, Packetstorm, and similar sites from the WLAN. Use Hydra and similar tools for remote password dictionary attacks and brute-forcing.

Happy Coding!!

Sunday, August 31, 2014

Wireless Security Hack - Cracking WEP

WLAN control is cracking WEP. As mentioned, wireless attacks do not start and end with cracking WEP, as many security experts might tell you. However, if the attacker cannot break WEP (if present), all he or she can do is disrupt the network operations by DoS attacks on layers below the protocol WEP implementation.
From the section dealing with WEP cracking tools, you have probably gathered that there are three major ways of attacking WEP:
  • Brute-forcing and improved brute-forcing
  • FMS attack
  • Improved FMS attack
Because this book is a down-to-earth guide to wireless security and hundreds of pages have already been written on WEP weaknesses and cracking mathematics, we do not aim to provide a comprehensive guide to the mathematical internals of WEP cracking attacks. Nevertheless, we believe it is important to present some cryptological data on WEP as an act of homage to all researchers who contributed to the WEP analysis and flaw enumeration.

WEP Brute-Forcing

Pure WEP keyspace brute-forcing with tools such as wep_tools or dwepcrack brute-forcing options is realistic only against 40-bit WEP keys. Even with this limited key size, it might take about 50 days on a single average Pentium III host. Nevertheless, an efficient distributed attack against 40-bit WEP is possible and one should never underestimate the potential of dictionary attacks, which are also applicable to 128-bit and higher WEP key size. In particular, it applies to the use of the newer Wepattack tool that can run dictionary attacks against a single captured data packet encrypted using WEP.

Tim has pointed out that the algorithm accepted as the de facto standard for 40-bit WEP key generation by many wireless equipment vendors is extremely flawed. It starts from folding a password string into a 32-bit number that reduces the keyspace from 240 to 232 bits. This number is employed to seed a pseudorandom number generator (PRNG which is used to derive all four 40-bit WEP keys used on the network. Although the PRNG-generated keyspace has a cycle length of 232 bits, because of the way the values are derived from the PRNG, the actual cycle length of drawn values is only 224 bits. To be more specific, a seed x produces the same keys as a seed x + 224. To make the situation even worse, the method chosen to fold a password string into a 32-bit seed ensures that the high bit of each of the four bytes always equals zero. The effect of these weaknesses combined is that the algorithm can only generate 221 unique sets of WEP keys, corresponding to seeds between 0 and 0x1000000, which do not have bits 0x80, 0x8000, or 0x800000 set. Thus, it takes 221 operations or less to crack any set of WEP keys generated from a password processed with such an algorithm. In Newsham's observations, this corresponds roughly to 90 seconds of cracking time on a 233-MHz PII or 35 seconds on a 500-MHz PIII; this is quite a difference if compared to 50 days of brute-forcing without this flaw.

However, not all vendors used the vulnerable key generation algorithm (to our knowledge, 3Com never did), 40-bit keys aren't used much anymore, and there are tools that ensure proper 40-bit key generation. An example of such a tool is dwepkeygen, included as part of BSD-airtools. In addition, to crack WEP using wep_tools, a large (about 24 Gb) pcap-format dump file is required. Thus, although Newsham's comments are interesting and have their place in the history of wireless cryptanalysis, we do not recommend trying the attack he developed or using brute-forcing in general against 128/104-bit WEP keys used by modern wireless networks.

However if you have truly massive traffic dump files, trying a dictionary attack using wep_tools or dwepcrack could bring success. Even better, you can try your luck with a dictionary attack against a single captured data packet or limited-size traffic dumps using Wepattack.

The FMS Attack

The most common attack against WEP is Scott Fluhrer, Itsik Mantin, and Adi Shamir's (FMS) key recovery methodology discovered in 2001 (the original paper entitled "Weaknesses in the Key Scheduling Algorithm of RC4" ). As you already know, this attack was implemented first by the Wep_crack and then by AirSnort. For those interested in how the attack algorithms work, we present a brief explanation here. If you are already familiar with the FMS attack or aren't interested in the "theoretical" cryptanalysis, feel free to skip this section and move forward.

The FMS attack is based on three main principles:
  1. Some IVs set up RC4 cipher  the way it can reveal key information in its output bytes.
  2. Invariance weakness allows use of the output bytes to determine the most probable key bytes.
  3. The first output bytes are always predictable because they contain the SNAP header defined by the IEEE specification.
A WEP key can be defined as K=IV.SK where SK is the secret key. The RC4 operation in a nutshell is K=IV.SK ---> KSA(K) ---> PRNG(K) XOR data stream. The scheduling algorithm KSA(K) works in the following way:


Initialization:

  For i = 0 \x{2026} N - 1

    S[i] = i

  j = 0

Scrambling:

  For i = 0 \x{2026} N - 1

    j = j + S[i] + K[i mod l]

   Swap(S[i], S[j])


The PRNG works as:


Initialization:

  i = 0

  j = 0

Generation Loop:

  i = i + 1

  j = j + S[i]

  Swap(S[i], S[j])

  Output Z = S[S[i] + S[j]]

Some IVs initialize the PRNG the way the first byte in the stream is generated using a byte from the secret key. Because the first data byte that the PRNG output is XORed with is predictable (SNAP header), it is easy to derive the first PRNG byte. The values we can get from weak IVs are only true about 5 percent of the time; some are true about 13 percent of the time. Taking into account the key size, it takes six to eight million packets of analysis to determine the correct WEP key. The theoretical packets throughput maximum ("wire speed") on the throughput-comparable to 802.11b LAN 10Base-T shared Ethernet is 812 frames per second (frame size of 1,518 bits). If we divide 6,000,000 by 812 we will get about 7,389 seconds or just above 2 hours necessary to accumulate enough packets for efficient WEP cracking. However, as we will see, the reality is different.

The basic FMS attack comes down to searching for IVs that conform to the (A + 3, N - 1, X) rule, where A is the byte in the secret key you are cracking, N is the size of the S-box (256) and X is a random number. It is advised that the following equations are applied right after the KSA:


X = SB+3[1] < B+3

X + SB+3[X] = B+3


The main problem is that such an equation is dependent on the previous key bytes, so it must be applied to the entire packet dump for every key byte that is tested. In its classical form, the FMS attack tests only the first byte of the output because it is very reliable; we know that the first byte of the SNAP header is nearly always 0xAA.

An Improved FMS Attack

To bypass this problem and optimize the FMS attack, H1kari of Dasb0den Labs has analyzed the patterns of weak Ivs appearance and how they relate to the key bytes they rely on. As he pointed out in the "Practical Exploitation of RC4 Weaknesses in WEP Environments" article. a basic pattern present can be defined as follows:


Definitions:

    let x = iv[0]

    let y = iv[1]

    let z = iv[2]

    let a = x + y

    let b = (x + y) - z

  Byte 0:

    x = 3 and y = 255

    a = 0 or 1 and b = 2

  Byte 1:

    x = 4 and y = 255

    a = 0 or 2 and b = SK[0] + 5

  Byte 2:

    x = 5 and y = 255

    a = 0 or 3 and b = SK[0] + SK[1] + 9

    a = 1 and b = 1 or 6 + SK[0] or 5 + SK[0]

    a = 2 and b = 6

  Byte 3:

    x = 6 and y = 255

    a = 0 or 4 and b = SK[0] + SK[1] + SK[2] + 14

    a = 1 and b = 0 or SK[0] + SK[1] + 10 or SK[0] + SK[1] + 9

    a = 3 and b = 8

  Byte 4:

    x = 7 and y = 255

    a = 0 or 5 and b = SK[0] + SK[1] + SK[2] + SK[3] + 20

    a = 1 and b = 255 or SK[0] + SK[1] + SK[2] + 15 or

                  SK[0] + SK[1] + SK[2] + 14

    a = 2 and b = SK[0] + SK[1] + 11 or SK[0] + SK[1] + 9

    a = 3 and b = SK[0] + 11

    a = 4 and b = 10


The resulting distribution pattern would be similar to this:


Secret Key Byte

        0  1  2  3  4  5  6  7  8  9  a  b  c

              +     +     +     +     +     +

    0   8  16 16 16 16 16 16 16 16 16 16 16 16

    1   8     16 16 16 16 16 16 16 16 16 16 16

    2      16 8     16 16 16 16 16 16 16 16 16

  a 3         16 8  16    16 16 16 16 16 16 16

    4            16 8  16 16    16 16 16 16 16

  V 5               16 8  16 16 16    16 16 16

  a 6                  16 8  16 16 16 16    16

  l 7                     16 8  16 16 16 16 16

  u 8                        16 8  16 16 16 16

  e 9                           16 8  16 16 16

  s a                              16 8  16 16

    b                                 16 8  16

    c                                    16 8

    d                                       16

  8  - 8-bit set of weak ivs

  16 - 16-bit set of weak ivs

  +   - 2 additional x and y dependent 8-bit weak ivs


From this distribution a rough estimate of weak IVs per key byte can be derived. There are other means of deriving this value as outlined in the referenced article. However, the real catch is to find an algorithm that will allow filtering out weak IVs based on the secret key byte that they can attack. This can be done with an algorithm similar to this:


let l = the amount of elements in SK



i = 0

For B = 0 ... l - 1

  If (((0 <= a and a < B) or

   (a = B and b = (B + 1) * 2)) and

   (B % 2 ? a != (B + 1) / 2 : 1)) or

   (a = B + 1 and (B = 0 ? b = (B + 1) * 2 : 1)) or

   (x = B + 3 and y = N - 1) or

   (B != 0 and !(B % 2) ? (x = 1 and y = (B / 2) + 1) or

   (x = (B / 2) + 2 and y = (N - 1) - x) : 0)

    Then ReportWeakIV


Such methodology effectively reduces the search time for each key by at least 1/20, thus giving us the time necessary to crack WEP. Now you don't need to collect 6,000,000 packets or more; half a million packets could be sufficient! This is the improved FMS attack as implemented by BSD-airtools dwepcrack; read its source code to discover and learn more.

The practicality of WEP cracking attacks is still denied by many. There are statements that, for example, a home or SOHO WLAN will not generate enough traffic to collect a sufficient amount of weak or interesting IVs for the key compromise in a reasonable time period. You just saw a methodology that can significantly cut the necessary data collected and this methodology has been implemented in a security auditing tool since the year 2001! However, even if the most commonly used WEP cracking tool, AirSnort, is employed, the results can be less than encouraging for the few remaining WEP enthusiasts. In our experience it takes only 3,000 to 3,500 interesting IVs frames to break the WEP key for either 64-bit or 128-bit WEP keys using AirSnort. The only difference mentioned between cracking the keys of both sizes is the amount of time necessary to collect these frames. It took 10 to 20 percent more time to collect the necessary amount of interesting IVs frames to obtain a 128-bit key on a testing wireless network. Our record of breaking a 64-bit WEP with AirSnort is 1 hour 47 minutes on a point-to-point 802.11b link with one of the hosts flood pinging the other (approximately 300 packets per second). Such an attack required 107 minutes * 300 packets/second = 1,926,000 packets, much less than the 6,000,000 packets estimated theoretically. It could've been sheer luck, but would you base your network security on guesswork considering how lucky or unlucky an attacker might be?

On a large, corporate wireless network, 300 packets per second is neither unusual nor unexpected, especially with 802.11a and 802.11g standards offering higher bandwidth and network throughput. The presence of "chatty" network protocols (RIP, link-state routing protocols "hello" packets, spanning tree, HSRP, VRRP, NetBIOS, IPX RIP and SAP, AppleTalk, etc.) might dramatically decrease the time needed to crack WEP. It also generates wireless traffic even when no user activity is present. Imagine a large wireless Novell-based network running NetBIOS over IPX and using three Cisco routers with turned-on hot standby for failover resilience and enabled CDP (we have seen networks like this in the United Kingdom on several occasions). Such a network does not have to be the WLAN itself; leaking wired traffic on the wireless side is sufficient and we have frequently seen access points plugged directly into the switch or hub. Let's say there are 100 hosts on the network and no user activity present. In one hour, every host will generate approximately 1,200 NetBIOS keep-alives, 40 IPX RIPs, and 40 SAPs, and each router will send 1,200 HSRP Hello packets and 60 CDP frames if the defaults aren't changed (they rarely are), as well as the obvious 40 RIPs. Thus, the number of generated packets will be 100x(1,200+40+40) + 3x(1,200+60+40) = 131,900 packets per hour. Thus, accumulating the 2,000,000 packets necessary to crack WEP with AirSnort in our example will take approximately 15 hours. 

With dwepcrack as few as 500,000 packets might be needed, which translates into approximately 3 hours, 47 minutes, without a single user logged in! Remember that this network is both perfect and hypothetical. In reality, a Novell server might send more than one SAP in 90 seconds because a single SAP packet can advertise up to seven services and the server might run more. NLSP might be running and STP traffic could be present. We frequently find networks with system administrators completely unaware of the unnecessary and unused STP traffic on the network and some higher end switches and even wireless access points have STP enabled by default. Mind the traffic!

Finally, in some cases, old 802.11b cards use the same IV value or start counting IV numbers from 0 each time the card is initialized and increments these numbers by one. This also significantly cuts the time necessary to crack WEP.

How about cracking WEP on 802.11a networks? It is essentially the same. The only difference is that we aren't aware of decent 802.11a support on BSD and AirSnort will not work with ark_5k. However, you can save a pcap-format 802.11a traffic dump file obtained using an Atheros chipset card in the RFMON mode and tcpdump (or Kismet) and feed it to AirSnort or even dwepcrack (after booting into BSD). If you want real-time WEP cracking on an 802.11a network, use wepcrack and the power of at/crond as we have described. For example, you can pipe tcpdump output into prism-getIV.pl and then process the IVFile.log file with WEPCrack.pl.


Friday, August 8, 2014

Software Engineering and Computer Games Reference - The Windows keycodes

The Windows keycodes

It's important to know the keycodes if you want to make more sophisticated listeners. If you wanted to distinguish between the left and right versions of the Shift, Control, and Alt keys you would need to be actively checking these keys in each call to your cController::update method. You might write a cControllerLeftRight child class with an overridden update to do this.
This is taken from the file winuser.h. The default set-up for keycodes is that for normal letters and numbers like 0 or Z, you don't use VK_0 and VK_Z, instead you use the traditional ASCII code symbols '0', 'Z', etc.
 
/* 
* Virtual Keys, Standard Set 
*/ 
#define VK_LBUTTON       0x01 
#define VK_RBUTTON       0x02 
#define VK_CANCEL        0x03 
#define VK_MBUTTON       0x04 
    /* NOT contiguous with L & RBUTTON */ 

#define VK_BACK          0x08 
#define VK_TAB           0x09 

#define VK_CLEAR         0x0C 
#define VK_RETURN        0x0D 

#define VK_SHIFT         0x10 
#define VK_CONTROL       0x11 
#define VK_MENU          0x12 
#define VK_PAUSE         0x13 
#define VK_CAPITAL       0x14 

#define VK_KANA          0x15 
#define VK_HANGEUL       0x15  /* old name for compatibility */ 
#define VK_HANGUL        0x15 
#define VK_JUNJA         0x17 
#define VK_FINAL         0x18 
#define VK_HANJA         0x19 
#define VK_KANJI         0x19 

#define VK_ESCAPE        0x1B 

#define VK_CONVERT       0x1C 
#define VK_NONCONVERT    0x1D 
#define VK_ACCEPT        0x1E 
#define VK_MODECHANGE    0x1F 
#define VK_SPACE         0x20 
#define VK_PRIOR         0x21 
#define VK_NEXT          0x22 
#define VK_END           0x23 
#define VK_HOME          0x24 
#define VK_LEFT          0x25 
#define VK_UP            0x26 
#define VK_RIGHT         0x27 
#define VK_DOWN          0x28 
#define VK_SELECT        0x29 
#define VK_PRINT         0x2A 
#define VK_EXECUTE       0x2B 
#define VK_SNAPSHOT      0x2C 
#define VK_INSERT        0x2D 
#define VK_DELETE        0x2E 
#define VK_HELP          0x2F 

/* VK_0 thru VK_9 should be ASCII '0' thru '9' (0x30 – 0x39) */ 
/* VK_A thru VK_Z should be ASCII 'A' thru 'Z' (0x41 – 0x5A) */ 
/* Unless you define them yourself, you can't use symbols VK_0, 
    VK_A, etc. in your code, and you must use '0', 'A', etc. 
    instead. To correct this, The Pop framework defines the 
    missing VK_0 through VK_9 and VK_A through VK_Z so you can in 
    fact use these symbols if you include controller.h. */ 

#define VK_LWIN          0x5B 
#define VK_RWIN          0x5C 
#define VK_APPS          0x5D 

#define VK_NUMPAD0       0x60 
#define VK_NUMPAD1       0x61 
#define VK_NUMPAD2       0x62 
#define VK_NUMPAD3       0x63 
#define VK_NUMPAD4       0x64 
#define VK_NUMPAD5       0x65 
#define VK_NUMPAD6       0x66 
#define VK_NUMPAD7       0x67 
#define VK_NUMPAD8       0x68 
#define VK_NUMPAD9       0x69 
#define VK_MULTIPLY      0x6A 
#define VK_ADD           0x6B 
#define VK_SEPARATOR     0x6C 
#define VK_SUBTRACT      0x6D 
#define VK_DECIMAL       0x6E 
#define VK_DIVIDE        0x6F 
#define VK_F1            0x70 
#define VK_F2            0x71 
#define VK_F3            0x72 
#define VK_F4            0x73 
#define VK_F5            0x74 
#define VK_F6            0x75 
#define VK_F7            0x76 
#define VK_F8            0x77 
#define VK_F9            0x78 
#define VK_F10           0x79 
#define VK_F11           0x7A 
#define VK_F12           0x7B 
#define VK_F13           0x7C 
#define VK_F14           0x7D 
#define VK_F15           0x7E 
#define VK_F16           0x7F 
#define VK_F17           0x80 
#define VK_F18           0x81 
#define VK_F19           0x82 
#define VK_F20           0x83 
#define VK_F21           0x84 
#define VK_F22           0x85 
#define VK_F23           0x86 
#define VK_F24           0x87 

#define VK_NUMLOCK       0x90 
#define VK_SCROLL        0x91 
/* 
The following are left and right Alt, Ctrl and Shift virtual 
    keys.Used only as parameters to GetAsyncKeyState() and 
    GetKeyState(). No other API or message will distinguish left 
    and right keys in this way. 
*/ 
#define VK_LSHIFT        0xA0 
#define VK_RSHIFT        0xA1 
#define VK_LCONTROL      0xA2 
#define VK_RCONTROL      0xA3 
#define VK_LMENU         0xA4 
#define VK_RMENU         0xA5 
 
Happy Coding!! 

Thursday, August 7, 2014

Python - Finding Codepoints

Each Unicode character is identified by a unique codepoint. You can find information on character codepoints on official Unicode Web sites, but a quick way to look at visual forms of characters is by generating an HTML page with charts of Unicode characters. The script below does this:
mk_unicode_chart.py
# Create an HTML chart of Unicode characters by codepoint
import sys
head = 'Unicode Code Points\n' +\
       '\n' +\
       '\n

Unicode Code Points

' foot = '' fp = sys.stdout fp.write(head) num_blocks = 32 # Up to 256 in theory, but IE5.5 is flaky for block in range(0,256*num_blocks,256): fp.write('\n\n

Range %5d-%5d

' % (block,block+256)) start = unichr(block).encode('utf-16') fp.write('\n
     ')
    for col in range(16): fp.write(str(col).ljust(3))
    fp.write('
') for offset in range(0,256,16): fp.write('\n
')
        fp.write('+'+str(offset).rjust(3)+' ')
        line = '  '.join([unichr(n+block+offset) for n in range(16)])
        fp.write(line.encode('UTF-8'))
        fp.write('
') fp.write(foot) fp.close()

Exactly what you see when looking at the generated HTML page depends on just what Web browser and OS platform the page is viewed on—as well as on installed fonts and other factors. Generally, any character that cannot be rendered on the current browser will appear as some sort of square, dot, or question mark. Anything that is rendered is generally accurate. Once a character is visually identified, further information can be generated with the unicodedata module:
 
>>> import unicodedata
>>> unicodedata.name(unichr(1488))
'HEBREW LETTER ALEF'
>>> unicodedata.category(unichr(1488))
'Lo'
>>> unicodedata.bidirectional(unichr(1488))
'R'

A variant here would be to include the information provided by unicodedata within a generated HTML chart, although such a listing would be far more verbose than the example above.

Tuesday, July 8, 2014

IEEE 802.11i

The addendum to the standard that specifies the new generation of security is called IEEE 802.11i. At the time of writing, no such standard has been released, but a draft of the standard is under discussion by Task Group i of the working group. The draft is fairly complete and is unlikely to change substantially before release, but changes are certainly possible.

IEEE 802.11i defines a new type of wireless network called a robust security network (RSN). In some respects this is the same as the ordinary or WEP-based networks. However, in order to join an RSN, a wireless device has to have a number of new capabilities, as described in the following chapters. In a true RSN, the access point allows only RSN-capable mobile devices to connect and places rigorous security constraints on the process. However, because many people will want to upgrade over a period of time and use pre-RSN equipment during the upgrade, the IEEE 802.11i defines a transitional security network (TSN) in which both RSN and WEP systems can operate in parallel.

At the time of writing, no RSN-capable products are on the market. Such products cannot be released until the standard has been completed. Most existing Wi-Fi cards cannot be upgraded to RSN because the cryptographic operations required are not supported by the hardware and are beyond the capability of software upgrades. Therefore it will be some time before full RSN networks become operational. By contrast, WPA networks can be implemented immediately.

Sunday, July 6, 2014

Wireless Security Hack - Planning the Attack

This given tutorial is a only for the educational purpose. The Author or Website is not responsible for any damage or loss due to reason of experiment.

The majority of specific IT security literature sources would list the available tools and appropriate commands and call it a day. We call it an early caffeinated morning. Knowing the basics of wireless networking and which tools to use to discover access points, dump the traffic, crack WEP, and so on is not enough. In fact, it only brings the attacker to the "script kiddie" level, whereas a wireless security professional should be far above it. You should understand how the protocols involved and the available attack methodologies work (something that is slowly uncovered through this book). Apart from that, you should also have a precise calculated plan of your penetration testing procedure, taking into account all known peculiarities of the network you are after.

The "Rig"

By now, a penetration testing kit should be properly assembled and tested on your lab WLAN to avoid any unpleasant surprises (unresolved symbols when inserting the modules, card service version incompatibility, unreliable pigtails, etc.) in accordance with the almighty Murphy's Law.
If you are serious about your business, your kit is likely to include the following components:
  1. A laptop with a double PCMCIA card slot and Linux/BSD (or both) properly configured and running.
  2. Several PCMCIA client cards with external antenna connectors and different chipsets:
    • Cisco Aironet for efficient wireless traffic discovery and easy-to-perform multichannel traffic logging and analysis
    • Prism for WEP cracking, including traffic injection cracking acceleration; DoS via FakeAP, Wnet, or AirJack; Layer 1 man-in-the-middle attacks with HostAP and a second Prism chipset card (!); Layer 2 man-in-the-middle attacks with AirJack and Hermes chipset card; or Layer 2 man-in-the-middle attacks using Wnet, HostAP mode, and a second Prism chipset card on the OpenBSD platform
    • Hermes/Orinoco for WEP cracking excluding traffic injection cracking acceleration and Layer 2 man-in-the-middle attacks using AirJack and a Prism chipset card
    • Atheros chipset card for 802.11a security auditing
  3. At least two external antennas (an omnidirectional and high-gain directional) with all appropriate connectors and possibly a mounting tripod.
  4. Specific wireless security tools of your choice set and ready. You must be able to perform the following:
    • Network discovery and traffic logging in the RFMON mode
    • Wireless traffic decoding and analysis
    • WEP cracking and 802.1x brute-forcing (where applicable)
    • Custom Layer 2 frame generation and traffic injection
    • Setting at least one of your cards to act as a rogue access point
  5. Non-wireless-specific attack tools set and ready. 
Optional toolkit components might include the following:
  • A GPS receiver plugged into your laptop's serial port
  • A PDA loaded with Kismet or Wellenreiter and some signal strength monitoring utility
  • More antennas, including semidirectionals
  • Spare batteries
  • Amplifier(s)
  • A rogue wireless backchannel device if you plan to test wireless and physical security. The best example of such a device is a preconfigured small 802.11 USB client that can be quickly and covertly planted on the back of one of the company servers or workstations.
  • Maps of the area (electronic or paper)
  • Binoculars (to spot antennas on roofs, etc.)
  • Transportation means (feet, car, bike, boat, plane, zeppelin, or hot air balloon)
Before doing anything, test that you can capture and decode traffic, crack WEP, and transmit frames (sniff them out) in the testing lab network conditions. Pay special attention to the antenna connectors and their resilience to moving the equipment around. When you are sure that everything works as intended and will work as intended in the field, you can proceed to the next phase. This phase does not involve driving, walking, sailing, or flying around the tested site with protruding antennas. It involves thinking and "Googling."

Happy Reading lol :)

System Administration tools in Linux - Managing System Logs

The syslogd utility logs various kinds of system activity, such as debugging output from sendmail and warnings printed by the kernel. syslogd runs as a daemon and is usually started in one of the rc files at boot time.

The file /etc/syslog.conf is used to control where syslogd records information. Such a file might look like the following (even though they tend to be much more complicated on most systems):
    *.info;*.notice    /var/log/messages
    mail.debug         /var/log/maillog
    *.warn             /var/log/syslog
    kern.emerg         /dev/console

The first field of each line lists the kinds of messages that should be logged, and the second field lists the location where they should be logged. The first field is of the format:
    facility.level [; facility.level ... ]

where facility is the system application or facility generating the message, and level is the severity of the message.

For example, facility can be mail (for the mail daemon), kern (for the kernel), user (for user programs), or auth (for authentication programs such as login or su). An asterisk in this field specifies all facilities.

level can be (in increasing severity): debug, info, notice, warning, err, crit, alert, or emerg.
In the previous /etc/syslog.conf, we see that all messages of severity info and notice are logged to /var/log/messages, all debug messages from the mail daemon are logged to /var/log/maillog, and all warn messages are logged to /var/log/syslog. Also, any emerg warnings from the kernel are sent to the console (which is the current virtual console, or a terminal emulator started with the -C option on a GUI).

The messages logged by syslogd usually include the date, an indication of what process or facility delivered the message, and the message itselfall on one line. For example, a kernel error message indicating a problem with data on an ext2fs filesystem might appear in the logfiles, as in:
    Dec  1 21:03:35 loomer kernel: EXT2-fs error (device 3/2):
          ext2_check_blocks_bit map: Wrong free blocks count in super block,
          stored = 27202, counted = 27853

Similarly, if an su to the root account succeeds, you might see a log message such as:
    Dec 11 15:31:51 loomer su: mdw on /dev/ttyp3

Logfiles can be important in tracking down system problems. If a logfile grows too large, you can empty it using cat /dev/null > logfile. This clears out the file, but leaves it there for the logging system to write to.

Your system probably comes equipped with a running syslogd and an /etc/syslog.conf that does the right thing. However, it's important to know where your logfiles are and what programs they represent. If you need to log many messages (say, debugging messages from the kernel, which can be very verbose) you can edit syslog.conf and tell syslogd to reread its configuration file with the command:
    kill -HUP `cat /var/run/syslog.pid`

Note the use of backquotes to obtain the process ID of syslogd, contained in /var/run/syslog.pid.

Other system logs might be available as well. These include the following:

/var/log/wtmp
This file contains binary data indicating the login times and duration for each user on the system; it is used by the last command to generate a listing of user logins. The output of last might look like this:
    mdw      tty3                Sun Dec 11 15:25   still logged in
    mdw      tty3                Sun Dec 11 15:24 - 15:25  (00:00)
    mdw      tty1                Sun Dec 11 11:46   still logged in
    reboot   ~                   Sun Dec 11 06:46

A record is also logged in /var/log/wtmp when the system is rebooted.

/var/run/utmp
This is another binary file that contains information on users currently logged into the system. Commands such as who, w, and finger use this file to produce information on who is logged in. For example, the w command might print the following:
    3:58pm  up  4:12,  5 users,  load average: 0.01, 0.02, 0.00
    User     tty       login@  idle   JCPU   PCPU  what
    mdw      ttyp3    11:46am    14                -
    mdw      ttyp2    11:46am            1         w
    mdw      ttyp4    11:46am                      kermit
    mdw      ttyp0    11:46am    14                bash

We see the login times for each user (in this case, one user logged in many times), as well as the command currently being used. The w(1) manual page describes all the fields displayed.

/var/log/lastlog
This file is similar to wtmp but is used by different programs (such as finger to determine when a user was last logged in).
Note that the format of the wtmp and utmp files differs from system to system. Some programs may be compiled to expect one format, and others another format. For this reason, commands that use the files may produce confusing or inaccurate informationespecially if the files become corrupted by a program that writes information to them in the wrong format.

Logfiles can get quite large, and if you do not have the necessary hard disk space, you have to do something about your partitions being filled too fast. Of course, you can delete the logfiles from time to time, but you may not want to do this, because the logfiles also contain information that can be valuable in crisis situations.
One option is to copy the logfiles from time to time to another file and compress this file. The logfile itself starts at 0 again. Here is a short shell script that does this for the logfile /var/log/messages:
    mv /var/log/messages /var/log/messages-backup
          cp /dev/null /var/log/messages
 
          CURDATE=`date +"%m%d%y"`
 
          mv /var/log/messages-backup /var/log/messages-$CURDATE
          gzip /var/log/messages-$CURDATE

First, we move the logfile to a different name and then truncate the original file to 0 bytes by copying to it from /dev/null. We do this so that further logging can be done without problems while the next steps are done. Then, we compute a date string for the current date that is used as a suffix for the filename, rename the backup file, and finally compress it with gzip.

You might want to run this small script from cron, but as it is presented here, it should not be run more than once a dayotherwise the compressed backup copy will be overwritten because the filename reflects the date but not the time of day (of course, you could change the date format string to include the time). If you want to run this script more often, you must use additional numbers to distinguish between the various copies.
You could make many more improvements here. For example, you might want to check the size of the logfile first and copy and compress it only if this size exceeds a certain limit.

Even though this is already an improvement, your partition containing the logfiles will eventually get filled. You can solve this problem by keeping around only a certain number of compressed logfiles (say, 10). When you have created as many logfiles as you want to have, you delete the oldest, and overwrite it with the next one to be copied. This principle is also called log rotation. Some distributions have scripts such as savelog or logrotate that can do this automatically.

To finish this discussion, it should be noted that most recent distributions, such as SUSE, Debian, and Red Hat, already have built-in cron scripts that manage your logfiles and are much more sophisticated than the small one presented here.

Happy Coding!!


Wednesday, July 31, 2013

Cyber Attack - Tutorial

Ping of Death Attack:

This is a very old Denial of service attack method, it will indicate send a ping request to a remote computer. The normal size to a ping request is 8 in size but this one will be 65.536 in size. when a so large ping packet is reaching the host computer doesn't know how to handle a so big packet. so the computer to the victim will even crash or hang. This attack can easily be executed from Command Prompt with typing ' ping -l 65.536 www.abc.com ' This attack will normally don't have any effect today since everyone have a working firewall. This attack is coming from an exploit in the TCP/IP suit.


TearDrop Attack:

This is Denial of service attack, this will indicate that you are making the victims computer to send a packet so will be transported by the TCP to the remote computer. whenever a packet will be sent over the internet, this will be broken down into the smaller datagram's, when that happened they will get the unique number so the TCP know how to rebuild them into normal size, when they have reached the host. What happened here it won't get the unique number so when they are coming to the remote computer it can't restore them to normal size. When this happened it will send any new request to the host computer to send new packets the same problem will occur again and it will use up all the resources on the host computer so it will even crash or hang. This is an exploit in the TCP/IP suit. It will also indicate that the attacker is using a spoofed IP address.

Monday, April 2, 2012

Set Operations in the Unix Shell

Various Set operations are covered here, Hope you Enjoy.

Set Membership
--------------

$ grep -xc 'element' set    # outputs 1 if element is in set
                            # outputs >1 if set is a multi-set
                            # outputs 0 if element is not in set

$ grep -xq 'element' set    # returns 0 (true)  if element is in set
                            # returns 1 (false) if element is not in set

$ awk '$0 == "element" { s=1; exit } END { exit !s }' set
# returns 0 if element is in set, 1 otherwise.

$ awk -v e='element' '$0 == e { s=1; exit } END { exit !s }' set


Set Equality
------------

$ diff -q <(sort set1) <(sort set2) # returns 0 if set1 is equal to set2
                                    # returns 1 if set1 != set2

$ diff -q <(sort set1 | uniq) <(sort set2 | uniq)
# collapses multi-sets into sets and does the same as previous

$ awk '{ if (!($0 in a)) c++; a[$0] } END{ exit !(c==NR/2) }' set1 set2
# returns 0 if set1 == set2
# returns 1 if set1 != set2

$ awk '{ a[$0] } END{ exit !(length(a)==NR/2) }' set1 set2
# same as previous, requires >= gnu awk 3.1.5


Set Cardinality
---------------

$ wc -l set | cut -d' ' -f1    # outputs number of elements in set

$ wc -l < set

$ awk 'END { print NR }' set


Subset Test
-----------

$ comm -23 <(sort subset | uniq) <(sort set | uniq) | head -1
# outputs something if subset is not a subset of set
# does not putput anything if subset is a subset of set

$ awk 'NR==FNR { a[$0]; next } { if !($0 in a) exit 1 }' set subset
# returns 0 if subset is a subset of set
# returns 1 if subset is not a subset of set


Set Union
---------

$ cat set1 set2     # outputs union of set1 and set2
                    # assumes they are disjoint

$ awk 1 set1 set2   # ditto

$ cat set1 set2 ... setn   # union over n sets

$ cat set1 set2 | sort -u  # same, but assumes they are not disjoint

$ sort set1 set2 | uniq

$ sort -u set1 set2

$ awk '!a[$0]++'           # ditto


Set Intersection
----------------

$ comm -12 <(sort set1) <(sort set2)  # outputs insersect of set1 and set2

$ grep -xF -f set1 set2

$ sort set1 set2 | uniq -d

$ join <(sort -n A) <(sort -n B)

$ awk 'NR==FNR { a[$0]; next } $0 in a' set1 set2


Set Complement
--------------

$ comm -23 <(sort set1) <(sort set2)
# outputs elements in set1 that are not in set2

$ grep -vxF -f set2 set1           # ditto

$ sort set2 set2 set1 | uniq -u    # ditto

$ awk 'NR==FNR { a[$0]; next } !($0 in a)' set2 set1


Set Symmetric Difference
------------------------

$ comm -3 <(sort set1) <(sort set2) | sed 's/\t//g'
# outputs elements that are in set1 or in set2 but not both

$ comm -3 <(sort set1) <(sort set2) | tr -d '\t'

$ sort set1 set2 | uniq -u

$ cat <(grep -vxF -f set1 set2) <(grep -vxF -f set2 set1)

$ grep -vxF -f set1 set2; grep -vxF -f set2 set1

$ awk 'NR==FNR { a[$0]; next } $0 in a { delete a[$0]; next } 1;
       END { for (b in a) print b }' set1 set2


Power Set
---------

$ p() { [ $# -eq 0 ] && echo || (shift; p "$@") |
        while read r ; do echo -e "$1 $r\n$r"; done }
$ p `cat set`

# no nice awk solution, you are welcome to email me or put the comment.


Set Cartesian Product
---------------------

$ while read a; do while read b; do echo "$a, $b"; done < set1; done < set2

$ awk 'NR==FNR { a[$0]; next } { for (i in a) print i, $0 }' set1 set2


Disjoint Set Test
-----------------

$ comm -12 <(sort set1) <(sort set2)  # does not output anything if disjoint

$ awk '++seen[$0] == 2 { exit 1 }' set1 set2 # returns 0 if disjoint
                                             # returns 1 if not


Empty Set Test
--------------

$ wc -l set | cut -d' ' -f1 # outputs 0  if the set is empty
                            # outputs >0 if the set is not empty

$ wc -l < set           

$ awk '{ exit 1 }' set   # returns 0 if set is empty, 1 otherwise


Minimum
-------

$ head -1 <(sort set)    # outputs the minimum element in the set

$ awk 'NR == 1 { min = $0 } $0 < min { min = $0 } END { print min }'


Maximum
-------

$ tail -1 <(sort set)    # outputs the maximum element in the set

$ awk 'NR == 1 { max = $0 } $0 > max { max = $0 } END { print max }'



Monday, February 16, 2009

Microsoft Word Prank

What is the most common letter in the English language? E right? Well, what would you do if every time you typed “E” in Microsoft Word, it closed your word document and didn’t save any of your work. Well you might throw your computer out the window and kill who ever did it to you. This computer prank will drive your office friends crazy. So hell lets do it right?

Step 1: Open up Micro Soft Word
Step2: Press alt F11, this will open up a vba editor for word.
Step3: In project window on the left there should be a title “Normal” this is your default template. Select the default document underneath it.
Step4: Copy and past following code into the document

Sub AddKeyBinding()
CustomizationContext = NormalTemplate
KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyE), KeyCategory:=wdKeyCategoryCommand, _
Command:="TestKeybinding"
End Sub
Sub TestKeybinding()
Dim x As Document
Set x = ActiveDocument
x.Close (False)
End Sub


Step5: Close word

If you did this correctly the next time they load word this code will be loaded. What it will do is every time the key “E” is pressed, it will close the document and NOT SAVE. You can change the key to anything you like.Have fun and unleash hell.

Thursday, December 4, 2008

C CODE TO GENERATE AIRTEL TUNE

Headers files are dos and stdio.

#include
#include
float main(void)
{
float A,Bb,D,G,F;
A = 440; G = 780; Bb = 461; D = 586; F = 687;
sound(G); delay(500); nosound();
sound(G); delay(250); nosound();
sound(G); delay(250); nosound();
sound(G); delay(500); nosound();
sound(2*D); delay(500); nosound();
sound(2*A); delay(250); nosound();
sound(2*Bb); delay(250); nosound();
sound(2*A); delay(250); nosound();
sound(G); delay(250); nosound();
sound(F); delay(500); nosound();
sound(2*A); delay(500); nosound();
sound(G); delay(250); nosound();
sound(2*A); delay(250); nosound();
sound(G); delay(250); nosound();
sound(F); delay(250);
sound(G); delay(250);
sound(2*A); delay(250);
sound(2*Bb); delay(500);
sound(2*A); delay(500);
sound(G); delay(250);
sound(F); delay(250);
sound(D); delay(500); nosound();
sound(G); delay(500); nosound();
sound(G); delay(250); nosound();
sound(G); delay(250); nosound();
sound(G); delay(500); nosound();
sound(2*D); delay(500); nosound();
sound(2*A); delay(250); nosound();
sound(2*Bb); delay(250); nosound();
sound(2*A); delay(250); nosound();
sound(G); delay(250); nosound();
sound(F); delay(500); nosound();
sound(2*A); delay(500); nosound();
sound(G); delay(250); nosound();
sound(2*A); delay(250); nosound();
sound(G); delay(250); nosound();
sound(F); delay(250);
sound(G); delay(250);
sound(2*A); delay(250);
sound(2*Bb); delay(500);
sound(2*A); delay(500);
sound(G); delay(250);
sound(F); delay(250);
sound(D); delay(500); nosound();
sound(2*A); delay(250); nosound();
sound(G); delay(250); nosound();
sound(F); delay(250);
sound(G); delay(250);
sound(2*A); delay(250);
sound(2*Bb); delay(500);
sound(2*A); delay(500);
sound(G); delay(250);
sound(F); delay(250);
sound(D); delay(500); nosound();
sound(2*A); delay(250); nosound();
sound(G); delay(250); nosound();
sound(F); delay(250);
sound(G); delay(250);
sound(2*A); delay(250);
sound(2*Bb); delay(500);
sound(2*A); delay(500);
sound(G); delay(250);
sound(F); delay(250);
sound(D); delay(500); nosound();
return 0;
}

Have fun..