DeutschEnglish

Submenu

 - - - By CrazyStat - - -

6. April 2021

Open PHP Scripts in Browser from Windows Explorer

Filed under: PHP,Windows — Tags: , , , , , — Christopher Kramer @ 19:07

PHP is a scripting language, so a PHP parser is needed to run PHP scripts. Furthermore, a webserver like Apache is required to run web applications written in PHP. We assume you already have all that installed (e.g. you installed xampp). Now you have php files in your htdocs-folder and want to open them in the browser, parsed by php and served by your local webserver? But that requires the browser to point to http://localhost/ instead of file://C:/xampp/htdocs/. I solved this by opening a tiny PHP script in the browser that redirects to the correct location. Here is how to set it up:

  1. Download FileTypesMan (direct download link for x64)
  2. Unzip FileTypesMan and run FileTypesMan.exe . Confirm the UAC prompt.
  3. Click Edit / Find and enter “php” in the search field
  4. If you do not find a row with the extension “.php” in the table, then:
    a) Double click a php-file in explorer and assign a default application to launch. This could be a text editor like notepad++, and IDE like Visual Studio Code, or notepad.exe.
    b) In FileTypesMan click File / Refresh Desktop now and search again for “php”. You should find it now.
  5. While the row “.php” is selected, click Actions / New action.
  6. Assign an action name like Parse php and open in Firefox
  7. Click “Browse…” and select the executable of the browser that should get launched, e.g. C:\Program Files\Mozilla Firefox\firefox.exe
  8. Now change the Command-Line so that after the path to the browser, the first argument is "http://localhost/load.php?file=%1" . This makes the browser open said php-file parsed by localhost and pass the filepath as parameter file. It should look similar as in the screenshot.
  9. Select “Default Action” if you want this action to happen on double-click.
  10. Click OK. You may create similar actions for other browsers.
  11. Drop the file load.php in your htdocs document root folder with the following content:
<?php
$htdocs = $_SERVER["DOCUMENT_ROOT"];
$webserver = "http://".$_SERVER["HTTP_HOST"];
if(empty($_GET['file'])) $redirectTo = $webserver;
else {
    $file = trim(str_replace("%20", " ", str_replace("\\\\", "/", str_replace(DIRECTORY_SEPARATOR, '/', $_GET['file']))));
	$inDocumentRoot = strpos($file, $htdocs)!==false;
	if(!$inDocumentRoot) { 
	    die('The file is not in the document root!');
	}
	$redirectTo = $webserver.str_replace($htdocs,"",$file);
}
header('Location: '.$redirectTo);
exit;

Now you can launch php files right from the context menu in Explorer or through double click. You can delete FileTypesMan now.

Please drop a comment it this made your day.

Recommendation

Try my Open Source PHP visitor analytics script CrazyStat.

19. March 2019

PHP: DateTime::createFromFormat fails for string read from CSV

Filed under: PHP — Tags: , , , , , — Christopher Kramer @ 19:31

I wrote a small PHP script to import a dozen csv files exported from Excel into a database. The CSV import basically looked like this:

&lt;?php
$f = "file.csv";	
if (($handle = fopen($f, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
         $date = DateTime::createFromFormat('d.m.Y', $data[0]);
         // Inserting this along with other data into a DB
    }
} ?>

And now what happened is that $date was false. So I fetched the errors like this:

var_dump(DateTime::getLastErrors());

And this returned:

array(4) {
  ["warning_count"]=>
  int(0)
  ["warnings"]=>
  array(0) {
  }
  ["error_count"]=>
  int(1)
  ["errors"]=>
  array(1) {
    [0]=>
    string(22) "Unexpected data found."
  }
}

So I added var_dump($date), but it gave string(13) "31.01.2019", which looked right. But looking closely, the string length of 13 seems a bit long for a 10 character date, right? I tried trim() , but without luck. And then I remembered that I had a similar problem before where invisible empty space was due to the UTF-8 Byte Order Mark (BOM). This is a sequence of “inivisible” bytes at the beginning of a textfile that define in which unicode encoding the file is (UTF-8, UTF-16, …) and its endianess (big-endian or little-endian). Microsoft Office programs such as Excel or Word like to write this to the beginning of a file, but other programs may do so as well.

So the solution is simple: In the first line, strip the BOM if it is there:

&lt;?php
$f = "file.csv";
$bom = pack('CCC', 0xEF, 0xBB, 0xBF);
$firstline=true;
if (($handle = fopen($f, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
         if ($firstline and substr($data[0], 0, 3) === $bom)
             $data[0] = substr($data[0], 3);
         $firstline=false;
         $date = DateTime::createFromFormat('d.m.Y', $data[0]);
         // Inserting this along with other data into a DB
    }
} ?>

So this just checks whether the first three bytes in the file match the UTF-8 BOM added by Excel and in case it detects them, it remove these bytes. Now the date parses fine. If your file has a different BOM, e.g. for UTF-16, you may need to change the definition of $bom. Just check your file in a hex-editor to find the first three bytes. This is PSPad, a great text-editor that includes a HEX-editor:

Note the first three bytes EF BB BF, which are the BOM.

If this helped you to solve your problem faster, please drop a comment below. This motivates me to keep writing these articles.

5. July 2018

PHP: trying to catch an Exception, but it never gets caught?

Filed under: PHP — Tags: , , , , , — Christopher Kramer @ 20:24

You are trying to catch an Exception like this and it never gets caught?

<?php
try {
// whatever you do here
// probably, you use some library
} catch(Exception $e) {
// this never works
}
?>

Most likely, your app is in some namespace. This means with the above code you only catch exceptions of the namespace of your app, not any exception. The solution is easy, just add a backslash:

try {
// whatever
} catch(\Exception $e) {
// this should work
// note the backslash!
}

Hope this helps somebody.

9. May 2014

Updating to PHP 5.4 causes missing Text

Filed under: PHP,Server Administration — Tags: , , , , , , — Christopher Kramer @ 14:29

After updating from PHP5.3 to PHP 5.4, on some sites text was missing. No error could be found in the error log so I had to dig into the code to find out what was going on.

The root cause is that with PHP5.4, the default character set expected by htmlentites(), htmlspecialcharacters() and html_entity_decode() changed from ISO-8859-1 to UTF-8. So if a script passes ISO-8859-1 characters like German “Umlaute” (öäüÖÄÜß) to one of these functions without specifying the charset with the corresponding parameter, these functions will return an empty string. And unfortunately, with PHP 5.4, they also removed the error message that PHP 5.3 recorded in the logfile in this case. This makes finding the problem a lot more difficult.

So what can you do about it? You could

  1. Use PHP 5.3 😉
    Here is a blog post on downgrading to PHP 5.3. on Debian Wheezy
  2. change the used charset to UTF-8
    This might require changing the character set in files, databases or config files, depending on what is used on the site.
    I explained in a blog post how to change the charset in Typo3 to UTF-8 back in 2012.
  3. Provide ISO-8859-1 as a parameter to all calls of htmlspecialcharacters() etc.

So for the third option, what you have to do is find places like this:

htmlspecialchars($string);

And replace them with something like:

htmlspecialchars($string, ENT_COMPAT | ENT_XHML, 'ISO-8859-1');

The problem is that it’s hard to do this automatically. What is easy to do, is replace all htmlspecialchars()-calls with calls to htmlspecialchars_PHP5-3() etc. and place these functions there:

function htmlspecialchars_PHP5-3($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') {
    return htmlspecialchars($string, $ent, $charset);
}

function htmlentities_PHP-5-3($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') {
    return htmlentities($string, $ent, $charset);
}

function html_entity_decode_PHP-5-3($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') {
    return html_entity_decode($string, $ent, $charset);
}

So just do a search & replace over all files and make sure that all scripts have a file included that contains these functions.

25. April 2013

phpLiteAdmin: Italian translation available for download

Filed under: PHP,phpLiteAdmin — Tags: , , , , , — Christopher Kramer @ 18:29

We now also received an Italian translation for phpLiteAdmin! :-)Thanks a lot to Franco Tassi who posted the Italian translation in our mailing list.

We now have translations to Arabic, Chinese, German, Italian and Russian (and English of course). In our wiki, you can find the download links and install instructions.

If phpLiteAdmin is not yet translated into your language, we would be very pleased if you translated it. It is very easy and also well explained in the wiki.

Thanks to all translators!

18. March 2013

phpLiteAdmin 1.9.4 released

Filed under: DBMS,PHP,phpLiteAdmin — Tags: , , , , , , , , , , — Christopher Kramer @ 18:53

I just released phpLiteAdmin 1.9.4. phpLiteAdmin 1.9.4

phpLiteAdmin is for SQLite what phpMyAdmin is for MySQL: A web GUI to manage your databases.

A lot of work has again gone into this release. It fixes bugs and introduces new features. No security issues fixed (compared to 1.9.3.3).

Every user of phpLiteAdmin is recommended to update.

New features of phpLiteAdmin 1.9.4 include:

  • Multi-Language support
  • external configuration possible
  • empty password -> no login required
  • easy backup of db files
  • edit and delete possible from search results
  • search function: added “LIKE %…%”
  • css and Js now served as separate, cacheable and compressed resources to speed up page loading

Important bug fixes include fixes in the ALTER TABLE support. We have again spent quite a lot of work to improve phpLiteAdmin. Thanks to everybody who reported issues and especially to the team for your work on phpLiteAdmin – especially Dreadnaut and Teryaki helped me a lot in this release. Thanks guys.

Download the new version here.

5. February 2013

Oxwall Community Software: How to create your own theme

Filed under: PHP — Tags: , , , , , , , , — Christopher Kramer @ 14:45

Oxwall is a great community-software written in PHP. You can easily install it on your own server to build your own community site.

It is open source and you have full control over the data.

Although Oxwall comes with some great themes that can even be easily customized in the backend a bit, one might want to build one’s own theme for Oxwall.

So here is how it’s done:

  1. Probably first build an HTML template of your design (one HTML page with CSS that looks like you plan how your Oxwall should look like). If you do that, make sure to use a list-based main menu and a div/link-based bottom-menu (see below) so you won’t get into trouble later.
  2. Always a good idea to have a backup – although adding a new theme shouldn’t break anything. I’d recommend you to create a copy of your Oxwall installation where you create and test your new theme and when it’s finished, move it to your live installation of Oxwall.
  3. Create a copy of an existing theme. You will find the themes in ow_themes. Choose one you’d like to use as a base for your own theme.
    Copy it. E.g on a linux shell:

    cp -rp ow_themes/spring ow_themes/mytheme

    Of course you could also use FTP or something like that.

  4. Define the meta-data of your theme like name, author and so on. To do so, open ow_themes/mytheme/theme.xml in a text editor and adjust the data. Make sure the <key> is equal to the foldername (“mytheme” in the example).
  5. If you want to, you can replace the theme_preview.jpg with a small thumbnail representing your theme (optional).
  6. Now you can select this theme in the Oxwall backend. Try it.
  7. Note: To be able to adjust the theme, enable DEV_MODE. Otherwise you won’t see any changes. So open ow_includes/config.php in a texteditor. Search for:
    else
    {
        /**
        * Make changes in this block if you want to enable DEV mode and DEBUG mode
        */
    
        define('OW_DEBUG_MODE', false);
        define('OW_DEV_MODE', false);
        define('OW_PROFILER_ENABLE', false);
    }

    Change OW_DEV_MODE to true:

    else
    {
        /**
        * Make changes in this block if you want to enable DEV mode and DEBUG mode
        */
    
        define('OW_DEBUG_MODE', false);
        define('OW_DEV_MODE', true); /* HERE! */
        define('OW_PROFILER_ENABLE', false);
    }
  8. Now you can start to adjust your theme. So what does a theme consist of?

Meta-Data: theme.xml

Like said, theme.xml contains the meta data and theme_preview.jpg is a preview image.

CSS: base.css

The main css of a stylesheet is called base.css. You can change/adjust the css there (there are also other places like the backend). I would recommend you to keep the css of your base theme and only adjust and add things to it. Otherwise you’ll have a hard time styling lots of things.

Images: images/*

If you need to include images, this is the best place to put them. If you refer to them from the css, use a path like this:

background-image: url(images/myimage.jpg);

HTML: master_pages/*

The HTML that builds your theme is stored in master_pages.

Note: Lots of themes do not contain all master_pages. If one is missing, the master_pages of the graphite theme are used. Therefore, I’d recommend you to first copy missing master_pages from the graphite theme to your theme so you get a full set of master_pages.

The following master_pages can be there:

  • admin.html (only for the admin backend – no need to adjust this)
  • blank.html (usually no need to change this as well)
  • dndindex.html (body for  pages without sidebar – you’ll want to adjust this!)
  • general.html (body for pages with sidebar – you’ll want to adjust this!)
  • html_document.html (html-head of all pages, you might want to add css or javascript here)

Markers

The following are the most important markers that you can put into your html master_pages:

{$siteUrl}

{*$siteName*}

{*$siteTagline*}

{component class=’BASE_CMP_Console’}

This is the console containing “Login”, “Register” and so on (usually at the top right corner).

{$main_menu}

A list-based menu.
Hint: Listamatic has lots of great list-based menu examples.

{$heading}

{component}

The sidebar.
Note: only in general.html

{add_content key=’base.add_page_top_content’}
{$content}
{add_content key=’base.add_page_bottom_content’}

These 3 build up the main content.
Note: You’ll only need {$content} in dndindex.html

{$bottom_menu}

The bottom menu.
Note: Not list-style, but a div with links.

{text key=’base+copyright’}

{$bottomPoweredByLink}

{decorator name=’floatbox’}

This should be at the end of your html file – oxwall puts some JavaScript and stuff like that there (for chat etc.).

All the others should be self-explaining.

So how you could do it:

  1. Upload your images to “images” and your js (of any) to the theme-folder
  2. Add your css at the end of base.css
  3. Add your references to additional css / js to html_document.html (no need to add a reference to base.css!)
  4. Put the content of your body into general.html and dndindex.html
  5. Replace your static content in there with markers.

Don’t forget DEV_MODE

When you are done, don’t forget to set DEV_MODE back to false. Otherwise your site will load slowly.

If this was of help for you or you still have a question, please let me know.

You can also contact me if you need someone to do an Oxwall theme for you.

26. January 2013

Funny pseudo-exploit for phpLiteAdmin

It seems people really got interested in the security of phpLiteAdmin. That’s cool, lots of people searching for security issues will give us the opportunity to fix a lot of things in a short period of time. Go on searching. We’ll go on fixing.

But some of these exploiters only publish an “exploit” that contains no real issue at all. Probably only to get some publicity, or maybe because they don’t even realize that what they “found” is not an issue at all. Or meant as a joke?

I recently found a new “security exploit” listing several “vulnerabilities”, which in fact are no bugs of phpLiteAdmin at all but misconfiguration or even features. So here I want to have a look at an “exploit” released by “KedAns-Dz”:

1-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=0
0     _                   __           __       __                     1
1   /' \            __  /'__`\        /\ \__  /'__`\                   0
0  /\_, \    ___   /\_\/\_\ \ \    ___\ \ ,_\/\ \/\ \  _ ___           1
1  \/_/\ \ /' _ `\ \/\ \/_/_\_<_  /'___\ \ \/\ \ \ \ \/\`'__\          0
0     \ \ \/\ \/\ \ \ \ \/\ \ \ \/\ \__/\ \ \_\ \ \_\ \ \ \/           1
1      \ \_\ \_\ \_\_\ \ \ \____/\ \____\\ \__\\ \____/\ \_\           0
0       \/_/\/_/\/_/\ \_\ \/___/  \/____/ \/__/ \/___/  \/_/           1
1                  \ \____/ >> Exploit database separated by exploit   0
0                   \/___/          type (local, remote, DoS, etc.)    1
1                                                                      1
0  [+] Site            : 1337day.com                                   0
1  [+] Support e-mail  : submit[at]1337day.com                         1
0                                                                      0
1               #########################################              1
0               I'm KedAns-Dz member from Inj3ct0r Team                1
1               #########################################              0
0-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-1
Okay yeah. We know exploiters love ASCII art. Kind of cool, agreed.
###
# Title : phpLiteAdmin v1.8.x->1.9.x (SQLi/FD) <= Multiple Vulnerabilities
# Author : KedAns-Dz
# E-mail : ked-h (@hotmail.com / @1337day.com)
# Home : Hassi.Messaoud (30500) - Algeria -(00213555248701)
# Web Site : www.1337day.com .net .org
# FaCeb0ok : http://fb.me/Inj3ct0rK3d
# TwiTter : @kedans
# Friendly Sites : www.r00tw0rm.com * www.exploit-id.com
# Type : proof of concept - webapp 0day - remote - php
# Tested on : Windows7
###
# <3 <3 Greetings t0 Palestine <3 <3
# F-ck HaCking, Lov3 Explo8ting !
As I said. I like exploits as well. Even if they just make me laugh 😉
######## [ Proof / Exploit ] ################|=>
# Google Dork :
# allintext:"Powered by phpLiteAdmin | "
##################
# [!] Description:
------------------
phpLiteAdmin is suffer from multiple vulnerabilities / bugs in
v1.8.x to-> 1.9.x , the attacker can use some bug in the Script
to inject some remote SQL command/code , and Disclosure the Full Path.
Interesting to say 1.9.x when there are still 1.9.x versions to be released in the future. So you are sure we won’t fix your “bugs”? Probably you are right 😉
# Bugs :
#-------
# Authentication Bypass
# SQL Injection/Exec
# Full Path Disclosure
#######################
#### (1) Authentication Bypass :
--------------------------------
[!] php-code :
line 38->39 :::::::::::::::::
//password to gain access
$password = "admin";
:::::::::::::::::::::::::::::
- not affected on all targets, just change the password to fix it
LOL
[+] http://[target]/[path]/phpliteadmin.php
[*] password : admin
I didn’t know we call it an “Authentication Bypass” if we use the authentication system by entering the correct password. Yeah, phpLiteAdmin has a default password, which is “admin”. No secret here. I mean, anybody keeping the default password on a publicly accessible installation should know that other people could get access. Current version of phpLiteAdmin even shows you a warning if you still use the default pw.
No “bug” or “vulnerability” at all.
#### (2) Full Path Disclosure :
-------------------------------
[+] http://[target]/[path]/phpliteadmin.php?view=import
[!] & Import File with (NULL/Bad) Content =>
- you get some sql error msg with the full path of phpliteadmin.php
ex: '-------------
Warning: PDO::exec(): SQLSTATE[HY000]: General error:
trying to execute an empty query in C:\Program Files\EasyPHP-12.1\www\phpliteadmin.php on line 987
____________________________________
Warning: SQLiteDatabase::queryExec() [sqlitedatabase.queryexec]: Cannot execute empty query.
in /homepages/20/d421371141/htdocs/pauleschoen.com/cgi-bin/phpliteadmin.php on line 646
------------------'
proof image (http://i46.tinypic.com/ddmek5.png) # in local test
proof image (http://i49.tinypic.com/juepet.png) # in remote test
LOL. That’s one of the most difficult ways to make phpLiteAdmin produce a PHP error message 😉
Probably you should configure your webserver correctly. Everybody who enables php-ini directive “display_errors” on a public server effectively provokes a “full path disclosure” somewhere. Maybe you should better publish an exploit for php itself 😉
Okay, seriously: We could use ini_set to make sure phpLiteAdmin won’t show any php errors. We probably will. But nevertheless, on about any php-server, you’ll find another script where you can provoke a php-error.
I am not saying it is good that these errors can happen at all. Of course it’d be better to improve checking of input and catch errors properly. This would be a real issue. But not a “vulnerability”. If these errors get displayed, your webserver is configured in a vulnerable way, which is not the fault of phpLiteAdmin.
#### (3) SQL Injection :
------------------------
php-code ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
$query = "SELECT * FROM ".$db->quote_id($_GET['table'])." WHERE ROWID = ".$pks[$j];
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
[+] http://[target]/[path]/phpliteadmin.php?action=row_view&table='
[&] http://[target]/[path]/phpliteadmin.php?action=row_view&table=' [ SQLi ]
If you publish an SQL injection exploit, why don’t you insert some real SQL as a proof of concept? Maybe because what you “found” here in fact is no SQL injection at all?
The function quote_id() will make sure you cannot inject some other SQL command. Of course you can “inject” some invalid table-name, which will make phpLiteAdmin show up some errors, as your “proof image” shows. So another complicated way of producing an error message. Congratulations! But you cannot inject a “DROP Table” here or something like that.
Moreover, it is ridiculous to even search for an SQL injection in phpLiteAdmin. If you are logged into phpLiteAdmin, you can of course perform any SQL command. That is what phpLiteAdmin is made for. It even gives you a GUI to perform SQL queries in a comfortable way. No need to inject them via parameters.
As long as you cannot inject an SQL query without authenticating properly, any “SQL injection” in phpLiteAdmin is not a security vulnerability but a normal issue. If some table has a special name, e.g. containing quotes, we need to make sure the name is escaped properly so phpLiteAdmin works as expected. But this is not the case here: quote_id() will make sure every table-name will be escaped properly. No issue here at all.
#### (4) Exec SQL code :
------------------------
Go to :
[*] http://[target]/[path]/phpliteadmin.php?view=sql
-& put the SQL Code in the text-area (Run SQL query/queries :)
and click 'GO' to exec ;) .
LOL. That’s a really funny one. You might call this a vulnerability, I’d call it a feature.
Don’t you show yourself here that issue 3 is ridiculous?
So I am not sure if this exploit really was meant seriously or if it was meant as a joke. It made me laugh anyway.
I hope you enjoyed it as well. Keep on exploiting!

 

3. November 2012

phpLiteAdmin 1.9.3 released (security-update)

Filed under: DBMS,PHP,phpLiteAdmin,Security,Server Administration — Tags: , , , , , , , , , , — Christopher Kramer @ 00:45

Screenshot of phpLiteAdmin 1.9.3

Screenshot of phpLiteAdmin 1.9.3

Some minutes ago, I released the new version of phpLiteAdmin, a web management GUI for SQLite databases written in PHP. You can download it from our project site.

The new version addresses and mostly fixes lots of issues. Among these, one security issue has been fixed. Therefore, I’d recommend anybody using phpLiteAdmin to update.

A lot of work has gone into this release, fixing lots of bugs to make phpLiteAdmin more robust. For example, you can now have tables or columns containing special characters. The ALTER TABLE features have been partly rewritten so they now work a lot more reliable. And lots of other issues have been fixed. Thanks to anybody who reported bugs to the bug tracker.

If you still have any problems or suggestions, please let us know on our issue tracker.

9. October 2012

Portuguese language file for CrazyStat

Filed under: CrazyStat,PHP — Tags: , , , , , — Christopher Kramer @ 14:42

I just noticed that I have not announced yet that CrazyStat has been translated into Portoguese by Pedro Cruz. Thanks a lot!

You can already download the file from SVN (click “Download this file”). Of course the file will be included in the next release.

Just upload it into your stat/src/lang-folder and select the language when logging in. You can also change the default language.

If you find any mistakes in this or any other language file, just let me know.

I hope you enjoy CrazyStat!

Older Posts »