Showing posts with label security. Show all posts
Showing posts with label security. Show all posts

Jan 21, 2015

Bypassing restrictive firewalls


The usual company security setup is to block all incoming and outgoing connections, letting through only HTTP(S) traffic.

Now, the trivial way to set this up (and to punch through the firewall) is to simply open the port 443 for HTTPS. To bypass this you can simply set up a VPN connection or proxy on that port.

More restrictive options include a proxy and/or deep packet inspection. Because HTTPS is encrypted via SSL, the proxy acts like a kind of man-in-the-middle. To accomplish this, the proxy makes a secure connection with the site you want to visit, and establishes a secure connection with the client with his certificate. Because there is a mismatch in the certificates, company computers must have the proxy's own certificate authority installed. Obviously if you have your own computer (without the proxy's CA marked as trusted) such connections would fail.

This also causes some privacy concerns when browsing on a corporate network, so in this article we will go through some of the options for maintaining privacy.

The only way through a proxy is to establish another HTTP proxy or a HTTP tunnel.
A HTTP tunnel encapsulates TCP data in standard http.

http://sebsauvage.net/punching/

The two most common solutions for this are


However these two didn't work for me.

When you are on a network secured with a proxy with a deep packet inspection, this data is examined and fails because the proxy firewall detects some weird base64 data being passed on, and blocks it.

Interestingly, another solution has worked.

stunnel (https://www.stunnel.org/index.html) makes an SSL tunnel (HTTPS uses SSL), so you will need a server with port 443 open and not in use.

First, install stunnel



apt-get install stunnel4 -y
Next, create a configuration file

nano /etc/stunnel/stunnel.conf

debug = 5
output = stunnel.log
cert = /etc/stunnel/cert.pem
key = /etc/stunnel/key.pem
[ssh]
accept  = 443
connect = 127.0.0.1:22
Generate server's certificate

openssl genrsa -out key.pem 2048
openssl req -new -x509 -key key.pem -out cert.pem -days 1095
cat key.pem cert.pem >> /etc/stunnel/key.pem
This will make an SSL tunnel on portz 443 which will connect to SSH on localhost, port 22. You will use this tunnel to create a SOCKS proxy via SSH.

On the client side, also install stunnel. We will use the Windows version this time.
https://www.stunnel.org/downloads.html
There is also an Android version.

The windows version includes a sample configuration file, that you can leave as is. The only thing to add is the section for the SSL connection on your server.

[my-conn]
client = yes
accept = 127.0.0.1:9922
connect = your.host:443
And that's it. Well, allmost.

Fire up PuTTY and navigate to Connection > SSH > Tunnels. Set source port to 8080 and choose Dynamic, then click Add. Connect with PuTTY to localhost 9922 (SSH).

Now you've made a SOCKS proxy on localhost port 8080 which uses the SSH on your server via SSL tunnel on port 443.

Congrats!

Nov 14, 2013

Encoding Web Shells in PNG IDAT chunks




Roses are red,
violets are blue,
images contain code,
you're hacked.


I've just had the privilege to have my mind blown, while reading this article:
Encoding Web Shells in PNG IDAT chunks. All credits go to Phil for this one, an IT consultant and hacker from down under. You should check out his other articles. Fascinating stuff.



In layman's terms, let's say you have a web page that allows user upload of images. You're feeling pretty safe about it, because when the image is uploaded, you immediately open and manipulate it in GD, a PHP image library, before you save it on the server. If you can't open the file, it's not a valid image. That should destroy all malicious code stored within the image, right?

That's right. It should.

But what if an image appears normal, and after you resize it in GD, a PHP shell appears out of thin air?

An image that contains a PHP shell "<?=$_GET[0]($_POST[1]);?>" when resized to 32x32 with GD.


There's no way around it. You can't really prevent it. And to make things worse, you're not even checking the file extension.


If you reverse the process of how the image is generated, you can encode all sorts of data in the image. When the image is then manipulated with GD, it produces plain text data within the image.
Sounds simple enough, but there are a few hoops one needs to jump through, to engineer such an image.
First, PHP code must be compressed, then reverse the PNG filtering process and finally embedding the data as raw pixels.


Depending on what the server does with this image, there are a few more tricks to be done.
If the file is resized with imagecopyresampled(), the payload needs to be encoded in a series of rectangles or squares.

Et voilà! Your PHP shell.



Oh sh*t!
But what can I do about it?

Like I said, not much. Without getting in too much detail on how this sorcery is done (you can check the source article for that), all you can do is focus on the prerequisites that enable this hack to work. Just uploading the image is, thankfully, not enough.

If you're a developer, don't be stupid. Don't do stupid things. Validate user input. Sanitize data. Have total control over how and where the files get saved. Triple check file and directory permissions and file extensions. There are many image hosting services and with the cloud becoming more and more popular, there are things like Amazon S3 you can use, to host data on third party.

Also, having total control over the file extension is not foolproof. You see, if your script contains a Local File Inclusion vulnerability (LFI) as well as user image upload, then my friend, I have bad news for you.
An attacker can just as well exploit the LFI with the path to the .png on the server.


Oh, you have all your include()-s and require()-s prefixed and suffixed? Tell me all about it! But while you're at it, have a look at this stackexchange debate. [*sound of explosion*]

If you're a user innocently hosting your web page somewhere, you can hope that your hosting provider has tight security, but also check file and directory permissions. Anything that isn't specificaly meant for upload, shouldn't have write access for apache. That typically means 644 or -rw-r--r--, for you. If you have .htaccess enabled, you can disable PHP execution on directories with user upload. See how below. Make sure it's not writable by anyone else.

If you're a sysadmin, you can expect your users to run all kinds of outdated opensourcy mumbo jumbo, which is like magnets for abusers. But you can't just mess with their files and do as you please. You've g0t r00t, and that's your real power. Figure out which directories can be written to by the web server, and stop PHP execution on these directories.
For example, Wordpress:

<Directory /home/test/www/wordpress/wp-includes>
php_flag engine off
</Directory>

<Directory /home/test/www/wordpress/wp-content/uploads>
php_flag engine off
</Directory>

Even though these directories contain PHP scripts, they're never called directly by URL. They are require()-d or include()-d by index.php originally. However, this raises another issue - source code disclosure, if done sloppy. The example above is quick and dirty. Yes, sloppy. Do some work.
Also, you can use a Web Application Firewall, like mod_security or things like that. Unfortunately, they wouldn't help in this my-png-is-a-shell situation. But they can solve a lot of other potential problems.


Well thanks, Jean! You've *really* helped me out with this information! ...NOT!

I've said it once, I've said it twice, I'll say it again.
There is no standard solution for this.
You're gonna have to find every hole through which an attacker can crawl through, fix every sensitive information disclosure (don't display error messages on the page, don't display source code - with php_flag engine off it will be displayed!). Don't be sloppy, don't be stupid.

Feeling safe yet?
If not, you can give us a call, and we can do some penetration testing for you.

Mar 25, 2013

Java, PHP :: RSA Asymmetric Encryption

Information Security and Privacy was a pretty fun and interesting class I had in college, I learned quite a lot of interesting new stuff, but when it came down to it, in practice, I had some problems implementing encrypted communication between Android (Java) frontend and PHP backend because of a tiny little detail.
Algorithm of choice was RSA and the most important part is to use "RSA/ECB/PKCS1PADDING" algorithm when calling Cipher instance in Java, other stuff is pretty straightforward.

RSA works like this.
Imagine a scenario where Alice sends an encrypted message to Bob.
As you can see, Alice encrypts data with Bob's public key, and only Bob can decrypt it, because only he has his private key.

Here's the Java code (Warning, some Android elements ahead)
public class Encryption {
 private static Key  privKey;
 private static PublicKey pubKey;
 private static PublicKey servPub;
 
 private static String  tag  = "Encryption";
 private static String[]  alg  = {"RSA","RSA/ECB/PKCS1PADDING"};
 private static String  hash  = "SHA1";
 private static String  serverPubKeyB64 = ""; //Bob's public key here
 
 
 public static String encrypt(String data) {
  return b64(encrpyt(data.getBytes()));
 }
 
 public static byte[] encrpyt(byte[] data) {
  genKey();
  try {
   Cipher c1 = Cipher.getInstance(alg[1]);
         c1.init(Cipher.ENCRYPT_MODE, getServPub());
         return c1.doFinal(data);
  } catch(Exception e) {
   Log.e(tag, "encrpyt", e);
  }
  return new byte[0];
 }
 
 public static void genKey() {
  if (privKey == null || pubKey == null) {
   Log.i(tag, "generating key");
   try {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(alg[0]);
    kpg.initialize(1024);
    KeyPair kp = kpg.generateKeyPair();
    privKey = kp.getPrivate();
    pubKey = kp.getPublic();
   } catch (Exception e) {
    Log.e(tag, "genKey", e);
   }
  }
 }
 
 public static PublicKey getServPub() {
  if(servPub == null) {
   try {
    byte[] encodedPublicKey = b64decode(serverPubKeyB64);
    
    KeyFactory keyFactory = KeyFactory.getInstance(alg[0]);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    
    return publicKey;
   } catch(Exception e) {
    Log.e(tag, "getServPub", e);
   }
  }
  return servPub;
 }
 
 public static PublicKey getPubKey() {
  genKey();
  return pubKey;
 }
 
 public static String getPubKeyB64() {
  PublicKey key = getPubKey();
  if(key != null) {
   return b64(getPubKey().getEncoded());
  } else {
   Log.e(tag, "getPubKeyB64 - key is null");
   return "";
  }
 }
 
 public static String b64(byte[] b) {
  return Base64.encodeToString(b, Base64.DEFAULT);
 }
 
 public static byte[] b64decode(String str) {
  return Base64.decode(str, Base64.DEFAULT);
 }
 
 public static String sha1(String data) {
  return sha1(data.getBytes());
 }
 
 
 public static String sha1(byte[] data) {
  return formatString(sha1bytes(data));
 }
 
 public static byte[] sha1bytes(byte[] data) {
  try {
   MessageDigest md = MessageDigest.getInstance(hash);
   return md.digest(data);
  } catch(Exception e) {
   Log.e(tag, "sha1", e);
   return new byte[0];
  }
 }
 
 @SuppressLint("DefaultLocale")
 public static String formatString(byte[] data) {
  StringBuilder sb = new StringBuilder();

  for (byte b : data) {
      sb.append(String.format("%02X", b));
  }
  
  return sb.toString().toLowerCase();
 }
}
And the PHP code:
class Encryption {

    public $pubkey = '...';

    public $privkey;
 
 public function __construct() {
  $this->privkey = openssl_pkey_get_private(file_get_contents('....pem'));
 }

    public function encrypt($data) {
        if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
            $data = base64_encode($encrypted);
        else
            throw new Exception('Unable to encrypt data.');

        return $data;
    }

    public function decrypt($data) {
        if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
            $data = $decrypted;
        else
            $data = '';

        return $data;
    }
}

Jul 11, 2009

Windows Tips: How Be Safe From Viruses / Kako ostati varen pred virusi

English version | Slovene version

Here's a non-developing blog entry... So, how to be safe from viruses?

I get asked this question a lot lately (wish I knew why, is there a new dark age coming or something?), especially which Anti-Virus software should one use, to be 100% safe from viruses.

Well, I'm not a big fan of Anti-Virus programs (I do use one, for "just in case"), nor do I want to advertise such software and above all, I don't think that any program can ensure full security.

Here's why (sorry for the lecture):
Viruses exist for any Operating System (Windows, Linux, ...). They're not called the same on different operating systems, but they act the same. They have simmilar methods of reproduction, and so on. Making a virus is very easy, even if you are a beginner at programming, making a good virus is a bit harder, but not much. A virus is a program, like any other, but it does stuff it's not supposed to, and that's why it's flagged as being a virus (malicious). And because it's a program, detecting it may be difficult sometimes, because it's functions don't look as fishy as they actually are - the program does things any normal program would do, let's say connects to a server and communicates with it. A lot of programs do that. Your browser does that. Your browser could be a "virus" if it would let someone else have access to things they're not supposed to.

Okay, enough of that, let's get to the good part.

Here's a short list of 4 simple tips you should follow, and if you'll follow all of them, you'll quickly find out that you don't have any use of your Anti-Virus program anymore.
They mostly apply on Windows Operating systems, but the idea is general.
  1. Disable Auto-Run
    Disable it. Disable it for everything. For CDs, USB keys, everything. It's useless and it's a major security problem. It's also a VERY popular way of virus reproduction.
    If you don't know what Auto-Run is, read about it on the wiki, but in a nutshell, AutoRun is a Windows service that enables a computer to run a program automatically when you plug in your USB key or a CD/DVD. Running a program whitout knowing what it is is like jumping from a bridge. It's dangerous and it's very likely that you'll get hurt.

    I'll be short on How-Tos, but here are some links:
    Basically, you navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Cdrom in your Registry, and set the AutoRun DWORD value to 0. You might also disable autoplay in your gpedit.msc - Local computer Policy\Computer configuration\Administrative Templates\System, select the item "Turn off Autoplay" and click the "Enabled" radio button.

    Also, if you don't know how to disable AutoRun, there is an alternative:
    If you hold the
    Shift key when you plug in a USB key/CD, you temporarily disable AutoRun.

  2. Use a firewall
    Firewalls come in many forms - there are physical firewalls, such as routers (but firewalling is not the router's primary function), and there are software firewalls.
    Firewalls block certain types of internet communication. They filter open ports which is also a very common way for virus reproduction:
    An infected machine connects through the internet to another vulnerable machine which has a vulnerable service running. But note that:
    • A computer is only vulnerable if it has a vulnerable service running
    • If the computer has no open ports (no services running) it cannot be infected/hacked via the internet.

    Which brings us to...
  3. Updates!
    A lot of people disable automatic updating (Control panel\System Properties\Automatic updates), because either they're afraid they might get that annoying little Windows Genuine Advantage tool or that they'll get viruses from it. Viruses from Microsoft updates?!?! Come on...
    Updates are in most cases a very good thing to do - if you don't care about security, you should at least care about the cool new features you get with the new version of any program. Programmers don't always get it right in the first try, that's why updates come in handy.

  4. Use your brain
    You heard me. Don't be stupid. Don't click on everything shiny, don't click on anything before reading what it is and understanding what it does. Don't open every email attachment. When you're browsing on the web, don't click on every link. Look at where it's pointing (in the status bar). If it's an .EXE file (a program) be extra careful, don't run it if you don't know what it is. KeyGens are NEVER what they say they are on the internet. Don't click on every "OK" or "I Agree" button. Some people think that when they suddenly have an unknown toolbar in their favourite browser, they have a virus. That's not true. They got that toolbar when they clicked on "I Agree" sometime in the near past without reading what it does.


Well that's all folks, I hope this article widens your horizon on computer security. Because I'm in an extra helping mood today, I'll translate the article for all of my Slovene friends.
Top
___________________________________________________________________________________

Zdaj pa en ne-programerski članek. Kako ostati varen pred virusi?

Zadnje čase dobivam to vprašanje zelo pogosto (ko bi le vedel zakaj, prihaja kakšna temna doba ali kaj podobnega?), še posebej: kateri Anti-Virus program naj bi uporabili, da bi bili 100% varni pred virusi.

Nisem ravno navdušen nad AntiVirus programi (sicer uporabljam enega "za vsak primer"), nimam niti želje oglaševati teh programov in povrh vsega, ne verjamem, da lahko program zagotovi popolno varnost.

Še razlog zakaj (oprostite za pridigo):

Virusi obstajajo za vsak Operacijski Sistem (Windows, Linux, ...). Ne kličejo se povsod enako, vendar obnašajo se isto. Imajo podobne načine razmnoževajna in tako naprej. Narediti virus je zelo lahko, tudi za začetnika programiranja. Narediti dober virus je malo težje, vendar ne veliko.
Virus je program, kot vsak drugi, le da počne stvari, ki jih nebi smel in zato je označen kot "virus". In ker je program kot vsak program je včasih zelo težko ga odkriti. Včasih so funkcije virusa zelo podobne običajnim programom, recimo, program se poveže na strežnik in z njim komunicira. Veliko programov to počne. Vaš brskalnik to počne. Vaš brskalnik bi lahko bil virus, če bi dovolil nekomu dostop do reči, do katerih nebi smel.

No, dovolj tega, preidimo do bistva.

Tukaj je kratek seznam štirih preprostih namigov, katerim lahko sledite, če pa upoštevate vse, lahko hitro ugotovite, da nimate več potrebe po uporabi antivirusnega programa.
Namigi so večinoma za Windows operacijske sisteme, vendar velja za vse.
  1. Izklopite Auto-Run
    Izklopite ga. Izklopite ga za vse. Za CD-je, USB ključke, vse. Neuporaben je in jezelo velik problem kar se tiče varnosti. Poleg tega je to zelo popularen način za samodejno razmnoževanje virusov.
    Če ne veste kaj je AutoRun, preberite o tem na Wikiju, v bistvu je pa to orodje operacijskega sistema Windows, ki omogoča samodejno zaganjanje programov, ko priklopite USB ključ ali CD/DVD v računalnik. Zaganjanje programov, brez vedeti kaj počno je kot skakanje čez most. Je nevarno in zelo verjetno je, da se boste poškodovali.

    Bom kratek pri navodilih kako to izklopiti, tukaj je pa nekaj povezav o tem: V registru pridete do mape HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Cdrom in nastavite AutoRun DWORD vrednost na 0. Dobro je tudi izklopiti autoplay v gpedit.msc - Local computer Policy\Computer configuration\Administrative Templates\System, izberite "Turn off Autoplay" in kliknite na "Enabled".

    Če ne znate izklopiti AutoRun, obstaja alternativa:
    Če držite tipko
    Shift, ko priklopite USB ključ ali CD s tem začasno izklopite AutoRun.

  2. Uporabljajte požarni zid
    Požarni zidovi obstajajo v različnih oblikah - obstajajo fizični požarni zidovi kot so usmerjevalniki (vendar požarni zid ni glavna funkcija usmerjevalnika), obstajajo pa tudi programski požarni zidovi. Požarni zid blokira določene vrste komunikacije prek iterneta. Filtrirajo odprta vrata kar je tudi zelo razširjen način razmnoževanja virusov:
    Okužen računalnik se poveže na ranljivega prek interneta, na katerem teče ranljiv program. Vendar pomnite:
    • Računalnik je ranljiv samo, če na njim teče ranljiv program
    • Če na računalniku ni odprtih vrat, potem ta računalnik ne more biti okužen preko interneta / vanj se ne da vdreti preko interneta.

    Kar nas privede do...
  3. Posodabljanje!
    Veliko ljudi izklopi avtomatično posodabljanje (Nadzorna plošča\Sistem\Avtomatične posodobitve). Ali se bojijo, da bodo s tem dobili tisto nadležno Windows Genuine Advantage orodje, ali pa da bodo s tem dobili viruse. Virusi pri posodabljanju Microsoft?!?! Dajte no...
    Posodabljanje je v zelo veliki večini primerov zelo dobra stvar - če vas ne zanima varnost na računalniku, vas bi lahko vsaj zanimale vse nove in kul funkcije, ki jih dobite z novo verzijo programa. Programerji ne zadenejo vse v prvo, zato pridejo posodobitve zelo prav.

  4. Uporabljajte možgane
    Prav ste me slišali. Ne bodite neumni. Ne klikajte na vse kar se sveti, ne klikajte na karkoli, predno preberete kaj piše in razumete kaj bo stvar storila. Ne odpirajte vsake priponke v spletni pošti. Če brskate po spletu, ne klikajte na vsako povezavo, poglejte kam kaže (na dnu programa piše). Če je povezava .EXE datoteka (program) bodite še posebej previdni, ne zaganjajte ga, če ne veste kaj bo storil. KeyGeni niso NIKOLI kar pravijo da so na internetu. Ne klikajte na vsak "V redu" ali "Strinjam se" gumb. Nekateri mislijo, da ko se na njihovem priljubljenem brskalniku nenadoma pokaže nova orodna vrstica, da je to virus. To ni res. To orodno vrstico so dobili, ker so v nedavni preteklosti kliknili na gumb "Strinjam se", brez da bi prebrali kaj piše.

No, to je to, upam da vam ta članek razširi obzorje računalniške varnosti.
Vrh