Friday, April 2, 2010

Mozilla pegs worldwide Firefox share at 30%

Mozilla estimates that Firefox now handles almost 30 per cent of worldwide web access.

On Wednesday, the open source outfit released its first ever quarterly analyst report (pdf), a collection of web-happy stats dubbed The State of the Internet. Crunching data from four separate online research houses - StatCounter, Quantcast, Net Applications, and Gemius - Mozilla says that its influence is the strongest in Europe, where it spans 39.2 per cent of the browser market.

Next comes South America at 31.1 per cent and then Africa at 29.7 per cent, with North America bringing up the rear at 26 per cent. Mozilla does not provide official numbers on Antarctica, but StatCounter says that on the bottom of the earth, Firefox has an 80 per cent share. Which only makes sense. Open source keeps you warm.

According to Mozilla, Firefox usage is growing most rapidly in Russia, where uptake spiked 20 per cent this quarter. Mozilla guesses this has something to do with chairperson Mitchell Baker's visit to the country in February. Now if we could only get her to visit all those companies still running IE6.

Russia, incidentally, is one place where Google is not the browser's default search engine. All those clicks are going to the native Yandex.

Indonesia, India, the Philippines, Australia, Mexico, and Turkey also showed Firefoxian growth in access of 15 per cent during the quarter. And according to the report, Asians are the most likely to beef up their browsers with add-ons - unless you consider that small sample size in Antarctica. Since January, Mozilla has seen 538 Antarctic add-on downloads from the continent's 1,000 inhabitants.

A recent Mozilla Labs study indicates that the average Firefox user has two to three tabs open at a time. But one unnamed participant went so far as to open 600. Presumably, none of the 600 were running Flash.

Mozilla pegs worldwide Firefox share at 30%

Mozilla estimates that Firefox now handles almost 30 per cent of worldwide web access.

On Wednesday, the open source outfit released its first ever quarterly analyst report (pdf), a collection of web-happy stats dubbed The State of the Internet. Crunching data from four separate online research houses - StatCounter, Quantcast, Net Applications, and Gemius - Mozilla says that its influence is the strongest in Europe, where it spans 39.2 per cent of the browser market.

Next comes South America at 31.1 per cent and then Africa at 29.7 per cent, with North America bringing up the rear at 26 per cent. Mozilla does not provide official numbers on Antarctica, but StatCounter says that on the bottom of the earth, Firefox has an 80 per cent share. Which only makes sense. Open source keeps you warm.

According to Mozilla, Firefox usage is growing most rapidly in Russia, where uptake spiked 20 per cent this quarter. Mozilla guesses this has something to do with chairperson Mitchell Baker's visit to the country in February. Now if we could only get her to visit all those companies still running IE6.

Russia, incidentally, is one place where Google is not the browser's default search engine. All those clicks are going to the native Yandex.

Indonesia, India, the Philippines, Australia, Mexico, and Turkey also showed Firefoxian growth in access of 15 per cent during the quarter. And according to the report, Asians are the most likely to beef up their browsers with add-ons - unless you consider that small sample size in Antarctica. Since January, Mozilla has seen 538 Antarctic add-on downloads from the continent's 1,000 inhabitants.

A recent Mozilla Labs study indicates that the average Firefox user has two to three tabs open at a time. But one unnamed participant went so far as to open 600. Presumably, none of the 600 were running Flash.

Red Hat injects RHEL with new iron love

Red Hat has pushed out another rev of its Linux variant. With Enterprise Linux 5.5, support for the latest processors from Advanced Micro Devices, Intel, and IBM has been back-ported to the Linux 2.6.18 at the heart of the RHEL 5 stack.

According to Tm Burke, vice president of platform engineering at Red Hat, the kernel in RHEL 5.5 has been improved, and it now includes features from more current Linux kernels, so it's not particularly fair to call it Linux 2.6.18. The point is that any application that was certified to run on Linux 2.6.18 or later, possibly many years ago, will work on RHEL 5.5 and still have support for new hardware like the Power7 processors from IBM that debuted back in February, the "Westmere-EP" Xeon 5600s from Intel that came out two weeks ago, the "Magny-Cours" Opteron 6100s from AMD that launched earlier this week, and the "Nehalem-EX" Xeon 7500s that were announced yesterday.

Because machines based on the Opteron 6100s, Xeon 7500, and Power7 processors all use a form of non-uniform memory access (NUMA) memory sharing across multiple processor sockets and also have multiple cores and caches inside sockets, RHEL 5.5 includes a lot of work that makes the operating system very aware of the system topology so memory allocation and job scheduling is done such that instruction streams and their data are placed as close together as possible. The kernel also has tweaks that try to cram as much work on as few cores as possible, allowing for servers to conserve power as they dial down or quiesce cores in the systems.

The updated RHEL also has a lot of I/O optimizations to take advantage of virtual I/O hardware features in the most current x64 and Power processors, which cuts down on I/O overhead in virtualized environments. In I/O-heavy virtualized workloads where the I/O was virtualized in software, rather than on the chip, the I/O overhead could be as high as 30 per cent, which is unacceptable.

Burke says that with these tweaks for I/O virtualization, which include a feature called Single Root I/O Virtualization (SR-IOV), a guest operating system running inside either a Xen or KVM hypervisor embedded in RHEL 5.5 can drive a 10 Gigabit Ethernet adapter card to its saturation point, and Burke claims this is the only hypervisor environment today that can do this. (That won't last for long, with RHEL being open source).

While the freestanding KVM hypervisor at the heart of the Red Hat Enterprise Virtualization, or RHEV, product was updated with a beta of its own 2.2 release using the RHEL 5.5 kernel earlier this week, RHEL 5.5 is available today and supports fatter guest virtual machines. The RHEV 2.2 beta can support 16 virtual CPUs and up to 256 GB of memory per guest, but RHEL 5.5 can support 32 physical processor cores and up to 512 GB of memory on either a Xen or KVM guest.

The bare-metal RHEL 5.5 kernel can support up to 1 TB of physical memory and can support well beyond the current top-end 64 sockets delivered today in eight-way Xeon 7500 systems. The open source community has already figured out how to do 512-core NUMA systems for the Itanium chips and is leveraging this work as x64 architectures get fatter. The RHEL 5 kernel has a stunning theoretical maximum of 32,000 threads that it can support, which is well beyond anything any server maker can put into the field in a single system image. Later this year, IBM's top-end Power 795 systems will have 32 sockets with a total of 256 cores and 1,024 threads.

The largest general-purpose Xeon 7500 machines will have maybe 64-sockets, which means 512 cores and 1,024 threads, and it looks like Itanium 9300 machines will probably top out at 64 sockets as well, but those quad-core chips only have eight threads, so that's a maximum of 512 threads. AMD is topped out at 40 threads in four-socket boxes with the Opteron 6100s. That will barely tickle the limits of RHEL 5.5.

By the way, RHEL 4 is not getting support for all this new iron, since Red Hat stopped doing major backporting to this early RHEL version six months ago. At some point, says Burke, the changes that would be necessary make new hardware work on the older versions without breaking application compatibility would involve way too much work or not be possible at all.

In general, a RHEL version gets three years of cutting-edge hardware support (roughly updated every six months), one year of transitional support where major hardware enablement and driver work is done, but perhaps not the greatest amount of tuning, and then three years where the version is in maintenance mode, with bug fixes and security patches. The expectation is that RHEL 5 will have a couple more years of hardware maintenance, but it really depends on how radical the hardware changes are in the future. If the changes are too radical, RHEL 5 gets sent to pasture sooner.

In addition to the updated hardware support, RHEL 5.5 has pulled in OpenOffice 3.1, which has better compatibility with Microsoft's Office 2007 formats, and the Samba print and file server has been updated to work with Windows 7. The SystemTap dynamic tracing tool that is part of the development stack in RHEL has also been enhanced so it can probe and poke C++ applications, rather than just C apps. The GDB debugger also has better support for C++ applications in that it allows developers to debug one thread at a time instead of having to suspend all threads in C++ code at the same time.

Trojan poses as Adobe update utility

Miscreants have begun creating malware that overwrites software update applications from Adobe and others.

Email malware that poses as security updates from trusted companies is a frequently used hacker ruse. Malware posing as update utilities, rather than individual updates, represents a new take on the ruse.

Vietnam-based anti-virus firm Bkis said the tactic is a logical follow-on from earlier approaches where viruses replace system-files and startup-program files.

Nguyen Minh Duc, director of Bkis Security, writes that the recently detected Fakeupver trojan establishes a backdoor on compromised systems while camouflaging its presence by posing as an Adobe update utility. The malware camouflages itself by using the same icons and version number as the official package.

Variants of the malware also pose as updaters for Java and other software applications.

Duc explains: "From analysis, we found that malware is written in Visual Basic, faking such popular programs as Adobe, DeepFreeze, Java, Windows, etc. In addition, on being executed, they immediately turn on the following services: DHCP client, DNS client, Network share and open port to receive hacker’s commands."

source : theregister.co.uk

Hacker's record credit card theft fetches 20-year sentence

Confessed TJX hacker Albert Gonzalez was sentenced to 20 years in federal prison for orchestrating one of the largest thefts of payment card numbers in history.

The sentence, by US District Court Judge Patti Saris, is the lengthiest to be imposed in a US hacking or identity prosecution. Miami-based Gonzalez was also fined $25,000 and still faces restitution charges that could be in the tens of millions of dollars.

Prosecutors told the judge Gonzalez should receive 25 years because he victimized millions of people and cost banks and their insurers as much as $200m. His attorney, Martin Weinberg, challenged that estimate and presented evidence his client suffered from Asperger's Syndrome, a form of autism.

Last year, Gonzalez pleaded guilty in three separate cases brought in Massachusetts, New Jersey and New York. Thursday's sentence in Boston dealt only with the Massachusetts case. A hearing scheduled for Friday will deal with the other two prosecutions.

Prosecutors said Gonzalez led a gang of hackers who conducted war-driving campaigns that identified retailers with weak wireless networks. They then penetrated those networks and installed sniffer programs that siphoned millions of credit and debit card numbers as they were being zapped to payment processors.

The operation targeted a variety of retailers and restaurants including TJX Cos. and BJ's Wholesale Club, Office Max, Barnes & Noble and Dave & Busters restaurant chain. Thursday's sentence came the same day Dave & Busters agreed to implement a comprehensive security program to settle US Federal Trade Commission charges the restaurant left consumers vulnerable to credit card thieves.

source : theregister.co.uk

Hackers hit where they live

The countries of hackers originating malware-laced spam runs have been exposed by new research, which confirms they are often located thousands of miles away from the compromised systems they use to send out junk mail.

A third of targeted malware attacks sent so far in March came from the United States (36.6 per cent), based on mail server location. However, after the sender's actual location is analysed, more targeted attacks actually began in China (28.2 per cent) and Romania (21.1 per cent) than the US (13.8 percent), according to the March 2010 edition of the monthly MessageLabs security report.

Paul Wood, MessageLabs intelligence senior analyst, explained the discrepancy: “A large proportion of targeted attacks are sent from legitimate webmail accounts which are located in the US and therefore, the IP address of the sending mail server is not a useful indicator of the true origin of the attack.

"Analysis of the sender’s IP address, rather than the IP address of the email server, reveals the true source of these targeted attacks.”

Further analysis of targeted attacks shows people at the sharp end of targeted malware attacks are responsible for foreign trade and defence policy, especially in relation to Asian countries. Virus activity in Taiwan was one in 90.9 emails, making it the most targeted country for email-borne malware in March. By comparison, one in 552 emails sent to US mailboxes came laced with malware.

Meanwhile, one in 77.1 emails sent to public sector mailboxes were blocked as malicious by MessageLabs.

The worldwide ratio of email-borne viruses to regular email traffic was one in 358.3 emails (0.28 per cent) in March, an decrease of 0.05 percentage points since February. In March 16.8 percent of email-borne malware contained links to malicious websites, a big decrease of 13.7 percentage points since February.

Spam rates after connections to known black spots were taken out of the picture reached 90.7 per cent, an increase of 1.5 percentage points since February. The vast majority of these junk mail messages came from compromised malware-infested networks of zombie PCs (aka botnets) MessageLabs reports that 77 per cent of spam sent from the Rustock botnet this month used secure TLS connections.

The average additional inbound and outbound traffic due to TLS requires an overhead of around 1KB, smaller than the average size of spam emails, and putting an added strain on already pressured email servers. Spam sent using TLS accounted for approximately 20 per cent of all junk mail so far in March, peaking at 35 per cent on March 10.

“TLS is a popular way of sending email through an encrypted channel," Wood said. “However, it uses far more server resources and is much slower than plain-text email and requires both inbound and outbound traffic. The outbound traffic frequently outweighs the size of the spam message itself and can significantly tax the workload on corporate email servers.”

source : theregister.co.uk

Microscope-wielding boffins crack cordless phone crypto DECT vivisection

Cryptographers have broken the proprietary encryption used to prevent eavesdropping on more than 800 million cordless phones worldwide, demonstrating once again the risks of relying on obscure technologies to remain secure.

The attack is the first to crack the cipher at the heart of the DECT, or Digital Enhanced Cordless Telecommunications, standard, which encrypts radio signals as they travel between cordless phones in homes and businesses and corresponding base stations. A previous hack, by contrast, merely exploited weaknesses in the way the algorithm was implemented.

The fatal flaw in the DECT Standard Cipher is its insufficient amount of "pre-ciphering," which is the encryption equivalent of shaking a cup of dice to make sure they generate unpredictable results. Because the algorithm discards only the first 40 or 80 bits during the encryption process, it's possible to deduce the secret key after collecting and analyzing enough of the protected conversation.

"This standard, as with everything else we have broken, has been designed some 20 years ago, and it is proprietary encryption," said Karsten Nohl, one of the cryptographers who helped devise the attack. "It relied on the fact that the encryption was unknown and hence could not be broken. This is a case where something that has some potential for being strong is broken by just this one design decision that in any public review would have been spotted immediately."

Nohl, 28, is the same University of Virginia microscope-wielding reverse engineer to crack the encryption in the world's most widely used smartcard. In December, he struck again after devising a practical attack for eavesdropping on cellphone calls.

He and fellow researchers Erik Tews of the Darmstadt University of Technology and Ralf-Philipp Weinmann of the University of Luxembourg, plan to present their findings Monday at the 2010 Fast Software Encryption workshop in Korea.

Like several of Nohl's previous hacks, it began with nitric acid and an electron optical microscope. After dissolving away the epoxy on the silicon chip and then shaving down and magnifying the section dedicated to the DECT encryption, he was able to glean key insights into the underlying algorithm. He then compared the findings against details selectively laid out in a patent and exposed during a debug process.

The results of all three probe methods revealed the fatally insufficient amount of pre-ciphering in the DECT Standard Cipher.

In practical terms, the attack works by collecting bits of the encrypted data stream with known unencrypted contents. In cordless phones, this often comes from a device's control channel, which broadcasts a variety of predictable data, including call duration and button responses. Sniffing an encrypted conversation with a USRP antenna and the average PC, an attacker would need to collect about four hours of data to break the key in typical scenarios.

In others - such as where DECT is used in restaurants and bars to wirelessly zap payment card details - the time needed to crack the key could be dramatically shorter, Nohl said. The time can also be sped up in a variety of other ways, including by adding certain types of graphics cards to beef up the power of the attacking PC. In some cases, the attack can retrieve the secret key in 10 minutes.

"We expect that some smarter cryptographers than ourselves will find better attacks, of course," Nohl told El Reg. "We found the algorithm and then implemented the first attack. It's almost guaranteed that this is not the best attack."

The DECT Forum, the international body that oversees the standard, said it takes the attack scenarios laid out in the paper seriously and "continues to investigate their applicability."

The crack of DECT is only the latest time Nohl has defeated the proprietary encryption of a device with critical mass. His 2008 attack on the Mifare Classic smartcard used similar techniques of filing down a silicon chip and then tracing the connections between transistors. His proposed attack of GSM encryption affects cellphones used by more than 800 carriers in 219 countries.

Open Source Keykeriki Captures Wireless Keyboard Traffic

Another interesting attack, rather than going after the PC/Server this one goes after the data sent by wireless devices such as the wireless keyboards sold by Microsoft. The neat thing is by using a replay attack you could also send rogue inputs to the device.

But then it serves Microsoft right for using XOR encryption for the data-steams, which can very easily be broken using frequency analysis.

Security researchers on Friday unveiled an open-source device that captures the traffic of a wide variety of wireless devices, including keyboards, medical devices, and remote controls.

Keykeriki version 2 captures the entire data stream sent between wireless devices using a popular series of chips made by Norway-based Nordic Semiconductor. That includes the device addresses and the raw payload being sent between them. The open-source package was developed by researchers of Switzerland-based Dreamlab Technologies and includes complete software, firmware, and schematics for building the $100 sniffer.

Keykeriki not only allows researchers or attackers to capture the entire layer 2 frames, it also allows them to send their own unauthorized payloads. That means devices that don’t encrypt communications – or don’t encrypt them properly – can be forced to cough up sensitive communications or be forced to execute rogue commands.

It’ll be interesting to see what other kinds of devices they can successfully use this data capture technique on. Keyboards are one thing, and I’d imagine the transmission range of a wireless keyboard is fairly limited so you or the sniffing device would have to be physically near to the target.

At least Logitech seem to have stepped up the security a bit by using AES-128 for the transmission on their wireless keyboards, but the researchers say they still may be able to crack it due to the way the secret keys are exchanged.

Again most likely not an algorithm problem but an issue with the implementation.

At the CanSecWest conference in Vancouver, Dreamlab Senior Security Expert Thorsten Schroder demonstrated how Keykeriki could be used to attack wireless keyboards sold by Microsoft. The exploit worked because communications in the devices are protected by a weak form of encryption known as xor, which is trivial to break. As a result, he was able to intercept keyboard strokes as they were typed and to remotely send input that executed commands on the attached computer.

“Microsoft made it easy for us because they used their own proprietary crypto,” Schroder said. “Xor is not a very proper way to secure data.”

Even when devices employ strong cryptography, Schroder said Keykeriki may still be able to remotely send unauthorized commands using a technique known as a replay attack, in which commands sent previously are recorded and then sent again.

News time is always fun during conference season due to the fact all these interesting and new attacks and vectors are released for public consumption – generally along with code and examples.

If they can use the same techniques to own more interesting devices with more sensitive data, things could certainly get a little more heated.

source : darknet.org.uk

Automated Scanning vs the OWASP Top Ten

The OWASP Top Ten is a list of the most critical website security flaws – a list also often used as a minimum standard for website vulnerability assessment (VA) and compliance. There is an ongoing industry dialog about the possibility of identifying the OWASP Top Ten in a purely automated fashion (scanning). People frequently ask what can and can’t be found using either white box or black box scanners. This is important because a single missed vulnerability, or more accurately exploited vulnerability, can cause an organization significant financial harm. Proper expectations must be set when it comes to the various vulnerability assessment solutions.

For our part, WhiteHat Security is in the website security business and provides a vulnerability management service. Our Sentinel Service incorporates expert analysis with proprietary scanning technology. Using a black box process, we assess hundreds of websites a month, more than anyone in the industry. What we’ve come to understand is that a significant portion of vulnerabilities are virtually impossible for scanners to find. By the same token, even the most seasoned Web security experts cannot find many issues in a reliable and consistent manner. To achieve full vulnerability coverage and therefore complete vulnerability management, we must rely on a combination and integration of both methods.

We’d like to share some of our experiences that led to this conclusion. Using situations we’ve seen in the real world, and the OWASP Top Ten as a baseline, we’ll demonstrate why scanning technology alone cannot find the OWASP Top Ten. To begin, we’ll focus on a single feature of a fictitious Web Bank responsible for funds transfers from one account to another account. Here is the full URL:

http://server/transfer.cgi?from_acct=1235813&to_acct=31415&amount=
1000.00&session=1001

The “from_acct” is the current user’s account number. “to_acct” is where the money should be sent. “Amount” is obviously the transfer amount, and the “session” is the authenticated session ID after having properly logged-in. This is a fairly typical and straightforward business process.


Unvalidated Input

Scanners must hazard a guess about what “transfer.cgi” does. Otherwise, it would be impossible to determine what it should NOT do.

A website security expert can easily figure this out, but scanners aren’t equipped with that intelligence: There is no knowledge of or appreciation for context. For the sake of discussion, let’s say a scanner has the ability, because there’s a dollar figure present and the “transfer” keyword in the URL might help it decide that this feature moves money. Realistically, these parameter names could be anything and are often far more cryptic. To attempt a classic funds transfer attack, let’s change the above URL substituting the “1000.00” amount to “-1000.00.”



Negative Amount Example:
http://server/transfer.cgi?from_acct=1235813&to_acct=31415&amount=-1000.00&session=1001

By transferring a negative amount, this custom Web application would potentially deduct money from the target account instead of adding to it! The challenge for a scanner is being able to decide whether or not the attack succeeded. How would it tell?

If the fraudulent transfer succeeded, the website might respond with, “Success, would you like to make another transaction?,” “Transfer will take place by 9 AM tomorrow,” “Request received, thank you,” or any number of possible affirmations. If the attack failed, “Transfer failed,” “Error: Transfer amount must be a positive number,” or, “Bank robbery detected, men with guns have been dispatched to your location!” Every custom Web Bank application will likely respond in a different manner. That’s precisely the problem! Pre-programming all the possible keyword phrases or behavioral aspects is simply unfeasible and for all mathematical provability, impossible. However, human gray matter (or, a crack website security operations team) can make this determination.

Automated Scanning vs the OWASP Top Ten

The OWASP Top Ten is a list of the most critical website security flaws – a list also often used as a minimum standard for website vulnerability assessment (VA) and compliance. There is an ongoing industry dialog about the possibility of identifying the OWASP Top Ten in a purely automated fashion (scanning). People frequently ask what can and can’t be found using either white box or black box scanners. This is important because a single missed vulnerability, or more accurately exploited vulnerability, can cause an organization significant financial harm. Proper expectations must be set when it comes to the various vulnerability assessment solutions.

For our part, WhiteHat Security is in the website security business and provides a vulnerability management service. Our Sentinel Service incorporates expert analysis with proprietary scanning technology. Using a black box process, we assess hundreds of websites a month, more than anyone in the industry. What we’ve come to understand is that a significant portion of vulnerabilities are virtually impossible for scanners to find. By the same token, even the most seasoned Web security experts cannot find many issues in a reliable and consistent manner. To achieve full vulnerability coverage and therefore complete vulnerability management, we must rely on a combination and integration of both methods.

We’d like to share some of our experiences that led to this conclusion. Using situations we’ve seen in the real world, and the OWASP Top Ten as a baseline, we’ll demonstrate why scanning technology alone cannot find the OWASP Top Ten. To begin, we’ll focus on a single feature of a fictitious Web Bank responsible for funds transfers from one account to another account. Here is the full URL:

http://server/transfer.cgi?from_acct=1235813&to_acct=31415&amount=
1000.00&session=1001

The “from_acct” is the current user’s account number. “to_acct” is where the money should be sent. “Amount” is obviously the transfer amount, and the “session” is the authenticated session ID after having properly logged-in. This is a fairly typical and straightforward business process.


Unvalidated Input

Scanners must hazard a guess about what “transfer.cgi” does. Otherwise, it would be impossible to determine what it should NOT do.

A website security expert can easily figure this out, but scanners aren’t equipped with that intelligence: There is no knowledge of or appreciation for context. For the sake of discussion, let’s say a scanner has the ability, because there’s a dollar figure present and the “transfer” keyword in the URL might help it decide that this feature moves money. Realistically, these parameter names could be anything and are often far more cryptic. To attempt a classic funds transfer attack, let’s change the above URL substituting the “1000.00” amount to “-1000.00.”



Negative Amount Example:
http://server/transfer.cgi?from_acct=1235813&to_acct=31415&amount=-1000.00&session=1001

By transferring a negative amount, this custom Web application would potentially deduct money from the target account instead of adding to it! The challenge for a scanner is being able to decide whether or not the attack succeeded. How would it tell?

If the fraudulent transfer succeeded, the website might respond with, “Success, would you like to make another transaction?,” “Transfer will take place by 9 AM tomorrow,” “Request received, thank you,” or any number of possible affirmations. If the attack failed, “Transfer failed,” “Error: Transfer amount must be a positive number,” or, “Bank robbery detected, men with guns have been dispatched to your location!” Every custom Web Bank application will likely respond in a different manner. That’s precisely the problem! Pre-programming all the possible keyword phrases or behavioral aspects is simply unfeasible and for all mathematical provability, impossible. However, human gray matter (or, a crack website security operations team) can make this determination.

10 Steps to Protect your Websites from SQL Injection Attacks

Data theft has become so common that the price of a stolen credit card number in the black market has fallen from $10 in 2006 to a few pennies in 2009. Consumers are losing confidence in ecommerce, online banking and other electronic means of doing business. Meanwhile, attackers are devising even more clever ways to steal data and increasing numbers of companies are falling prey to those techniques. Legal and compliance requirements are getting stricter to protect the consumer, but still new incidents are on the rise in 2009. In a recent Verizon Business Data Breach Investigations Report1, studying over 600 incidents in the past five years, SQL Injection was identified as the single largest attack vector responsible for data theft

This finding is not surprising. Given the way Web applications are designed, it is very common for SQL injection attacks to occur without a company’s knowledge. Often, it is only when the credit card companies such as VISA and American Express notify the victimized company, that they learn about the hack and by then, it’s too late.

SQL injection attacks have the potential to cause significant and costly damage to an organization. They are targeted at the database, which stores sensitive information including employee and customer data. This type of attack exploits vulnerabilities in your application and manipulates the SQL queries in the application via input from the Web browser.

In a SQL injection attack, a malicious user can send arbitrary input to the server and trick the Web application into generating a different SQL statement than was originally intended. As a result, the SQL, when executed, fetches a different set of results from the database than the application would have originally requested. SQL injection attacks are most frequently used to gain unauthorized access to, or manipulate the data residing in, the database on the server.

Much has already been written about how SQL injection attacks are performed. The focus here is to prevent the attacks in the first place. Following are 10 steps that both developers and database administrators can take to prevent applications from being vulnerable to SQL injection attacks.

Tuesday, February 9, 2010

Python - A Real Beginners Guide

PYTHON

I. Intro
II. My First Program
III. Variables, Numbers and Strings
IV. String Manipulation
V. Operators
VI. Arrays/Lists
VII. Loops and Conditionals
a. The IF/ELIF/ELSE Statements
b. The WHILE Statement
VIII Bye bye! Good luck!

+---------------------------------------+
I. Intro
+---------------------------------------+
PYTHON! According to Python.org, this is what Python is...:

"Python is a dynamic object-oriented programming language that can be
used for many kinds of software development. It offers strong support
for integration with other languages and tools, comes with extensive
standard libraries, and can be learned in a few days. Many Python
programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code"

More simply however, Python is an easy-to-read, highly compatible,
oft-used programming language that is powerful and quick. It is often
compared to languages such as Perl, Ruby, Java, etc

ABOUT THIS GUIDE:
- This guide is intended for COMPLETE beginners to programming
languages, and is suggested to most as a first language, as it is as
mentioned before, an easy-to-read and simple language :)

REQUIREMENTS FOR THIS GUIDE:
- Having the latest version of Python installed on your computer. The
installers can be found at http://www.python.org/download/


+---------------------------------------+
II. My First Program
+---------------------------------------+
FOR the first program, we will be creating a small program that writes
"Hello World!" on screen.

Here is the code:
CODE :
__________________________________________________________________________
>>>print("Hello World!")
__________________________________________________________________________

BREAKDOWN:
print() - the typical function (functions will be covered more later
on) to write sentences and variables to the screen.

NOTE: It should also be noted that when using the print function, you
must remember that when you try print multiple things, e.g.
>>>print("Lol", "and", "hi"), a space will immediately be placed
between each part.

NOTE2: Instead of using print(), we also can type the string, number,
or variable and press enter in Python Shell to print the value of it
(remember that you will have to wrap strings in quotation marks if you
decide to use this method).


+---------------------------------------+
III. Variables, Numbers and Strings
+---------------------------------------+
VARIABLES are ways of holding information inside a word, to be able to
call the information back later in a program. The way to assign a value is..:
CODE :
__________________________________________________________________________
>>>#This is a comment line... Comment lines in Python are always
>>>#Preceded by a #
>>>#A variable can either hold a string (words) or a number
>>>varName = "variable"
>>>varName1 = 2009
__________________________________________________________________________

Variables can be changed later in the program. They can also hold a
formula or function. In addition, you can assign the same values to
several variables at once. For examples...

CODE :
__________________________________________________________________________
>>>#This variable holds a total of 25
>>>varFormula = 5*5
>>>
>>>#These variables both hold a value of 45
>>>varX = varY = 40+5
>>>
>>>#This variable holds a function that finds out the length of a
>>>#string or other value
>>>varLength = len("Hello World!")
>>>
>>>#The len() function does not work with numbers!
>>>#Using print(varLength) will output the length of "Hello World!"
>>>#which is 12.
>>>
>>>#Remember that when using the len() function, it counts every
>>>#character, including the space, and not just letters.
__________________________________________________________________________

+---------------------------------------+
IV. Word Indexing
+---------------------------------------+
BEING able to control strings is a vital part of programming. We
already know a couple of basic functions that allow us to manipulate or use strings, i.e. print() and len(). Another useful feature of Python is word indexing: being able to pick out certain letters in strings.

Here is an example of how to use word indexing:

CODE :
__________________________________________________________________________
>>>Hello = "Hello World!" #Establishes a variable...
>>>
>>>Hello[0] #Writes the first letter of the variable
"H"
>>>
>>>Hello[1:] #Writes all letters after the first letter
"ello World!"
>>>
>>>Hello[:5] #Writes all letters up to the sixth letter
"Hello"
>>>
>>>Hello[3:7] #Writes letters between the third and eighth letters
"lo W"
>>>
>>>Hello[3:-1] #Writes letters between position 3 and -1
"lo World"
__________________________________________________________________________

Yes, strangely enough, the first letter is indexed as [0]... Here is a
little table to illustrate index positions.
CODE :
__________________________________________________________________________
+---+---+---+---+
| A | B | C | D | = String
+---+---+---+---+
| 0 | 1 | 2 | 3 | = Positive indices
+---+---+---+---+
|-3 |-2 |-1 | ? | = Negative indices
+---+---+---+---+
__________________________________________________________________________

As you will see, there is absolutely no way of selecting a whole string using negative numbers... Of course, there are other ways of doing that.



+---------------------------------------+
V. Operators
+---------------------------------------+
OPERATORS are VERY important in Python... And sound much more
complicated than they really are. Operators are simply mathematical
symbols that do stuff for programming languages. Here is the table of
operators and how they work:
CODE :
__________________________________________________________________________
MATHEMATICAL OPERATORS - These produce a value
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|+..............|Addition.......|a + 5 = 10.............|
+---------------+---------------+-----------------------+
|-..............|Subtraction....|a - 5 = 0..............|
+---------------+---------------+-----------------------+
|*..............|Multiplication.|a * a = 25.............|
|**.............|Powers.........|a **3 = 25*25*25 = 125.|
+---------------+---------------+-----------------------+
|/..............|Division.......|a / a = 1..............|
|//.............|Rounds to floor|a // 0.3 = 16..........|
|%..............|Gives remainder|a % 2 = 1..............|
+---------------+---------------+-----------------------+

ASSIGNMENT OPERATORS - These give values to a variable
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|=..............|Assigns a value|a = 5..................|
+---------------+---------------+-----------------------+
|-=.............|Subtraction....|a-=10 is the same as...|
|...............|assigner.......|a = a - 10.............|
+---------------+---------------+-----------------------+
|*=.............|Multiplication.|a *= 10 is the same as.|
|...............|assigner.......|a = a * 10.............|
+---------------+---------------+-----------------------+
|**=............|Power assigner.|a **= 2 is the same as.|
|...............|...............|a = a ** 2.............|
+---------------+---------------+-----------------------+
|/=.............|Division.......|a /= 10................|
|...............|assigner.......|a = a / 10.............|
+---------------+---------------+-----------------------+
etc...etc...etc...etc...etc...etc...etc...etc...etc...etc

COMPARISON OPERATORS - These evaluate the truth of a statement
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|==.............|Is equal to....|a == 5.........TRUE....|
+---------------+---------------+-----------------------+
|!=.............|Not equal to...|a != 5.........FALSE...|
+---------------+---------------+-----------------------+
|>..............|More than......|a > a..........FALSE...|
|<..............|Less than......|a < 10.........TRUE....|
+---------------+---------------+-----------------------+
|>=.............|More than......|a >= a.........TRUE....|
|...............|or equal to....|a >= 6.........FALSE...|
+---------------+---------------+-----------------------+

BOOLEAN OPERATORS - These are used to link COMPARISON OPERATORS
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|and............|Both expression|a==5 and a>1...........|
|...............|must be true...|Evaluates to true......|
+---------------+---------------+-----------------------+
|or.............|Either expressi|a>6 or a<3.............|
|...............|on must be true|Evaluates to false.....|
+---------------+---------------+-----------------------+
|in.............|Checks if value|arr=["lol", "rofl"]....|
|...............|is in an array.|"lol" in arr...TRUE....|
+---------------+---------------+-----------------------+
__________________________________________________________________________

These are the main operators that you will need when programming in
Python.


+---------------------------------------+
VI. Arrays/Lists
+---------------------------------------+
ARRAYS/lists can be indexed exactly like words, but can store multiple
strings, numbers and variables. Also, you can append arrays: changing
them as you see fit. Here is the correct way of starting an array and changing it.
[/code]
>>>#Starts an array, 5 "elements" long
>>>arr = ["H", "e", "l", "l", "o"]
>>>
>>>arr[0] #Writes the first element in the array
"H"
>>>
>>>#Here are 3 functions that can change lists
>>>#These will be explained at the end of this chapter
>>>
>>>arr.append("!")
>>>arr # <- Prints the array
["H", "e", "l", "l", "o", "!"]
>>>
>>>arr.insert(1, "a")
>>>arr
["H", "a", "l", "l", "o", "!"]
>>>
>>>arr.extend(["Wo", "rld", "!"])
>>>arr
["H", "a", "l", "l", "o", "!", "Wo", "rld", "!"]
>>>
>>>arr.remove("!")
>>>arr
["H", "a", "l", "l", "o", "Wo", "rld", "!"]
[/code]
BREAKDOWN:
arrName.append(value):
........arrName.........- the array to be changed.
........append(value)...- the function to be used. Only takes one
................argument though. I.e, you can not add two elements to
................the array.

arrName.insert(pos,value):
........arrName.........- the array to be changed.
........insert(pos,v...)- function adds an element at the indicated
................position.

arrName.extend([value1, value2...])
........arrName.........- the array to be changed.
........extend([val...])- function adds multiple elements onto the
................end of a list. The elements to be added must be
................inside square brackets. This function only takes
................one argument - i.e. a list ([]).

arrName.remove(value):
........arrName.........- the array to be changed.
........remove(value)...- removes the first instance of the value
................inputted.

As mentioned before, arrays can be indexed the same way as words. Python also allows you to pick a specific letter/range of letters out
words in an array...

>>>arr = ["Hello", "World", "!"]
>>>arr[0][3:] #Picks first word, letters between 3 to end
"lo"

Also, a useful function for both single strings and arrays:

>>>arr = ["Hello, "World", "!"]
>>>arr.index("Hello") #Displays pos of value in array
0
>>>word = "Hello!"
>>>word.index("H") #Displays pos of first occurrence in array
0

Arrays can also be changed by putting them into formulas, e.g.

CODE :
__________________________________________________________________________
>>>arr = ["Hello", "World", "!"]
>>>arr = arr + [":P"]
>>>arr
["Hello", "World", "!", ":P"]
>>>
>>>arr = [90, 91] * 2
>>>arr
[90, 91, 90, 91]
__________________________________________________________________________

In conclusion to this section, arrays are a very much needed tool of a
serious programmer...


+---------------------------------------+
VII. Loops and Conditionals
+---------------------------------------+
+---------------------------------------+
VII.a. The IF/ELSE/ELIF Statements
+---------------------------------------+
IFS, elifs and elses help us develop a sense of control to our
programs... Without these, programs would be, in one word, pretty useless... *(...?)*

In this section, we will also create a whole program, that will
eventually be able let the user of the program input a number, and have the program count down from their number to 0.
Here is a summary of each term, and how they work, IF, ELIF, and ELSE,
including the syntax.

CODE :
__________________________________________________________________________
#For this part of the program, we need to make sure that the input
#is no more than 9, and no less than 1
#----------------------------------------------------IF---------
>>>numArray = [1,2,3,4,5,6,7,8,9]
>>>#^ Sets up a number array,
>>>#so that we can check if the
>>>#input is between 1:9
>>>
>>>a = int(input("Enter a number 1-9: "))
>>> #This line of programming says that the program will
>>> #output "Enter a number 1-9", asking the user to
>>> #"input" an "integer" (whole number) between 1 and 9
>>>
Enter a number 1-9: #Input goes here
>>>if a in numArray: #Checks if input is in numArray
... print("Countdown initializing!")
__________________________________________________________________________

So far, the program lets the user input a number to the program and the program checks if that number is between 1 to 9, and if it is, the
program prints "Countdown initializing!". Unfortunately, if the number
is more than 9, or less than 1, nothing happens... That is BAD. So we
need to sort this out. Introducing ELIF...
CODE :
__________________________________________________________________________
#----------------------------------------------------ELIF------
>>>numArray = [1,2,3,4,5,6,7,8,9]
>>>#^ Sets up a number array,
>>>#so that we can check if the
>>>#input is between 1:9
>>>
>>>a = int(input("Enter a number 1-9: "))
>>> #This line of programming says that the program will
>>> #output "Enter a number 1-9", asking the user to
>>> #"input" an "integer" (whole number) between 1 and 9
>>>
Enter a number 1-9: #Input goes here
>>>if a in numArray: #Checks if input is in numArray
... print("Countdown initializing!")
...elif a > 9: #Checks if a is more than 9
... print("Your number is too high...")
__________________________________________________________________________

Ah, great! Now our program tells the user off for entering a number too high... But what if the input is less than 1? Well, seeing as we have covered 1-9, and anything above 9, we can now introduce "else"...
CODE :
__________________________________________________________________________
#----------------------------------------------------ELSE------
>>>numArray = [1,2,3,4,5,6,7,8,9]
>>>#Sets up a number array,
>>> #so that we can check if the
>>> #input is between 1:9
>>>
>>>a = int(input("Enter a number 1-9: "))
>>> #This line of programming says that the program will
>>> #output "Enter a number 1-9", asking the user to
>>> #"input" an "integer" (whole number) between 1 and 9
>>>
Enter a number 1-9: #Input goes here
>>>if a in numArray: #Checks if input is in numArray
... print("Countdown initializing!")
...elif a > 9: #Checks if a is more than 9
... print("Your number is too high...")
...else:
... print("Your number is a bit too low!")
__________________________________________________________________________

WONDERFUL! Our program now works. However, it is a bit plain, let us go on to WHILE.

+---------------------------------------+
VII.b. The WHILE Statement
+---------------------------------------+
SO, our program up to now is pretty good. We still need to make the
countdown though. And on top of that, we need the input to repeat, in
case the number that the user enters a number that is not between
1-9... This is where the WHILE statement comes into play. The WHILE
statement will repeat and repeat til the condition that makes it run
changes.

Here is the modified script, using the WHILE loop.
CODE :
__________________________________________________________________________
#----------------------------------------------------WHILE-----
>>>numArray = [1,2,3,4,5,6,7,8,9] #Sets up number array
>>>
>>>case = 0
>>>#^ This variable will allow us to switch from
>>>#one loop to the next... Read on
>>>
>>>while case == 0: ###Checks if case == 0 and then runs script
... a = int(input("Enter a number 1-9: "))
... if a in numArray: #checks if input is in numArray
... print("Countdown initializing...!")
... case += 1 #Tells case to increase by 1;
...
... else:
... pass
>>>#"pass" tells the program to do nothing
>>>#And go to the beginning of the loop again
>>>
>>>#The above loop will repeat til the user enters a valid number
>>>#then case will change to 1 and run the below script
>>>
>>>
>>>
>>>while case == 1: #Checks case == 1, i.e, it checks if the
>>> #number in the first loop is valid
... if a == 0:
... case +=1 #Passes the program to the next part
... else:
... print(a,"more loop(/s) til the bang!")
... a -= 1 #Tells the program to take 1 away from input
>>>
>>>#The above loop continues to repeat til a == 0, when it finally
>>>#carries you to the last part of the program...:
>>>
>>>if case == 2:
>>> print("BANG!")
__________________________________________________________________________

The above program can be broken down into four simple parts:
1. a preparation of the variables for the program to handle

2. loop one: this loop makes the user enter a number between
one to nine, and then goes to loop two, carrying across the
"a" integer input variable.

3. loop two: this loop counts down starting from "a", which
the user specified. When the loop turns variable "a" to 0, the
program changes case to 2, and sends it across to the final
part.

4. This part simply ends the program, printing 'BANG!' to the
screen.


+---------------------------------------+
VIII. Bye Bye! Good Luck!
+---------------------------------------+
SO, yeah, that's the very very very basics of Python. And I can only
hope that this all didn't sound like a complete load of donkey doodar
to you.

If this does not help you at all, many apologies. Here is a site that
might help you if you wanna take it slower:
http://docs.python.org/3.1/tutorial/ :)
Best of luck to all of you :)

BYE BYE!! <3
Code2004 // Connor

Post-script: please remember that ">>>" and "..." mean that this was written in Python Shell. DO NOT use them in a script, because it wont work xD!

Python - A Real Beginners Guide

PYTHON

I. Intro
II. My First Program
III. Variables, Numbers and Strings
IV. String Manipulation
V. Operators
VI. Arrays/Lists
VII. Loops and Conditionals
a. The IF/ELIF/ELSE Statements
b. The WHILE Statement
VIII Bye bye! Good luck!

+---------------------------------------+
I. Intro
+---------------------------------------+
PYTHON! According to Python.org, this is what Python is...:

"Python is a dynamic object-oriented programming language that can be
used for many kinds of software development. It offers strong support
for integration with other languages and tools, comes with extensive
standard libraries, and can be learned in a few days. Many Python
programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code"

More simply however, Python is an easy-to-read, highly compatible,
oft-used programming language that is powerful and quick. It is often
compared to languages such as Perl, Ruby, Java, etc

ABOUT THIS GUIDE:
- This guide is intended for COMPLETE beginners to programming
languages, and is suggested to most as a first language, as it is as
mentioned before, an easy-to-read and simple language :)

REQUIREMENTS FOR THIS GUIDE:
- Having the latest version of Python installed on your computer. The
installers can be found at http://www.python.org/download/


+---------------------------------------+
II. My First Program
+---------------------------------------+
FOR the first program, we will be creating a small program that writes
"Hello World!" on screen.

Here is the code:
CODE :
__________________________________________________________________________
>>>print("Hello World!")
__________________________________________________________________________

BREAKDOWN:
print() - the typical function (functions will be covered more later
on) to write sentences and variables to the screen.

NOTE: It should also be noted that when using the print function, you
must remember that when you try print multiple things, e.g.
>>>print("Lol", "and", "hi"), a space will immediately be placed
between each part.

NOTE2: Instead of using print(), we also can type the string, number,
or variable and press enter in Python Shell to print the value of it
(remember that you will have to wrap strings in quotation marks if you
decide to use this method).


+---------------------------------------+
III. Variables, Numbers and Strings
+---------------------------------------+
VARIABLES are ways of holding information inside a word, to be able to
call the information back later in a program. The way to assign a value is..:
CODE :
__________________________________________________________________________
>>>#This is a comment line... Comment lines in Python are always
>>>#Preceded by a #
>>>#A variable can either hold a string (words) or a number
>>>varName = "variable"
>>>varName1 = 2009
__________________________________________________________________________

Variables can be changed later in the program. They can also hold a
formula or function. In addition, you can assign the same values to
several variables at once. For examples...

CODE :
__________________________________________________________________________
>>>#This variable holds a total of 25
>>>varFormula = 5*5
>>>
>>>#These variables both hold a value of 45
>>>varX = varY = 40+5
>>>
>>>#This variable holds a function that finds out the length of a
>>>#string or other value
>>>varLength = len("Hello World!")
>>>
>>>#The len() function does not work with numbers!
>>>#Using print(varLength) will output the length of "Hello World!"
>>>#which is 12.
>>>
>>>#Remember that when using the len() function, it counts every
>>>#character, including the space, and not just letters.
__________________________________________________________________________

+---------------------------------------+
IV. Word Indexing
+---------------------------------------+
BEING able to control strings is a vital part of programming. We
already know a couple of basic functions that allow us to manipulate or use strings, i.e. print() and len(). Another useful feature of Python is word indexing: being able to pick out certain letters in strings.

Here is an example of how to use word indexing:

CODE :
__________________________________________________________________________
>>>Hello = "Hello World!" #Establishes a variable...
>>>
>>>Hello[0] #Writes the first letter of the variable
"H"
>>>
>>>Hello[1:] #Writes all letters after the first letter
"ello World!"
>>>
>>>Hello[:5] #Writes all letters up to the sixth letter
"Hello"
>>>
>>>Hello[3:7] #Writes letters between the third and eighth letters
"lo W"
>>>
>>>Hello[3:-1] #Writes letters between position 3 and -1
"lo World"

Yes, strangely enough, the first letter is indexed as [0]... Here is a
little table to illustrate index positions.
CODE :

+---+---+---+---+
| A | B | C | D | = String
+---+---+---+---+
| 0 | 1 | 2 | 3 | = Positive indices
+---+---+---+---+
|-3 |-2 |-1 | ? | = Negative indices
+---+---+---+---+

As you will see, there is absolutely no way of selecting a whole string using negative numbers... Of course, there are other ways of doing that.



+---------------------------------------+
V. Operators
+---------------------------------------+
OPERATORS are VERY important in Python... And sound much more
complicated than they really are. Operators are simply mathematical
symbols that do stuff for programming languages. Here is the table of
operators and how they work:
CODE :

MATHEMATICAL OPERATORS - These produce a value
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|+..............|Addition.......|a + 5 = 10.............|
+---------------+---------------+-----------------------+
|-..............|Subtraction....|a - 5 = 0..............|
+---------------+---------------+-----------------------+
|*..............|Multiplication.|a * a = 25.............|
|**.............|Powers.........|a **3 = 25*25*25 = 125.|
+---------------+---------------+-----------------------+
|/..............|Division.......|a / a = 1..............|
|//.............|Rounds to floor|a // 0.3 = 16..........|
|%..............|Gives remainder|a % 2 = 1..............|
+---------------+---------------+-----------------------+

ASSIGNMENT OPERATORS - These give values to a variable
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|=..............|Assigns a value|a = 5..................|
+---------------+---------------+-----------------------+
|-=.............|Subtraction....|a-=10 is the same as...|
|...............|assigner.......|a = a - 10.............|
+---------------+---------------+-----------------------+
|*=.............|Multiplication.|a *= 10 is the same as.|
|...............|assigner.......|a = a * 10.............|
+---------------+---------------+-----------------------+
|**=............|Power assigner.|a **= 2 is the same as.|
|...............|...............|a = a ** 2.............|
+---------------+---------------+-----------------------+
|/=.............|Division.......|a /= 10................|
|...............|assigner.......|a = a / 10.............|
+---------------+---------------+-----------------------+
etc...etc...etc...etc...etc...etc...etc...etc...etc...etc

COMPARISON OPERATORS - These evaluate the truth of a statement
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|==.............|Is equal to....|a == 5.........TRUE....|
+---------------+---------------+-----------------------+
|!=.............|Not equal to...|a != 5.........FALSE...|
+---------------+---------------+-----------------------+
|>..............|More than......|a > a..........FALSE...|
|<..............|Less than......|a < 10.........TRUE....|
+---------------+---------------+-----------------------+
|>=.............|More than......|a >= a.........TRUE....|
|...............|or equal to....|a >= 6.........FALSE...|
+---------------+---------------+-----------------------+

BOOLEAN OPERATORS - These are used to link COMPARISON OPERATORS
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|and............|Both expression|a==5 and a>1...........|
|...............|must be true...|Evaluates to true......|
+---------------+---------------+-----------------------+
|or.............|Either expressi|a>6 or a<3.............|
|...............|on must be true|Evaluates to false.....|
+---------------+---------------+-----------------------+
|in.............|Checks if value|arr=["lol", "rofl"]....|
|...............|is in an array.|"lol" in arr...TRUE....|
+---------------+---------------+-----------------------+

These are the main operators that you will need when programming in
Python.


+---------------------------------------+
VI. Arrays/Lists
+---------------------------------------+
ARRAYS/lists can be indexed exactly like words, but can store multiple
strings, numbers and variables. Also, you can append arrays: changing
them as you see fit. Here is the correct way of starting an array and changing it.
[/code]
>>>#Starts an array, 5 "elements" long
>>>arr = ["H", "e", "l", "l", "o"]
>>>
>>>arr[0] #Writes the first element in the array
"H"
>>>
>>>#Here are 3 functions that can change lists
>>>#These will be explained at the end of this chapter
>>>
>>>arr.append("!")
>>>arr # <- Prints the array
["H", "e", "l", "l", "o", "!"]
>>>
>>>arr.insert(1, "a")
>>>arr
["H", "a", "l", "l", "o", "!"]
>>>
>>>arr.extend(["Wo", "rld", "!"])
>>>arr
["H", "a", "l", "l", "o", "!", "Wo", "rld", "!"]
>>>
>>>arr.remove("!")
>>>arr
["H", "a", "l", "l", "o", "Wo", "rld", "!"]
[/code]
BREAKDOWN:
arrName.append(value):
........arrName.........- the array to be changed.
........append(value)...- the function to be used. Only takes one
................argument though. I.e, you can not add two elements to
................the array.

arrName.insert(pos,value):
........arrName.........- the array to be changed.
........insert(pos,v...)- function adds an element at the indicated
................position.

arrName.extend([value1, value2...])
........arrName.........- the array to be changed.
........extend([val...])- function adds multiple elements onto the
................end of a list. The elements to be added must be
................inside square brackets. This function only takes
................one argument - i.e. a list ([]).

arrName.remove(value):
........arrName.........- the array to be changed.
........remove(value)...- removes the first instance of the value
................inputted.

As mentioned before, arrays can be indexed the same way as words. Python also allows you to pick a specific letter/range of letters out
words in an array...

>>>arr = ["Hello", "World", "!"]
>>>arr[0][3:] #Picks first word, letters between 3 to end
"lo"

Also, a useful function for both single strings and arrays:

>>>arr = ["Hello, "World", "!"]
>>>arr.index("Hello") #Displays pos of value in array
0
>>>word = "Hello!"
>>>word.index("H") #Displays pos of first occurrence in array
0

Arrays can also be changed by putting them into formulas, e.g.

CODE :

>>>arr = ["Hello", "World", "!"]
>>>arr = arr + [":P"]
>>>arr
["Hello", "World", "!", ":P"]
>>>
>>>arr = [90, 91] * 2
>>>arr
[90, 91, 90, 91]


In conclusion to this section, arrays are a very much needed tool of a
serious programmer...


+---------------------------------------+
VII. Loops and Conditionals
+---------------------------------------+
+---------------------------------------+
VII.a. The IF/ELSE/ELIF Statements
+---------------------------------------+
IFS, elifs and elses help us develop a sense of control to our
programs... Without these, programs would be, in one word, pretty useless... *(...?)*

In this section, we will also create a whole program, that will
eventually be able let the user of the program input a number, and have the program count down from their number to 0.
Here is a summary of each term, and how they work, IF, ELIF, and ELSE,
including the syntax.

CODE :

#For this part of the program, we need to make sure that the input
#is no more than 9, and no less than 1
#----------------------------------------------------IF---------
>>>numArray = [1,2,3,4,5,6,7,8,9]
>>>#^ Sets up a number array,
>>>#so that we can check if the
>>>#input is between 1:9
>>>
>>>a = int(input("Enter a number 1-9: "))
>>> #This line of programming says that the program will
>>> #output "Enter a number 1-9", asking the user to
>>> #"input" an "integer" (whole number) between 1 and 9
>>>
Enter a number 1-9: #Input goes here
>>>if a in numArray: #Checks if input is in numArray
... print("Countdown initializing!")

So far, the program lets the user input a number to the program and the program checks if that number is between 1 to 9, and if it is, the
program prints "Countdown initializing!". Unfortunately, if the number
is more than 9, or less than 1, nothing happens... That is BAD. So we
need to sort this out. Introducing ELIF...
CODE :

#----------------------------------------------------ELIF------
>>>numArray = [1,2,3,4,5,6,7,8,9]
>>>#^ Sets up a number array,
>>>#so that we can check if the
>>>#input is between 1:9
>>>
>>>a = int(input("Enter a number 1-9: "))
>>> #This line of programming says that the program will
>>> #output "Enter a number 1-9", asking the user to
>>> #"input" an "integer" (whole number) between 1 and 9
>>>
Enter a number 1-9: #Input goes here
>>>if a in numArray: #Checks if input is in numArray
... print("Countdown initializing!")
...elif a > 9: #Checks if a is more than 9
... print("Your number is too high...")

Ah, great! Now our program tells the user off for entering a number too high... But what if the input is less than 1? Well, seeing as we have covered 1-9, and anything above 9, we can now introduce "else"...
CODE :

#----------------------------------------------------ELSE------
>>>numArray = [1,2,3,4,5,6,7,8,9]
>>>#Sets up a number array,
>>> #so that we can check if the
>>> #input is between 1:9
>>>
>>>a = int(input("Enter a number 1-9: "))
>>> #This line of programming says that the program will
>>> #output "Enter a number 1-9", asking the user to
>>> #"input" an "integer" (whole number) between 1 and 9
>>>
Enter a number 1-9: #Input goes here
>>>if a in numArray: #Checks if input is in numArray
... print("Countdown initializing!")
...elif a > 9: #Checks if a is more than 9
... print("Your number is too high...")
...else:
... print("Your number is a bit too low!")

WONDERFUL! Our program now works. However, it is a bit plain, let us go on to WHILE.

+---------------------------------------+
VII.b. The WHILE Statement
+---------------------------------------+
SO, our program up to now is pretty good. We still need to make the
countdown though. And on top of that, we need the input to repeat, in
case the number that the user enters a number that is not between
1-9... This is where the WHILE statement comes into play. The WHILE
statement will repeat and repeat til the condition that makes it run
changes.

Here is the modified script, using the WHILE loop.
CODE :

#----------------------------------------------------WHILE-----
>>>numArray = [1,2,3,4,5,6,7,8,9] #Sets up number array
>>>
>>>case = 0
>>>#^ This variable will allow us to switch from
>>>#one loop to the next... Read on
>>>
>>>while case == 0: ###Checks if case == 0 and then runs script
... a = int(input("Enter a number 1-9: "))
... if a in numArray: #checks if input is in numArray
... print("Countdown initializing...!")
... case += 1 #Tells case to increase by 1;
...
... else:
... pass
>>>#"pass" tells the program to do nothing
>>>#And go to the beginning of the loop again
>>>
>>>#The above loop will repeat til the user enters a valid number
>>>#then case will change to 1 and run the below script
>>>
>>>
>>>
>>>while case == 1: #Checks case == 1, i.e, it checks if the
>>> #number in the first loop is valid
... if a == 0:
... case +=1 #Passes the program to the next part
... else:
... print(a,"more loop(/s) til the bang!")
... a -= 1 #Tells the program to take 1 away from input
>>>
>>>#The above loop continues to repeat til a == 0, when it finally
>>>#carries you to the last part of the program...:
>>>
>>>if case == 2:
>>> print("BANG!")

The above program can be broken down into four simple parts:
1. a preparation of the variables for the program to handle

2. loop one: this loop makes the user enter a number between
one to nine, and then goes to loop two, carrying across the
"a" integer input variable.

3. loop two: this loop counts down starting from "a", which
the user specified. When the loop turns variable "a" to 0, the
program changes case to 2, and sends it across to the final
part.

4. This part simply ends the program, printing 'BANG!' to the
screen.


+---------------------------------------+
VIII. Bye Bye! Good Luck!
+---------------------------------------+
SO, yeah, that's the very very very basics of Python. And I can only
hope that this all didn't sound like a complete load of donkey doodar
to you.

If this does not help you at all, many apologies. Here is a site that
might help you if you wanna take it slower:
http://docs.python.org/3.1/tutorial/ :)
Best of luck to all of you :)

BYE BYE!! <3
Code2004 // Connor

Post-script: please remember that ">>>" and "..." mean that this was written in Python Shell. DO NOT use them in a script, because it wont work xD!

Social Engineering

I am writing this article, because social engineering is almost a necessity for any hacker. You would be surprised what valuable information people will give away to a complete stranger. I have not seen any articles on this topic so far, so I am going to do my best and hopefully teach you all something you did not know before.

Introduction
Social Engineering is the art of manipulating a person into revealing sensitive information. Social Engineering is the best hacking tool you can use, in my opinion. Similar to using a computer program to make another system spew out amounts of valuable information about the machine, that an attacker can later use. Think of it as "people hacking". When hacking into system you find a weakness or vulnerability that you can exploit, to gain access to restricted information. Social engineering is taking advantage of a persons weakness and getting them to disclose confidential information. All it takes is a large amount a confidence and basic knowledge of human nature and social behavior patterns. Social engineering does not just apply to computer security, it can apply to nearly any situation.


Understanding Human Nature
When it comes to social engineering there are typically only a handful of “tools” you can use. Some of which are; A basic understanding of human nature, cognitive biases, and psychological fallacies. People generally have social patterns and behaviors that can easily be exploited. Everyone has these flaws, it is a matter of finding out what works with the particular person. There are literally hundreds of these fallacies, and nearly everyone is guilty of them. This is just a few that really stand out to me. Maybe I will cover more in a future article. Some of the most popular human social patterns include:

*The Bandwagon Effect-This is the tendency to follow patterns of another persons, or a groups behavior. Generally everyone has heard the term "jump on the bandwagon", It simply means to do as others do. This particular bias plays a very important roll in social engineering and can be taken advantage of quite easily. Also known as conformity.

*Illusion of Control-This is the illusion that a human believes that they can control the outcome of certain situation, when it is clearly out of their hands. Think of someone who is gambling who believes they can really control the outcome of the numbers they roll. Some people truly believe that they can control the outcome of an event as if to predict the future. Prayer or belief in the paranormal could also be thrown into this category.

*Stereotyping-Stereotyping is judging a person by their distinguished characteristics. Everyone is clearly guilty of this at some point. Every time you meet someone for the first time, you almost always inadvertently judge them. You judge them by their clothes, their hairstyle and just their general appearance. However, stereotyping can sometimes be accurate as I will explain later on in the article.

*The Ostrich Effect-This is act of ignoring the negative situation that is going on. Think of someone that is over-optimistic about financial issues and pretending everything is fine. This particular fallacy is performed by almost anyone in a negative situation.

*Consistency bias-This is known as incorrectly remembering your past thoughts or actions in a given situation. This can be greatly taken advantage of. A new employee may not know how to answer a question, or how they answered it in the past. Therefore possibly disclosing valuable information.


Basic Techniques

You are not going to want to use every technique at once, find one that fits a particular situation and play the part well. Most social engineering can be done over the phone. It is quite simple to call up a company while imitating a person of authority and retrieving sensitive information. Help desks and customer service are very likely to this method of attack.

Be Polite
The best thing you can do is always be polite, never blow your cover by acting rude. Remember, you are sometimes taking advantage of someones good nature. So getting on their bad side is not a good start. Remember to speak up and be firm, but do not be rude. For example, call up a company you are interested in, and politely ask questions. Act as if you truly want to learn about how their system works, or what tools they use. Do not blatantly ask for something that you know is restricted information. You have to keep talking to them, while sounding knowledgeable and interested. Ask to speak to a manager, or someone in charge. Working your way up to someone that knows it all. Write down the names of employees pretend you are interested in that particular field of work, ask what type of education and things you will need to learn. The goal here is to persuade them from a psychological point of view.

Pretend to be ignorant
You obviously do not want the target to know much about you, so you want to be as discrete as possible. You do not want them to become concerned with a question you may have asked. Playing dumb is also another technique that can be used. Pretend to know nothing whatsoever and create a fake problem to ask customer service about. Keep them on the phone long enough and keep asking questions. Give them a fake name and phony problem. Ask for their name and figure out where they stand in the company. You know how annoying it is when you call a company and they keep redirecting you to someone else. They have thousands of calls each day, chances are they will not remember you. In all honesty they probably could not care less, they just want to get rid you and have someone else help you.

Be Curious, without giving it away
Write down a list of things you want to figure out with a certain phone call. Whether it be a certain name, phone number or just a piece of information that helps put together a piece of the puzzle. Ask for names, and to speak to certain people. Make sure you do your homework first and have a general knowledge about the company. If you do not know what to say beforehand you will sound like a fumbling idiot and your confidence level will decrease.

Pretending to be someone of higher authority
This applies the the bandwagon effect and also false memory. Tell a client that is lower in the chain that you are someone who you are not. Tell them you are an employee (in this case it would be a good idea to have a list of employees that you found on the company website or through the yellow pages.) Ask to speak to so and so, who is higher up in the company than she is. Tell them you need a phone number, or whatever it may be you are searching for. That is why I think it is a good idea to have a goal of what you are truly after. This method is known as reverse social engineering. This requires a bit of research and preparation to pull off, but with proper execution and very well be one of the best methods.

Other Techniques
These techniques are aimed to physical access to a specific company. Be careful with these though, they could land you in some pretty tough situations that may be harder to talk your way out of. Just remember that social engineering can be applied to nearly any given situation.

Dumpster Diving
As silly as this may sound, dumpster diving as an effective way of gaining valuable information about a company. You would be surprised what kinds of things they may have thrown away. Perhaps a trashed company computer with the hard rive still in it. Or possibly company phone books, organizational charts, memos, company policy manuals, calendars of meetings, events and vacations, system manuals, printouts of sensitive data or login names and passwords, printouts of source code, disks and tapes, company letterhead and memo forms, and outdated hardware. I will not go into great detail of how to dumpster dive, but I am sure you get the picture. Bottom line is that valuable things can be found in a company dumpster.

Tailgating
The art of following an authorized person into an area where you are not authorized. This is where your acting skills can come in handy. Pretend to be the repair man they called last week. Come ready with all your tools, hardhat white t-shirt and jeans and play the part. When really you just want physical access to something a normal civilian would not have rights to access. This technique takes some serious dedication, but in the end very much worth the effort. This requires doing your best to blend in. Maybe pretending to be just another employee on a smoke break. They will eventually finish and go back inside. That would be your cue to follow them inside, thus giving you physical access. Whatever your doing play the part, and do it with confidence.

Shoulder Surfing
Seems easy enough, right? It is as simple as it sounds, peering over someones shoulder to see what they are typing. Be careful not to get caught with this one, by making it obvious you are trying to view what they are typing. I am sure all of you have exercised some form of this at one point. I do not think I need to go into great detail on this, just be smooth about things.


People Watching
This is by far my favorite method. Keep in mind that social engineering does not always involve tricking people. Like I said before, it is all about understanding human nature. For some odd reason, I enjoy watching people. Whenever I go to a mall, airport or somewhere where I can sit down in public, I love to watch people. (In a non-rapist/stalker sort of way) I like to nonchalantly eavesdrop and just hear about their lives and what they have to say. I know you have all done it, at one time or another you have listened in on someones conversation and heard something they probably did not want you to hear. Everyone judges other people by the way they look or talk. It is one of the cognitive biases I listed called Stereotyping. A great way to practice your social engineering skills is to sit down and judge people. Not in a rude way, but try to figure out their life based on their appearance and social patterns. Pick out someone and see think about what they are wearing, what they are talking about, how they carry themselves and try to imagine what kind of life they lead.


Conclusion
This is just the tip of the iceberg when it comes to social engineering. There is much more to cover, but I hope you all learned something. Overtime you will become better at reading and understanding human nature. You will develop your own style of social engineering. There are many more methods that I left out, but these are great to start with. Knowing how to social engineer is a great way to prevent yourself from getting tricked by others. For example, the police use social engineering and forms of manipulation constantly. Others may disagree, but overall I feel this is an important topic to cover and I enjoyed writing this article. This is my first article, so let me know what you thought and I will keep them coming.

MacOs X and UNIX | Basic Tutorial

Getting Started on MacOs

You can skip this if you know how to access your unix command-line
- Open: Applications -> Utilites (shortcut: cmd-shift-U)
- Run Terminal.app

Browsing

The standards for Unix filesystems are as follows
/ -The root directory / The directory divider symbol
~/ -Your home folder
./ -The current directory
../ -Up one directory
* -The wildcard symbol
Directory: For those who only ever use the Finder or Filesystem GUI, a directory is a folder... baisically. Really a directory is just a pointer to any memory address.

Commands

cd -Change to the given directory
ls -List the contents of the active directory
rm -Erase a memory link (delete a file)
srm -Securely erase a link, by writing all zeros (like rm but it actually wipes the memory instead of just removing the pointer.)
mkdir -Make a new directory in current location. (Like New Folder)
mv- Copy files from one place to another

Excercises and Examples
Try these out to see if you understand:
Remove the quotations when typing commands.

1.

-Type ls, this should list the contents of your home folder, which is of course a directory. From here on all folders will be referred to as directories. If you do not see your home directory type cd ~/.
-Type touch test.noway. The touch command updates the last modified date of a file or creates a new one if the given filename does not exist. I used the .foobar extension to make sure you didnt accidentally change a file you had which happened to be named test.
-Switch to the finder and go to your home folder. You should now see a file called test.foobar.
-You just created that file well move it in exercise 2

2.

-Type ls, this should list the contents of your home folder. If you do not see your home directory type cd ~/.
-Type mkdir foo a new folder will appear named foo.
-Press the up arrow key to recall mkdir foo
Type mkdir foo/bara new folder will appear in foo named bar.
You can use the arrow-keys to scroll through command history at any time.
-Type touch test.noway this will create an empty file if you didn not do the first lesson.
-Type mv test.noway foo/bar test.noway is now in ~/foo/bar/
-Type mv ~/foo/bar/test.nowway ~/Pictures test.noway is now in your pictures folder.
-Type cd ~/Pictures ls will show you that you are in your pictures folder.
-Type mv test.noway ../ test.noway should move up one directory into you home folder.
-Type pwd you should see the path of your active directory.
-Type cd ../ your active directory should move up one to ~/. You can use pwd to test this.
-Type srm test.noway this will securely remove test.noway. Your computer may make funny clicking noises, but that is normal.
-Type rm foo You will receive an error message. Unix cannot by default delete a directory if there is something in it. Either delete ~/foo/bar/ or type rm -R this is what is known as a flag, switch, or dip-switch. -R will cause rm to load the hierarchy for deletion by reading all the pointers.

Help

Unix is notoriously poorly documented on the internet. Mainly becuase everything you need to know can be accessed via man
man a command - Access help for command.
man -k or apropos a string (search text) - When you know what you need but do not know what it is called.
Use space and arrows to navigate man. Press q when you done.
The OS manual can be accessed via info bash assuming the top bar of the terminal window says bash, which is the default.

FAQ

1. What is * for?
This is the wildcard character. Use it when you have given the computer enough information to figure out what you would type.
e.g.

cd ~/Pi* = cd ~/Pictures
rm ~/Pi*/* = rm ~/Pictures/ everthing in pictures.
rm ~/Pi*/a* = rm ~/Pictures/ everthing in pictures beginning with the letter a
rm ~/Pi*/a*b = rm ~/Pictures/ everthing in pictures beginning with the letter a and ending in b
rm ~/Pi*/*.jpeg = rm ~/Pictures/ every .jpeg in pictures

2. What is ./ for?
Some programs need you to use this to differentiate between other commands and the file youre modifying.

3. Error: You do not have sufficient privileges, access denied ?
Use man to lookup chmod and chgroup
chmod 777 file - your file can be accessed by everyone
chmod 755 file - your file can be acessed by you

4. I need to be an admin, but I am not under this account?
Use sudo at the begining of your command. Type admin password when prompted
Use login to change users in your terminal, but not MacOs.

5. What do I use if the man page says to use a | character?
The | character is referred to as the pipe character. It is used to pass parameters to the input of the command you are using.

Web Interaction Using Python

Introduction


In a number of the HTS programming missions you are asked to interact with the site from a program that you have written, as opposed to using a webbrowser. There are plenty of other applications for web interaction, however. I have written a few python scripts to download various data from websites (e.g. http://python.pastebin.com/f268e6319 )

I will cover two ways of getting data from a website (and in fact, sending data too). If there are any problems with the article, leave a comment.

All examples have been written in Python 2.6. There are quite a few differences between 2.6 and 3.0, but the only ones that should apply in the code snippets in this article involve the print function.

In Python 2.6 a simple hello world is this:
CODE :
__________________________________________________________________________
print "Hello World"
__________________________________________________________________________

In Python 3.0 it looks like this:
CODE :
__________________________________________________________________________
print("Hello World")
__________________________________________________________________________

It's a good idea, and I will switch to 3.0 when it is finally worn in, but for the moment I'm sticking with 2.6.
If there are problems with any of the code running as 3.0, try using the 2to3 script (It came preinstalled with Xubuntu for me.. not sure about on windows etc).

Anyway, now that's all covered, on with the article.

The Url Libraries

First of all we will start with a tutorial on the URL libraries. These are urllib and urllib2.

Let's immediately get started with some code.
CODE :
__________________________________________________________________________
import urllib2
url = "http://example.com"
website = urllib2.urlopen(url)
print website.read()
__________________________________________________________________________

Pretty simple code really, and for a lot of things it's all you need to know. It fetches the website "http://example.com" and stores the data as an instance on which we use the read() function to return the data retrieved from the site. Here are the functions:
instance.read() This returns the data retrieved from the site.
instance.info() This returns the HTTP message from the server, it has a lot of useful information in it including cookie info and server type.
instance.geturl() Returns the URL that was requested - seems pointless but we'll cover it in a second and you'll see why there is a point.
instance.getcode() Returns the HTTP status code. (e.g. 404, 200)

It's worth messing around with those a bit, rather than just taking my word for what they do.
I'll now just show a use of the geturl() function:
CODE :
__________________________________________________________________________
import urllib2
url = "http://google.com" # After google, try 'http://example.com'
website = urllib2.urlopen(url)
if url == website.geturl():
print "Website not redirected."
else:
print "Website redirected you."
__________________________________________________________________________

Why you'd want to do that, I don't know, but there's bound to be a use for it sometime. But that is one application of the geturl() function anyway.

Let's do a HTTP POST request now. They're pretty easy really, but can look a little complicated, so don't worry.
Before you look at the code, you might want to set up a server (or get some webspace) so you can test this out. A little PHP script like below will do the trick:
CODE :
__________________________________________________________________________
echo $_POST['test'];
?>
__________________________________________________________________________

And before anyone says anything about XSS - get lost - it's a testpage that will be up for 10 minutes on a server that noone cares about. But if you really are that bothered, you can use strip_tags() around that. (I say this because I can tell there'll be someone who will try and pipe up a clever comment).

Now then, we'll be introducing a new module for this (though it isn't strictly necessary, it's the best way I reckon). I will import the single function as we don't need any other functions from the module.

Okay, let's go:
CODE :
__________________________________________________________________________
import urllib2
from urllib import urlencode # new module and function

url = "http://localhost/test.php"
data = {'test':'lolwut'}
# you can add as much info as you want to this dictionary
# "test" is the label for the data, so that PHP script above
# should display "lolwut".

encoded_data = urlencode(data)
# remember that this is from that imported module, normally you'd
# use this: urllib.urlencode(data) if you used a normal import.

website = urllib2.urlopen(url, encoded_data)
print website.read() # That was pretty easy, right?
__________________________________________________________________________

Pretty straightforward, right?
Let's go onto HTTP Basic Authentication. This is more tricky. Here's the skeleton code for opening more advanced things, including HTTP authentication.
CODE :
__________________________________________________________________________
import urllib2

url = "http://example.com"

openerDirective1 = ...
openerDirective2 = ...

opener = urllib2.build_opener(openerDirective1, openerDirective2)

urllib2.install_opener(opener)

website = urllib2.urlopen(url)
__________________________________________________________________________

Okay, that's a lot more complicated. Note the "openerDirective"s. They are basically a way of adding headers to the urlopen requests.
You can have numerous opener directives, or just the one. You build them into an opener using the build_opener() function then install it, using install_opener(). After that, you can request a site and it will include the headers that you have specified.

Let's look at creating a HTTP Basic Authentication header.

CODE :
__________________________________________________________________________
authDirective = urllib2.HTTPBasicAuthHandler()
realm = "Webmail"
url = "http://example.com/webmail/"
username = "leethaxxer"
password = "letmein"
authDirective.add_password(realm, url, username, password)
__________________________________________________________________________

Then, we just build the opener and install it like we did in the skeleton code. Here:
CODE :
__________________________________________________________________________
opener = urllib2.build_opener(authDirective)
urllib2.install_opener(opener)
__________________________________________________________________________

I plan to write another article soon about cookies in Python, both as part of CGI and as part of requests with Urllib2.
Now I will move onto sockets and raw HTTP requests, and include cookies in that.

Socket Programming in Python

Socket programming is a really useful thing to learn - it's a must really, especially if you want to learn about security.

Again, we'll get some code out there straight away:
CODE :
__________________________________________________________________________
import socket
s = socket.socket()

host = "www.example.com"
port = 80
addr = (host, port)

s.connect(addr)
s.send("Something to send..")
print s.recv(1024)
# 1024 is the buffer size, you don't need to worry about it
# much right now.

s.close()
__________________________________________________________________________

There we are. We've created a socket, connected to "www.example.com" on port 80 then sent "Something to send.." and received something back, which has been printed out. Then we closed the socket, which isn't strictly necessary - but good practice.

Here's some better stuff to send, however:
CODE :
__________________________________________________________________________
GET /index.html HTTP/1.1\r\n
Host: www.example.com\r\n
__________________________________________________________________________

That's a simple HTTP GET request, asking for "index.html".
Here's a post request:
CODE :
__________________________________________________________________________
POST /index.php HTTP/1.1\r\n
Host: www.example.com\r\n
Content-Length: 11\r\n
\r\n
hello=world\r\n
__________________________________________________________________________

Now let's add a cookie to a HTTP GET:
CODE :
__________________________________________________________________________
GET /index.html HTTP/1.1\r\n
Host: www.example.com\r\n
Set-Cookie: hello=world\r\n
__________________________________________________________________________

There are other socket modes that can be set, this article is a very basic introduction. I would recommend reading this article if you want to learn more: http://www.amk.ca/python/howto/sockets/

Conclusion

Hopefully this article will help you begin to interact with the Internet using Python. It's just the beginning and I will work on follow-up articles. Good luck and thanks for reading.
dotty.

+++

Share |

"make something then You never be lost"

wibiya widget