failed Login attempts logic I want to add security to the system login. So here's my idea:

If a user tries to login with a valid username but invalid password, then count it as a failed login attempt and store it in the users database for that specific user.

After X failed login attempts for that user, take some specific action (eg. display captcha). However when that user is able to login successfully, reset the login attempts to in the database.

Is this logic any effective?

The problem is that this only helps if one particular account is attacked. But instead of trying 100 passwords on one account, an attacker might also try one common password on 100 accounts. To prevent this, you also have to monitor the total number of failed logins and start displaying CAPTCHAs when the number gets exceptionally high.

For user-friendliness, the failed logins should expire automatically after a while. It doesn't make sense to keep the counter for more than, say, 24 hours.

Last but not least, be careful with race conditions when you actually implement this. Many people first check the number of failed logins and then increment the counter if needed. But this allows an attacker to send an arbitrary number of concurrent requests between the check and the increment, and each time the server will still “see” the old counter. You need a single query where you increment the counter and get the new value at the same time, and then you have to check that value. Different database systems have different techniques for this. In PostgreSQL, you can use an UPDATE query with a RETURNING clause. In MySQL, you can use an UPDATE query with the increment expression wrapped in LAST_INSERT_ID() and then get the incremented value with SELECT LAST_INSERT_ID(). Note that you can't just make a plain SELECT query after the update, because the counter might already have increased in the meantime.


Repudiation in Copyright Infringement (BitTorrent) Seeing this question : How can alleged illegal downloading be detected? sparked a question I have had for a long time.

How does repudiation/non-repudiation work in such cases ?

Argument: It is known that violators are determined from Peer-lists of popular torrents and are reported to ISPs which in turn may send a notice. In extreme cases, we have read stories such as a person being reprimanded and heavily fined for p2p use.

How can one determine with absolute certainity that a particular PC/user in a network was involved in the sharing violation. I don't see any way to prove that especially in an environment where there are numerous computers behind a public IP.

Also, one could repudiate that an individual's wireless AP was shared between various people in the vicinity that anyone could have been part of it.

If this is the case, what information can be obtained to isolate an individual from a network and pin-point that individual as a pirate ?

A link to a recent ruling by a judge in Florida : http://torrentfreak.com/ip-address-not-person-140324/

As far as legally equating an IP address to a person, that's gone both ways in the USA.  The USA Supreme court hasn't ruled, so anything is possible. I suppose that in the Axiomatic System of the US Legal system, you could equate an IP address and a person, but in the Real World, you are correct. Such identification is going to turn out false in some cases. For instance, some people have spoofed the system, causing their printers to be implicated in file sharing.

Just as an aside, I think it's a bad idea to put things that come up false, or can be made to come up false on demand, into an axiomatic system. Theoretically, that lets you prove any theorem of the axiomatic system. Disaster for the US legal system.


Privacy error in google chrome Recently I installed some random softwares on my windows 8.1 PC from the internet and along with that some malware also got installed. I started getting " Your connection is not private " error in google chrome when I tried to open google.com .

When I checked the certificate, I found instead of Google's certificate I received "GoProxy untrusted MITM proxy Inc"certificate.

Then I checked my proxy setting. I found "Use a proxy server for your LAN" checkbox automatically checked and on clicking Advanced button, I saw my system was using 127.0.0.1 on port 8080 as proxy for both HTTP and Secure connection. When I opened http://127.0.0.2:8080 in my browser, I got the message "This is a proxy server. Does not respond to non-proxy requests"

Even if I uncheck the option to use the proxy, it automatically gets checked after closing the dialog.

My question is has the malware installed proxy server on my pc? How the malware has done this? How to resolve this issue?

My question is has the malware installed proxy server on my pc?

Based on your description this is very likely.

  How the malware has done this?

Use of proxy is only a registry setting or similar (i.e. browser profile) setting and can be changed by a process (no manual interaction required).

  How to resolve this issue?

Unless you have instructions which are specific to your malware you should reinstall the system from scratch. You might also try a trusted antivirus (AV) product and see if this helps. But don't just download some random software claiming to be an AV - there are lots of fake AV out there which do even more harm.


How to display the SHA256 hash while signing or in signature I realize (using --clearsign) that GnuPG is using SHA256 as the hashing algorithm for signing, but I would like to be able to see the actual SHA256 hash in the signature somewhere.  Is there a way with -vv or --list-packets or perhaps with xxd or something like that to show the actual SHA256 hash that is signed?

Also, if I wanted to verify that hash by hand, how would I do it?

GZip cleartext message
Hash the gzip stream with SHA256

Thoughts?

I realize (using --clearsign) that GnuPG is using SHA256 as the hashing algorithm for signing, but I would like to be able to see the actual SHA256 hash in the signature somewhere. Is there a way with -vv or --list-packets or perhaps with xxd or something like that to show the actual SHA256 hash that is signed?

Yes, you can make GPG display the signed hash when you create the signature by including the option --debug 1024 when you enter the command to sign. This will write debugging data to STDOUT - look for a line containing the text SETHASH. This will be followed by the hash algorithm ID (8 for SHA256) a space, then the full hash.
You won't be able to see this information with --list-packets because the signature itself only includes the left 16 bits of the hash in the unhashed data portion. As per the OpenPGP specification (RFC-4880) the body of a signature packet is organized as follows:

One-octet version number.
One-octet signature type.
One-octet public-key algorithm.
One-octet hash algorithm.
Two-octet scalar octet count for following hashed subpacket data.
Hashed subpacket data set (zero or more subpackets).
Two-octet scalar octet count for the following unhashed subpacket data.
Unhashed subpacket data set (zero or more subpackets).
Two-octet field holding the left 16 bits of the signed hash value.
One or more multiprecision integers comprising the signature. This portion is algorithm specific.

Also, if I wanted to verify that hash by hand, how would I do it?

The hash is done over a concatenation of the following:

(a) The data being signed. In the case of clearsigned text, any line
endings are canonicalized with <CR><LF> (0x0d 0x0a).
(b) The signature data starting at the version number and ending with the last octet of hashed subpackets (items 1 thru 6 in the list above).
(c) An extra trailer which for version 4 signatures consists of the octets 0x04, 0xFF followed by a four-octet big endian number that is the count of octets in (b) from the signature data.

Demonstration with examples
First lets create some text to sign:
$ printf "foo\nbar" > foobar

Now sign it with the debug option:
$ gpg --debug 1024 --digest-algo SHA256 -a --clearsign foobar

In the debug output the hash can be found on this line
gpg: DBG: chan_3 -> SETHASH 8 1A601BF0156447669150C0B06CEDFB24D0A08A55E1E9556ACB49F4918016BC45

Calculating the hash
The generated cleartext signature:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

foo
bar
-----BEGIN PGP SIGNATURE-----

iQIzBAEBCAAdFiEE5orKzV6pxnr3CiiWM9QrW9OS6+IFAmBv9ZsACgkQM9QrW9OS
6+IaYA/7BqcQI9ENIUGyHtxrePuP59uRzUrXGv1to6EOZPMOq9vl3Bd2rDjmplPN
N0A3egYOWD5Wx3G3ccZzGI0xzNHJEPBPcEnJ5ZOFNlpRrEq+r8r6lP+2Rr+ATa2O
goUX+jWw7yy1DZFaQZVV24dDRdszpxNFusA1l4aMipkSTgfzwrNe/Pm0tgI+YTX3
f/7ccBLpnqw55BGtzvO1dTiz5qXN6UV1eiJgKy/mtfgjiNZRpZUt7BMpV3/m6G2f
xz6rQEdKPW4ILql/mcCaVqrpHSJtNIdCh4Hoabztyt2G8xEBkMX+TkVRQ64NWpc2
RepaS0WTqGUtF/qA0OiBzsE1OOkYA0i1SbrAD4DC+MPh1V6UBI0qK5Obc0Lfj7Gt
oIXpm08OEhdQwr4Q1sDM1IlC7UPRKxv/LZp92/thy7RN3fDl9HCbPJInPGJKevBp
7yqpfkflg5RUIy6LEYqHd/YQi8pnWnwXiMinS/koe33IuJYv/kJrhcSy7wApQ7kS
xqVgGjRm1I5S8D01z0zCeBa7I/sFS+gswmuynjdKJE7W4G65ymehpLLi++J+W+MZ
NX+chJZU3DP2ZZmGqI6qyl0SB6ELE2dRF4vD+6xIm+FIzVrsR3I8eTiCzZiHoSYI
KA7zxKizS9yYxnNQW2DkAMPeNVUnlaA9j8KsWYks+UKTnpvm8Rc=
=oG3T
-----END PGP SIGNATURE-----

Canonicalize signed text: 66 6F 6F 0D 0A 62 61 72
Inspect signature octets:
89 02 33 04 01 01 08 00 1D 16 21 04 E6 8A CA CD 5E A9 C6 7A F7 0A 28 96 33 D4 2B 5B D3 92 EB E2 05 02 60 6F F5 9B 00 0A 09 10 33 D4 2B 5B D3 92 EB E2 1A 60 0F FB 06 A7 10 23 D1 0D 21 41 B2 1E DC 6B 78 FB 8F E7 DB 91 CD 4A D7 1A FD 6D A3 A1 0E 64 F3 0E AB DB E5 DC 17 76 AC 38 E6 A6 53 CD 37 40 37 7A 06 0E 58 3E 56 C7 71 B7 71 C6 73 18 8D 31 CC D1 C9 10 F0 4F 70 49 C9 E5 93 85 36 5A 51 AC 4A BE AF CA FA 94 FF B6 46 BF 80 4D AD 8E 82 85 17 FA 35 B0 EF 2C B5 0D 91 5A 41 95 55 DB 87 43 45 DB 33 A7 13 45 BA C0 35 97 86 8C 8A 99 12 4E 07 F3 C2 B3 5E FC F9 B4 B6 02 3E 61 35 F7 7F FE DC 70 12 E9 9E AC 39 E4 11 AD CE F3 B5 75 38 B3 E6 A5 CD E9 45 75 7A 22 60 2B 2F E6 B5 F8 23 88 D6 51 A5 95 2D EC 13 29 57 7F E6 E8 6D 9F C7 3E AB 40 47 4A 3D 6E 08 2E A9 7F 99 C0 9A 56 AA E9 1D 22 6D 34 87 42 87 81 E8 69 BC ED CA DD 86 F3 11 01 90 C5 FE 4E 45 51 43 AE 0D 5A 97 36 45 EA 5A 4B 45 93 A8 65 2D 17 FA 80 D0 E8 81 CE C1 35 38 E9 18 03 48 B5 49 BA C0 0F 80 C2 F8 C3 E1 D5 5E 94 04 8D 2A 2B 93 9B 73 42 DF 8F B1 AD A0 85 E9 9B 4F 0E 12 17 50 C2 BE 10 D6 C0 CC D4 89 42 ED 43 D1 2B 1B FF 2D 9A 7D DB FB 61 CB B4 4D DD F0 E5 F4 70 9B 3C 92 27 3C 62 4A 7A F0 69 EF 2A A9 7E 47 E5 83 94 54 23 2E 8B 11 8A 87 77 F6 10 8B CA 67 5A 7C 17 88 C8 A7 4B F9 28 7B 7D C8 B8 96 2F FE 42 6B 85 C4 B2 EF 00 29 43 B9 12 C6 A5 60 1A 34 66 D4 8E 52 F0 3D 35 CF 4C C2 78 16 BB 23 FB 05 4B E8 2C C2 6B B2 9E 37 4A 24 4E D6 E0 6E B9 CA 67 A1 A4 B2 E2 FB E2 7E 5B E3 19 35 7F 9C 84 96 54 DC 33 F6 65 99 86 A8 8E AA CA 5D 12 07 A1 0B 13 67 51 17 8B C3 FB AC 48 9B E1 48 CD 5A EC 47 72 3C 79 38 82 CD 98 87 A1 26 08 28 0E F3 C4 A8 B3 4B DC 98 C6 73 50 5B 60 E4 00 C3 DE 35 55 27 95 A0 3D 8F C2 AC 59 89 2C F9 42 93 9E 9B E6 F1 17

The header info tells us the signature body starts at the 4th octet with 04 01 01 08 00 1D - a version 4 signature (0x04) of a canonical text document (0x01) using an RSA key (0x01) and SHA256 hash (0x08) with 29 additional octets (0x00 0x1D) of hashed subpacket data: 04 01 01 08 00 1D 16 21 04 E6 8A CA CD 5E A9 C6 7A F7 0A 28 96 33 D4 2B 5B D3 92 EB E2 05 02 60 6F F5 9B
Since this is a version 4 signature with 35 octets of hashed signature data, we construct the extra trailer: 04 FF 00 00 00 23
This produces the full set of hashed data: 66 6F 6F 0D 0A 62 61 72 04 01 01 08 00 1D 16 21 04 E6 8A CA CD 5E A9 C6 7A F7 0A 28 96 33 D4 2B 5B D3 92 EB E2 05 02 60 6F F5 9B 04 FF 00 00 00 23
Checking the hash:
$ printf '\x66\x6F\x6F\x0D\x0A\x62\x61\x72\x04\x01\x01\x08\x00\x1D\x16\x21\x04\xE6\x8A\xCA\xCD\x5E\xA9\xC6\x7A\xF7\x0A\x28\x96\x33\xD4\x2B\x5B\xD3\x92\xEB\xE2\x05\x02\x60\x6F\xF5\x9B\x04\xFF\x00\x00\x00\x23' | sha256sum
1a601bf0156447669150c0b06cedfb24d0a08a55e1e9556acb49f4918016bc45  -

This matches the hash given in the debug output:
1A601BF0156447669150C0B06CEDFB24D0A08A55E1E9556ACB49F4918016BC45


What do the terms used in OpenPGP keyserver SKS mean? (sig, sbind, sig3, exp2, Policy, ...) When viewing a key record in a public key server, such as this one, there are lots of keywords used: sig, sig3, exp3, Policy, sbind…). I understand that "sig" probably means a signature, but what's the difference between a "sig" and a "sig3" and a "sbind"? And what exactly is a "Policy" record?

In OpenPGP, signatures are used not only for documents, but also for certifications between primary keys with different levels of trust (sig, sig1, sig2, sig3; as hex codes 0x10-0x13 in this order) and several more internal stuff.

Signatures are also very important for binding subkeys to primary keys (and the other way round): these are displayed as sbind signatures by key servers, and a simple sig by GnuPG, and have signature types 0x18 and 0x19 in OpenPGP. User IDs are bound by "normal" certification signatures, also called self-signatures or selfsigs.

If for any reason you want to undo a signature, this is generally not possible (you cannot delete anything from the key server network). Instead, you again issue another kind of signature, a revocation of a key (0x20), revocation of a subkey (0x28) or revocation of a certificate (0x30). All of those will be displayed as revok by most key servers, and rev by GnuPG.

A certification policy displayed with the key word Policy drops out of this list, a little bit, as it does not denote another signature type, but is a signature subpacket describing a so-called certification policy. I already left a more detailed description in "What are you saying when you sign a PGP key?". Notations also describe a certification, and could for example be used to describe how the signer identified the signee.

The signature types are defined in RFC 4880, OpenPGP, 5.2.1.  Signature Types, signature subpackets only a little bit further down in the same document.


How to bypass XMLHttpRequest header protection for a CSRF attack A client is only submitting forms using XMLHttpRequest with the use of a header (X-Header: [any value would be correct]) to protect against Cross Site Request Forgery attacks.

I know this is not the right way to prevent CSRF vulnerabilities, but how would you exploit this type of CSRF vulnerability?

The requirement is to send an HTTP request with a custom header.

This is a very similar method to using the X-Requested-With header, just that X-Header is used instead (neither of which are standard headers, although X-Requested-With could be considered a de-facto standard).

This is a valid method of preventing CSRF as only the following headers are allowed cross domain:

  Accept
  Accept-Language
  Content-Language
  Last-Event-ID
  Content-Type

any others cause a "pre-flight" request to be issued in CORS supported browsers. Non CORS browsers will ignore other headers.

As long as the CORS configuration isn't allowing the header and domain the attacker is using then this is a valid method.

If CORS was enabled and was allowing the attacker's domain, then other methods of CSRF protection such as the recommended Synchronizer Token Pattern would also fail because the attacker could make a GET request to retreive the token value (assuming the access-control-allow-credentials header is set to true). Note that lack of CORS does not prevent requests from being made by the browser, it only prevents the responses from being read.

So, it appears that you're out of luck for a CSRF exploit, unless another Flash or browser plugin bug/feature will allow you to add the header to the request.


Why does our Web Security team block web-fonts? The company that I work for have begun to block web fonts on external domains.

This creates a poor UX on most sites given that a large number of assets are generated through the likes of FontAwesome (as well as having to view 90% of websites in sans-serif).

What is the risk of allowing web-fonts to be downloaded and rendered by a web browser? It's the first time I've known a security team to take this measure.

When your site uses external resources (often JS libraries or fonts via a CDN), your visitors may leak information to the third-party host as their browsers request the resources in the background. Privacy concerns about such leaks may be the reason for whitelisting a few trusted sites.
Most notably, the current URL can leak via the Referer header. Imagine a password reset page with a secret reset token in the URL that loads an external font – the token may be inadvertently revealed to that third-party via request header. (E.g., this vulnerability report refers to this type of problem.) Even with no secrets in the URL or other countermeasures like a Referrer-Policy, the content provider can still collect usage statistics for your site by recording page visits, user-agent strings, etc.
Another risk of using untrusted third-party fonts may be defacement (although not as severe as script injection via external JS). That is, if the provider was compromised, an attacker could modify their fonts in a way that changes the shape and appearance of the glyphs, effectively rewriting texts on your site. For this scenario, a solution can be hash verification (see Subresource Integrity).
But even if you don't expect an attack, remember you'll have to rely on the host's availability. So if they aren't a reputable CDN, you might consider self-hosting the files.


Is it dangerous to have the built-in Administrator account enabled? I've seen it said that when using the built-in Windows Administrator account, the best practice is to enable it (net user administrator /active:yes), use it, and then disable it.

I do realize it's a security measure against malware not to use it when not needed (and in fact, not use a regular admin account either), But - why disable it?

I understand the confusion.. let me try and explain..

  But.. Why disable it..?

The reason behind disabling it.. Well.. Let me first kind of define an administrator account in a very generic way:

It is a user profile that is had administrator level privileges enabled which essentially gives that particular user complete access to the system.

So.. On windows it is named as 'Administrator'. It always exists on the system, whether enabled/disabled/in-use or dormant. So.. when malwares are written they are programmed to check for the existence of such profiles. Someone could also rename it to admin or root or something like that are generally privileged profiles.

If they do exist.. Voila... It saves me the work of "executing additional code" to gain privileges in the system. People make mistakes.. If they are enabled, let's take control and play havoc.

To make it more clear, let us assume that you are a skilled burglar and want to break into a house. Assume that the "house key" is the admin account. If I check for the house key in generic places like 'under the pot, or under the welcome cat, or on the ledge".. If I get them, I'll break in easily. If you don't keep the set of house keys outside, then I don't find it. The burglar will break it using additional pick-locks and levers (Privilege escalation methods). If your lock is unpickable then you are safe. (Relate it to something like hardening your security).

So you see, disabling it will ensure that the malware atleast has to "put in work effort" in order to gain access to the system. A highly motivated and skilled hacker might be able to get through but can be stopped by implementing tight security controls on the system. If your system is secure, then the malware is useless.

Theoretically speaking.. I hope its helpful.. :)


Is it safe to use Python package managers like pip, easy_install or conda? I know it is unsafe to install software (including Python packages) from not trusted or compromised sources.

However I wonder how safe I am when I am installing a trusted package from Python Package Index or from Anaconda repository (which I also consider trusted).

Packages in PyPI may be PGP signed, which makes me believe it is fair safe to install/update them manually.

However, there is no automatic signature verification in pip and it seems there is not going to be.

I wonder how sure can I be there is no MITM attack when I connect to PyPI (or Anaconda) repositories with either pip, easy_install or conda?

I guess pip connection uses at least SSL with certificate verification (it is known to fail with SSL error), but given that pip used plain HTTP as default in 2013 I am pretty sceptical about how strict it is e.g. in case of trusted root CA (for example if it trusts StartCOM and WoSign or not).

Does anyone know what level of security do I have when I decide to use Python package managers?

Update

My question is about safety of PyPI (and similar) clients and their connection to server while Which security measures does PyPI and similar third-party software repositories take? is about whether packages at PyPI may be trusted.
In my question PyPI and packages at the server site are assumed to be trusted.

I setup MITM for pip to pypi.python.org and it seems that pip does indeed validate the certificate. It fails with SSLError: [SSL: CERTIFICATE_VERIFY_FAILED]. Maybe I will have more luck with other repositories...

Pip may not be checking gpg signatures but it's not like you are downloading from untrusted sources. For example, Linux packages are spread across mirrors all over the world, and without gpg it would be very likely that some of these packages would be compromised. In pip case, the only source for download is pypi.python.org which is using Fastly CDN for distribution instead of untrusted mirrors.

I don't know conda, never used it.


Is it appropriate to use haveged as a source of entropy on virtual machines? While looking for solutions to entropy pool depletion on virtual machines, I came across an interesting project called haveged, which is based on the HAVEGE algorithm (HArdware Volatile Entropy Gathering and Expansion). It makes a pretty fantastic claim.

  HAVEGE is a random number generator that exploits the modifications of
  the internal CPU  hardware states (caches, branch predictors, TLBs) as
  a source of uncertainty. During an initialization phase, the hardware
  clock cycle counter of the processor is used to gather part of this
  entropy: tens of thousands of unpredictable bits can be gathered per
  operating system call in average.

If this really produces nearly unlimited high-quality entropy on headless virtual machines, it should be included in every server distribution by default! And yet, some people have raised concerns.

  "At its heart, [HAVEGE] uses timing information based on the
  processor's high resolution timer (the RDTSC instruction). This
  instruction can be virtualized, and some virtual machine hosts have
  chosen to disable this instruction, returning 0s or predictable
  results."
  (Source: PolarSSL Security Advisory 2011-02 on polarssl.org).

And furthermore, popular NIST and ENT tests will sometimes give haveged a PASS even when it's intentionally mis-configured, and not actually producing random numbers!

  I replaced the “HARDTICKS” macro in HAVEGE with the constant 0 (zero)
  rather than reading the time stamp counter of the processor. This
  immediately failed the randomness test. However, when I used the
  constant 1 (one) instead, the ent test passed. And even nist almost
  passed with only a single missed test out of the 426 tests executed.
  (Source: Evaluating HAVEGE Randomness on engbloms.se).

So, which virtualization platforms/hypervisors are safe to use with haveged in a virtual machine?
And is there a generally accepted best practice way to test whether a source of randomness is producing sufficiently high quality numbers?

(Caveat: I certainly don't claim that HAVEGE lives up to its claims. I have not checked their theory or implementation.)

To get randomness, HAVEGE and similar systems feed on "physical events", and in particular on the timing of physical events. Such events include occurrences of hardware interrupts (which, in turn, gathers data about key strokes, mouse movements, incoming ethernet packets, time for a hard disk to complete a write request...). HAVEGE also claims to feed on all the types of cache misses which occur in a CPU (L1 cache, L2 cache, TLB, branch prediction...); the behaviour of these elements depends on what the CPU has been doing in the previous few thousands clock cycles, so there is potential for some "randomness". This hinges on the possibility to measure current time with great precision (not necessarily accuracy), which is where the rdtsc instruction comes into play. It returns the current contents of an internal counter which is incremented at each clock cycle, so it offers sub-nanosecond precision.

For a virtual machine system, there are three choices with regards to this instruction:

Let the instruction go to the hardware directly.
Trap the instruction and emulate it.
Disable the instruction altogether.

If the VM manager chooses the first solution, then rdtsc has all the needed precision, and should work as well as if it was on a physical machine, for the purpose of gathering entropy from hardware events. However, since this is a virtual machine, it is an application on the host system; it does not get the CPU all the time. From the point of view of the guest operating system using rdtsc, this looks as if its CPU was "stolen" occasionally: two successive rdtsc instructions, nominally separated by a single clock cycles, may report an increase of the counter by several millions. In short words, when rdtsc is simply applied on the hardware, then the guest OS can use it to detect the presence of an hypervisor.

The second solution is meant to make the emulation more "perfect" by maintaining a virtual per-VM cycle counter, which keeps track of the cycles really allocated to that VM. The upside is that rdtsc, from the point of view of the guest, will no longer exhibit the "stolen cycles" effect. The downside is that this emulation is performed through triggering and trapping a CPU exception, raising the cost of the rdtsc opcode from a few dozen clock cycles (it depends on the CPU brand; some execute rdtsc in less than 10 cycles, other use 60 or 70 cycles) to more than one thousand of cycles. If the guest tries to do a lot of rdtsc (as HAVEGE will be prone to do), then it will slow down to a crawl. Moreover, the exception handling code will disrupt the measure; instead of measuring the hardware event timing, the code will measure the execution time of the exception handler, which can conceivably lower the quality of the extracted randomness.

The third solution (disabling rdtsc) will simply prevent HAVEGE from returning good randomness. Since it internally uses a PRNG, the output may still fool statistical analysis tools, because there is a huge difference between "looking random" and "being unpredictable" (statistical analysis tools follow the "look random" path, but cryptographic security relies on unpredictability).

The VirtualBox manual claims that VirtualBox, by default, follows the first method (rdtsc is unconditionally allowed and applied on the hardware directly), but may be configured to apply the second solution (which you don't want, in this case).

To test what your VM does, you can try this small program (compile with gcc -W -Wall -O on Linux; the -O is important):

#include <stdio.h>

#if defined(__i386__)

static __inline__ unsigned long long rdtsc(void)
{
        unsigned long long int x;

        __asm__ __volatile__ (".byte 0x0f, 0x31" : "=A" (x));
        return x;
}

#elif defined(__x86_64__)

static __inline__ unsigned long long rdtsc(void)
{
        unsigned hi, lo;

        __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
        return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}

#endif

int
main(void)
{
        long i;
        unsigned long long d;

        d = 0;
        for (i = 0; i < 1000000; i ++) {
                unsigned long long b, e;

                b = rdtsc();
                e = rdtsc();
                d += e - b;
        }
        printf("average : %.3f\n", (double)d / 1000000.0);
        return 0;
}

On a non-virtual machine, with the "true" rdtsc, this shall report a value between 10 and 100, depending on the CPU brand. If the reported value is 0, or if the program crashes, then rdtsc is disabled. If the value is in the thousands, then rdtsc is emulated, which means that the entropy gathering may not work as well as expected.

Note that even getting a value between 10 and 100 is not a guarantee that rdtsc is not emulated, because the VM manager, while maintaining its virtual counter, may subtract from it the expected time needed for execution of the exception handler. Ultimately, you really need to have a good look at the manual and configuration of your VM manager.

Of course, the whole premise of HAVEGE is questionable. For any practical security, you need a few "real random" bits, no more than 200, which you use as seed in a cryptographically secure PRNG. The PRNG will produce gigabytes of pseudo-alea indistinguishable from true randomness, and that's good enough for all practical purposes.

Insisting on going back to the hardware for every bit looks like yet another outbreak of that flawed idea which sees entropy as a kind of gasoline, which you burn up when you look at it.


Checking "return" parameter in login page My login page accepts the  "return" parameter, which should contain URI to redirect user if he wasn't logged in and tried to access page which isn't accessible by unauthenticated users. It could be anything from my site.

How do I properly check that parameter in my server code, before I return HTTP 302 status with that URI to user after he successfully authenticated on the login page?

Is it enough to check that uri[0] == '/' && uri[1] != '/' (so malicious user won't send request like /login?return=http://google.com)?

Can a malicious user construct some tricky uri which will send victim user to trouble?
Of course I assume that other pages do not contain XSS vulnerabilities, GET request do not change anything in the database, etc.

If a malicious user can trick the victim to click on his link and the victim user is already logged in, things will happen anyway and I can't do anything to prevent that except implement known security measures such as CSRF protection, etc.

The best way is to create a whitelist of possible URLs, if the redirect is not part of the whitelist you can redirect to a default home page. However this isn't too flexible.

You can also regex the whole thing so it ensures the start of the URI is your website e.g. http://example.com/ and that what which comes after your last / only contains numbers, letters, & or ? and disallow any other characters (you might as well work with relative paths).


Is older software safer to use? Is software (and even hardware) that is a few years old safer to use than something that's only been out for a few months?

On GRC Security I remember the author cautioning against Windows 7 as it has a new TCP/IP stack whereas the old one was tried-and-true. Does this line of reasoning make sense? For example it seems logical to conclude Windows 8 has more time to be tested than Windows 10, therefore Windows 8 has more of its bugs caught than Windows 10 and is thus safer.

There are way too many factors to consider in your question.

older software has had a chance to have its bugs discovered and fixed
older software might have known bugs that have not been fixed or can't be fixed (famous IE examples over the years)
newer software has not had a chance to have the same level of review and might have unknown bugs
newer software will not have had a chance to have published bugs for others to exploit

You cannot make a blanket statement about new or old software. The whole point is to perform a risk analysis of staying with old software as opposed to new software in the light of all of these possibilities. Statements, like the ones made by GRC, are about reminding people about the potential risks and cannot be used as advice to avoid anything specific.


DMARC on ProtonMail custom domain I began using ProtonMail email service, I like it that much, that I connected my domain yesterday and did appropriate changes to DNS.

This page of ProtonMail's knowledgebase says how DMARC shall be set up. An image for the words:

I have successfully connected my domain, set up SPF, DKIM, and I believe I'm ready for DMARC.

The thing is:

I am unsure if it's a good idea to set it with

p=quarantine

or

p=reject

Do I need to specify any other things like rua or ruf or anything else if I wanted to make it p=reject?

My current status is:

It depends a lot on the specific case. If you are really sure you know where all the mail being sent is coming from, and that you’ve set up SPF & DKIM appropriately, then you might go directly to p=reject or p=quarantine.

The safer course is to do a staged roll-out, e.g.:

p=none with rua and/or ruf set (there are tools like Dmarcian that you can use to help process the reports you get). Do this to make sure that everything that’s going to fail should actually fail, or fix things that you spot that you hadn’t thought about.
p=quarantine with a low percentage just to check that things are ok in practice - if you get lots of issues, then at least it’s (a) likely available in the recipient’s quarantine, and (b) only a small amount of the mail
p=quarantine with 100%, maybe with other steps in between. You might stop here.
p=reject, again maybe doing percentage steps, if you’re completely certain that failing mail should never be read by the recipient.

One thing to consider when deciding between quarantine and reject is that failures can be out of your control. For example, if someone is forwarding mail, then it’s likely there’s going to be an SPF failure (particularly if it’s not well set up) but the recipient probably does actually want the email. Similarly, if there’s something in the chain that mucks about with the message (often the subject) then there may be a DKIM failure but it’s still a legitimate message.

If you really want to say “the mail comes directly from me to you”, then reject is likely where you want to get to. If you’re ok with “the mail comes directly from me to you, and if you muck about with that then it may end up in your quarantine”, then quarantine is a better end point.


Listening to phone calls as user profiling for marketing I had a landline phone call about xyz with an xyz-expert (also on landline) for about an hour, for the first time. After couple of days I started getting suggested links on websites as an ad exactly about xyz's services.

Question: In theory, either my landline phone company or my smartphone is listening in, then probably selling my info. Is this type of ad profiling common and/or legal? Or was it pure chance I saw the targeted ad?

Update from comments:

I am based in the UK
I never did a web search on the xyz topic, nor sent/received emails regarding this topic. That is why I am assuming phone calls are being profiled.
As pointed out, the legality side belongs to a different SE, so just in case if anyone can provide legal side of the question, it would be a huge bonus.

Updated question:

I am also curious if these types of practices exist at all:

A Landline company keeping track of certain word frequencies
Or my smartphone doing something similar, even when it is not in use

Data dealers often buy data from multiple sources and aggregate it to generate an all-compassing user-profile from it. For example:

xyz company sold your telephone number and what the conversation was about.
social network which asks for your phone number for password recovery sold your telephone number and your ip address at some point in time.
advertisement network sold the tracking cookie ID for that IP address at that point in time.

Now the data dealer has linked your call with xyz to your identity on the advertisement network and can pay the advertisement network to show you xyz-related advertisement.

To avoid this from happening in the future:

Look at the privacy policy of any companies and websites you interact with and refuse to do business with them when the policy allows them to resell your data.
Do not reveal more personal information to internet services than strictly necessary.
Use a browser plugin like Ghostery or Privacy Badger to block web trackers (keep in mind that an advertisement filters like AdBlock only blocks visible advertisement and are not designed to prevent invisible trackers from tracking you).
Inform yourself about what rights to privacy you have according to your local laws and make use of them (for example, in many EU countries you have the right to order companies to tell you what private information they have about you and can order them to delete it).


How do SEO scams work? Lately, I've been getting emails for my work email address from SEO scammers. Some examples look like this:

Hi,
Hope you are doing well there!
Would you like to increase the traffic of your website?
Would you like to be listed at the top of Google for multiple search phrases (keywords) relevant to your products or services?
Contact us for the best quote for your website & we will guarantee to rank your website on the (1st page of Google) we provide a complete solution for your Online Business.
Kind Regards,
FirstName,
Digital Marketing Expert

Since our security policy says to just report and ignore them, I can't exactly reply to them. From what I Googled, articles like these just explains how my email was found out or that the service they provide are sub-optimal. But how do these scams work exactly? How are their SEO service different than a legit SEO service?

It's entirely likely that these aren't scams but rather just spam for a semi-legitimate service. Either way, they could take your money and either do some amount real SEO work or do nothing (in which case it would be a scam) and it'd be hard to judge whether or not work was actually done since SEO simply attempts to increase traffic to your site, thus using SEO techniques may not always work and likewise traffic may increase after SEO for a completely different reason. It's also possible they could use click-farming to make it seem like the "SEO" was effective in the short-term (whether or not they actually did anything).

Another possibility here is that they will ask for credentials to access your site to "do the SEO" and start using it to host phishing pages and malware, but I doubt this is likely. I'd imagine it's merely spam along the same lines of online pharmacies or "green coffee"-like miracle products: there is an actual product being sold in most cases, but the business and advertising practices are wrong.


What can and can't a malicious DNS do? I have been thinking of using http://tunlr.net/ for accessing "geo-IP banned websites" like netflix.

However, I have my concerns about safety of using some third party DNS server for everything. So, my question is. Let's suppose I use something like tunlr.net or some other third party DNS  server. What "evil" they can and can't do?

Let's also add these assumptions.

I access mails, facebooks and most importantly bank accounts only through https, but I don't check the certificates by hand, but let my browser do it for me
I generally disallow any third party plugins in browser as much as I can (flash, java, Acrobat)
I am smart enough not to fall for completely obvious phishing
I install actualization, but I don't use antivirus (since I use OS X and Ubuntu)

With all this said - if I use some third party DNS server and it becomes malicious, what can they do?

[edit, 2017 - tunlr.net is no longer operating; it was a DNS server that redirected netflix to proxied US version for free. There might be similar servers now.]

Malicious DNS alteration usually drives people to phishing sites instead of the legitimate site they want, but it can also be used to prevent machines from retrieving updates for their OS/Security software, or route your connections through a proxy where an adversary can intercept communications.


Why is so much ransomware breakable? The site: https://www.nomoreransom.org/ offers many decrypter tools for ransomware.

But why?

It shouldn't be so hard to use the Windows Crypto API (e.g. just google "create AES Key in Windows") to create AES Keys, encrypt them with a locally generated public RSA Key and encrypt the corresponding private RSA Key with a Public RSA Key that the attacker controls. (The method of Wanacry.)

If the victim pays the ransom, they have to send the encrypted private RSA key to the attackers, and hopefully get the decrypted private RSA key back.

Why do these people try to reinvent the wheel and in the process make mistakes that allow the development of decrypter tools?

Disclosure: I work for one of vendors participating in NoMoreRansom.

Most modern ransomware indeed implements proper cryptography. Earlier versions were using rand() for key generation, seeding the random generators with variants of time() - this is why it was important for successful decryption to know when exactly the infection happened; ideally down to minutes. Those could be decrypted with brute force. But most modern ransomware indeed uses either Windows Crypto API, or bundled crypto libraries.

However, no matter how correctly ransomware is implemented, there is always a weak point - to facilitate decryption, the key(s) have to be stored somewhere. This location could be traced by security companies, who would work together with law enforcement to take it over. Access to the server gives the security company the ability to decrypt the ransomware victims files. This is for example the case with GangCrab ransomware.


What is the entropy of a call to java.lang.Math.random()? Math.random() produces a double value (IEEE 754 binary64) in the range [0.0, 1.0). How many digits (or bits) of entropy does the return value of random() contain?

If it simplifies things, I'm okay with assuming the distribution is a true uniform random distribution - in which case I'm essentially asking how many unique values are contained in a double in [0.0, 1.0).

(Sorry in advance if this question is off-topic - wasn't sure where to ask.)

The representable values of any floating point scheme including 754 are never uniformly spaced. The values returned by Math.random and equivalently Random.nextDouble are uniform in the range [0,1) but are only a small fraction of the double values in that range.

The Java-default Random never has entropy over 48 bits and depending on seeding can be less, and as forest commented it doesn't even try to be secure -- techniques for breaking an LCG (Linear Congruential Generator) given a few outputs have been known for decades. In contrast there are very nearly 2^62 double values in the stated range.


Storing Credit Card Information on Mobile Phones I've inherited the code-base for a legacy mobile app (both the native Android and native iOS version) and am running a security review on it, a few things stood out to me.

The app allows a user to store their credit card details on the phone for future purchases (note: The CSN number is explicitly not stored as a security measure), when the number is presented again the number is shown masked. The numbers are stored in a hashed/encrypted state (iOS keychain, Android has it as a hashed encrypted value). When making a purchase the credit card info is sent across via a configurable url that uses https.

The app doesn't currently have integration with thrid party credit card handlers (Paypal,Stripe etc).

I'm going to push for all credit card handling to be done via secure third party vendors and am wondering if PCI-DSS standards are being violated here, I've read through the OWASP and PCI-DSS guidelines and nothing seems to be directly breached but it seems to be skirting the edge of doing so.

Credit card storage on a user device just raises red flags to me so I'd like to check if someone else has experienced something similar?

You are absolutely correct.  Storing the credit card on the device as it is currently being stored would be asking for trouble and would not be in line with PCI-DSS guidelines.  One of the "Don'ts" on the PCI-DSS compliance states "Do not store cardholder data unless it is absolutely necessary" and beyond this there would need to be adequate measures to ensure that this data was being safeguarded.  From what you have described - yes the data is encrypted but no it is not absolutely necessary to store this data.

Even Apple Pay on iPhone6 won't store your credit card details on the device - they use tokenisation.

Hope that answers your question.


Course Material for GPEN Certification? I am planning for GPEN certification, although i have been extensively involved in penetration projects, still looking at the topics it seems a bit difficult.. what could be good study guide for preparation?

I assume you're talking about a challenge certification; any other route would provide you with all the courseware you need.

As per the GIAC FAQ:

  Please review the course descriptions at http://www.sans.org to gain
  an understanding of what material is covered in each course. Please be
  sure to look at each day of training. While we certainly recommend the
  SANS training as the best method of preparing for the GIAC
  Certifications since that is what they are based on, other resources
  can be purchased at most book stores.

The exams do track the courseware closely, so it really is the best guide.  That said, I don't believe they sell the courseware alone, and selling used copies is likely against the license.  I do recall that once upon a time they would sell off extra courseware in the bookstore at conferences - e.g., they ship in 100 copies of GPEN, 90 people show up, they have 10 copies to either sell to conference attendees or box up and ship back.  So there was a legitimate sale method at least at one point.  (I purchased the GCUX set at a conference intending to challenge, but never got around to it).

You do also get two practice exams if you sign up for the challenge, which gives you a chance to figure out what topics you should study but haven't yet.  If you already hold a GIAC certification and are on any of the related mailing lists, people often give away practice exams they didn't need, maybe that would let you figure out if you want to try this before spending $1,050 to get your own practice exams.


Single web application - security advantages to two server model? I'm looking to deploy infrastructure for a web application that will live on a LAMP stack. The infrastructure is such that this is the only application that will ever live on this server and it must be as secure as possible.

Traditionally, we deploy a front end server in a DMZ and have a DB server on a segregated network and between them is a firewall rule that only allows TCP 3306 calls from the web server back to the database server. When multiple applications live on a server, I see the relevance there as if one application/site gets compromised then the potential exists to quarantine the damages to the application & credentials that have been harvested.

With a single web application I'm struggling to see how this might provide a security benefit. In theory, if your web server gets compromised then people will have access to the DB credentials the application uses at which point it's game over, right?

From a strictly security perspective what are the major reasons to split the application into front and back end servers?

In general, I agree with your implication that if you only have a single web application there is little security benefit to moving the DB onto a separate server. That being said, there could be some contrived scenarios where there might be a security benefit. For example, if the web application does not have full admin rights to the DB, then a compromised web server would reveal credentials for some access to the DB, but not all. If the DB resided on the same web server presumably the attacker might be able to gain full access to the DB too, rather than just the limited access for the found credentials. An example of partial DB rights might be giving the web application write access to a logging table but not read access.


Splitting data between wifi networks for security Does there exist, software or technology, that can use more than one wifi network, in such a way that only part of the data travels through each 'side'? You would probably need an end address like a proxy. Something similar to TOR, except each primary network wouldn't be able to intercept all the data sent or received.

Bonding two channels to the same AP is done. But you want to take it one big step further.

You could perhaps do something of the kind using two wireless cards, two separate ESSIDs and some fancy footwork at kernel level (not all OSes would be able to do that), using bonding; or, even more complicated, by using two WiFi chips on a card that would simulate a single interface and do bonding transparently (you would need special access points though - you'd be in effect doing SuperG using two APs on the same network).

But it would be very difficult to overcome all the problems - and it would be all for naught, because the radio signal would be traveling in the same volume of space, where an attacker could sniff both signals. True, he would have to decrypt two conversations instead of one, but that's a mere 2^1 increase in the hardness of the attack. Employing additional encryption over the existing WPA2 would be far easier, and garner a lot more benefits for much less effort.


Is an Initialization Vector (IV) required with unique data? When used to encrypt data that is unique, is an Initialization Vector (IV) still required? For example, Credit Card numbers or Social Security numbers.

The ultimate point of an IV is to ensure that the CipherText of two identical PlainText messages is not the same. If the PlainText is unique is there a need for the IV?

The role of the IV depends a lot on the encryption system, e.g. whether it is a stream cipher or a block cipher, and, in the latter case, the mode of operation.

IV means Initialization Vector: this is a generic term for the start value of any looping process. In cryptography, we use the term IV to designate a parameter that is used at the start of a computation, changes often, but is not secret (otherwise we would call it a key).

In general, reusing an IV is a mortal sin, but the amount of suffering implied by an IV reuse can vary. In the case of a block cipher in CBC mode, IV reuse immediately leaks whether two messages starts with the same sequence of block; and, more generally, the IV for CBC must be generated randomly, uniformly, and unpredictably, otherwise you are open to Chosen Plaintext Attacks, as was demonstrated in the case of SSL/TLS (where it was popularized under the name "BEAST attack").

If you use a block cipher in CTR or OFB mode, then IV reuse is deadly (it becomes the infamous "two-times pad") leading to easy recovery of the encrypted data. The same applies to stream ciphers that use an IV. In CFB mode IV reuse is a bit less comprehensive in its devastation but it still is dire.

As general rules:

An IV shall never be reused for a given key.
You can get away with using a fixed IV if (and only if) you never reuse a key. If each key value is ever used for a single message, then a fixed IV can be used. However, since keys are secret while IV are not, changing the IV for each message is considered easier than changing the key for each message (you can convey the IV by including it in an unencrypted file header, for instance).
Most attack models that make encryption desirable also allow for malicious alterations, so you also need checked integrity. Combining integrity and encryption is not as easy as it seems; the sane way is to use an encryption mode that does both, which, in practice, means GCM. GCM has its own requirements on IV, namely that an IV shall never be reused, and that is important.
Anything which handles credit card numbers is likely to fall in scope of PCI-DSS, and if you ask the question you asked, then chances are that your system does not comply at all with PCI-DSS, at which point it would be wiser to get your hands off your keyboard and rethink your business choices.


Content-Security-Policy & Facebook login This question seems to be related to https://stackoverflow.com/questions/15913200/facebook-js-sdk-not-executed-in-my-chrome-extension , but I am not developing a chrome extension. I am developing a normal web application.

I am trying to integrate Facebook login on my website, which has a tight CSP policy. I am following the recommendations of https://developer.chrome.com/extensions/contentSecurityPolicy , where it is mentioned that 'unsafe-eval' should not be used. However, if I put the following CSP-policy:

    <add name="Content-Security-Policy" value="default-src 'self'; connect-src 'self'; script-src 'self' https://connect.facebook.net; img-src 'self' https://www.facebook.com; media-src 'self'; object-src 'self'; style-src 'self'  'unsafe-inline'; frame-src 'self' https://s-static.ak.facebook.com https://www.facebook.com https://www.youtube.com; "/>

then the facebook login does not appear, as the CSP policy restricts unsafe eval code. If I change it to the following:

    <add name="Content-Security-Policy" value="default-src 'self'; connect-src 'self'; script-src 'self' 'unsafe-eval' https://connect.facebook.net; img-src 'self' https://www.facebook.com; media-src 'self'; object-src 'self'; style-src 'self'  'unsafe-inline'; frame-src 'self' https://s-static.ak.facebook.com https://www.facebook.com https://www.youtube.com; "/>

then it works. Notice the extra 'unsafe-eval' in the script-src part of the CSP. Anyway, I don't want to use the 'unsafe-eval' condition, as this would greatly reduce the security of my website.

Is there a way that I can use the Facebook login (SDK), without having to use 'unsafe-eval' in my CSP policy?

No, you can't use the Facebook SDK without 'unsafe-eval' if the Facebook SDK requires it, sadly. This is one of the problems with CSP. Until Facebook remove the requirement, you have to allow it.

You mention that your app may be a single-page app, but if it wasn't, you could issue the 'unsafe-eval' expression on that particular page only to improve the situation, rather than site-wide.


Modsecurity CRS how to deal with field arrays I have a question how to deal with whitelisting field arrays in modsecurity. Currently am doing the following:
... ctl:ruleRemoveTargetById=942510;ARGS:_owc_pdc_faq_group[0][pdc_faq_answer]"
... ctl:ruleRemoveTargetById=942510;ARGS:_owc_pdc_faq_group[1][pdc_faq_answer]"
... ctl:ruleRemoveTargetById=942510;ARGS:_owc_pdc_faq_group[2][pdc_faq_answer]"
... ctl:ruleRemoveTargetById=942510;ARGS:_owc_pdc_faq_group[3][pdc_faq_answer]"

Now for WP there is a limited amount of items. But another application has near unlimited fields. As far as I have found there is no way to use regex for the target parameter. I also don't believe it's possible to cut the field parameter short as there is no wildcard at the end of the field.
This wont work for the examples above:
... ctl:ruleRemoveTargetById=942510;ARGS:_owc_pdc_faq_group"
... ctl:ruleRemoveTargetById=942510;ARGS:_owc_pdc_faq_group*"

I don't want to drop the field parameter if I don't have to. I would love to hear any suggestions you may have.

This is a tricky one and I have to confirm your conclusions.
It would be sweet, if the following form would work, but it does not:
SecRule ARGS:/test.*/   "@unconditionalMatch"   "id:1006,phase:1,pass,ctl:ruleRemoveTargetById=930120;%{MATCHED_VAR_NAME}"```

So I guess dropping the rule for all of ARGS is the next best thing you can do. Maybe limit the rule exclusions to the path as well.


What are the chances of a database being hacked? How often do websites (and their databases) get hacked? Hacked as in user accounts stolen, tables flushed,  and all in all, damage done to the database.

I'm talking about e-commerce websites, and moreover, anything besides major financial institutions because I always hear about those hacks on the news.

Even if such a statistic existed, it would be meaningless because these attacks don't occur as a result of random chance.

Your chances of being "hacked" rise dramatically if:

You don't secure the application properly (SQL Injection being the most obvious, and sadly still commonplace vulnerability; others include plain-text passwords, XSS/XSRF, and not validating form/query string inputs);
You don't secure the site properly (e.g. you allow directory listings, allow anonymous FTP access, don't chroot the FTP, etc.)
You don't secure the network properly (e.g. you run services under privileged accounts, don't set up proper ACLs or firewall rules, etc.), which would make it far easier for an attacker to scan for vulnerabilities and find some means of privilege elevation.
You have a large and/or poorly-trained staff working on the system, increasing the odds of a random social engineering attack being successful.
Your site is high-traffic, high-revenue, high-sensitivity, or otherwise represents a high value to attackers, which implies a greater likelihood of a targeted social engineering or similar attack (i.e. espionage).

If you secure your environment and your applications properly, you have very little to worry about as long as you don't paint a big target sign on your back.  Once you get to that size, you should be hiring a full-time IT security consultant who will ensure that the odds of you being "hacked" are very close to zero, and/or that the actual business implications of such an occurrence would be minimal.


In the recent DKIM vulnerability, how did someone determine key length by looking at headers? Having read this recent article : Wired-DKIM vulnerability, I have a couple of questions.

How can one determine the key length that is being used simply by looking at the headers ?

And I'm assuming the attack is as follows: correct me if I'm wrong:

Factor the private key (of short key length) by knowing the public key, the mechanism (i.e. RSA etc)
Spoof the e-mail, replace the DKIM hash with hashes illegally calculated
Fool the verifier into thinking that the e-mail's origin is proper

I've written a DKIM parser and signer for Microsoft Exchange so this is pretty straightforward.  Just note that the public key stored in DNS isn't a typical public key, it is in a more compact form called "public key subject form".

  How can one determine the key length that is being used simply by looking at the headers ?

Do a TXT query for the following values in the header:
    {s value}._domainkey.{d value}   (omit brackets)
Extract the value named "p=" in the above DNS query
Use an ASN.1 parser to determine the key length and other things that are stored within the

Example Public 2048 bit key found in a DKIM "p=" query with an exponent of 65537

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoSd6ya7haEmQl1sWoEVVou8iC618evFqluT5zb
0aMEgBEfHSJRjT/FojPWqhjAtCYMAIggaE0ZxVzPDsMeRc3Mixy2WO9DWYAJuzwP7DyzUAclhGTfP4cG44SlbSsEsMM/91cu5zr9+TulnqPDxUyPvLZjGpJEHXoEWc4m
f6tbksyxZTI+wssw84NLfEs3VC4jN9P1CnfG2aTCC74lj1mePbEBCsg83+Ilz/dsDcH2FGmWVa5ytNCP7kkzyBYkfF09YpDiSXxowRGZbRkGveDvOP3ONUhLrXumpTP6
+/Hm34kbG/kGBSxNOXn8/2jf2m+08Bt8ci9Orzb2s8J81q6QIDAQAB

Simply paste this key into the ASN.1 Javascript decoder to figure out the key length.  Most programmers will just have a library to figure this out.


Why am I getting a certificate error while searching google.com.ph? I have searched many solutions but it didn't work on me please help.

(This is the message)
Your connection is not secure

The owner of www.google.com.ph has configured their website improperly. To protect your information from being stolen, Firefox has not connected to this website.

This site uses HTTP Strict Transport Security (HSTS) to specify that Firefox may only connect to it securely. As a result, it is not possible to add an exception for this certificate.
(end of message)

(The certificate)

https://www.google.com.ph/?gfe_rd=cr&ei=MRmhWOLNB-7O8gfmhKPoDQ&gws_rd=ssl Peer’s Certificate issuer is not recognized. HTTP Strict Transport Security: false HTTP Public Key Pinning: true Certificate chain:

  -----BEGIN CERTIFICATE----- MIIDHTCCAgWgAwIBAgIRAOaoGFboIEzBazRQq+owKjUwDQYJKoZIhvcNAQELBQAw
  UzEpMCcGCSqGSIb3DQEJARYaaW5mb0B0ZWNobm9sb2dpZW1vdW5hYy5jb20xCzAJ
  BgNVBAYTAkVOMRkwFwYDVQQDDBAyNjNmMGM5NWNjZDVlYmFiMB4XDTE3MDEyNTEw
  MDgwMFoXDTE3MDQxOTEwMDgwMFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNh
  bGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxEzARBgNVBAoMCkdvb2ds
  ZSBJbmMxGDAWBgNVBAMMDyouZ29vZ2xlLmNvbS5waDCBnzANBgkqhkiG9w0BAQEF
  AAOBjQAwgYkCgYEAxG2tDjKrM41STdy2LUEgW/YNlqDU3DgYOI6YJI9nzRFrFIoa
  P6CMc0w5Y9KBRMPDjUqlXBHm7MS3YMJWxRUze5/VZ3qQQJF/tm8AFMim8DRjIkpc
  /MkOhquYOUCt7eG4mDgS4307oaopoVU5XGIGyT6t5FoXyzDY1pRfH8BEBA0CAwEA
  AaNaMFgwKQYDVR0RBCIwIIIPKi5nb29nbGUuY29tLnBogg1nb29nbGUuY29tLnBo
  MAwGA1UdEwEB/wQCMAAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMA0G
  CSqGSIb3DQEBCwUAA4IBAQA05WDImY8XxmLDs2gplZXknOLZfH094iNxGUbPhNdI
  7jwTxZziR6iSxf0EhGyxkr4x/Q9Mchnca3qIqLHAf5ieqb5/wrDYLQFd++OrYE00
  EtovOUf7CVuy9gMQ26hzgdcZqbmNQivM97kZual/rzOKIwtdsoyifh3sy1DbXKaE
  WQdgYQeAyIRFW8/goB6tM5b1/E6L78PjTiIlFqAygSPAi0mfL2LLyhxvzanLjWSJ
  kwpbWQNBYhwaBrNiTka5tjgMqZwA0NJE9gU0sHBAbGPLvIC0+euZL9kZe4F/IF4L
  QpJrXJi/NxEH5JWhykipg0U1jQDPVfWCJ+IILWFF/LBt

  -----END CERTIFICATE-----

  (end of certificate)

Note that I'm searching on google.com.ph

Uninstall the Social2Search browser addon from your computer.

It appears to be intercepting connections to web sites you visit, probably to inject its content into web pages. In the process, it is inserting its own invalid SSL certificates into HTTP connections.

A human-readable version of the certificate is below -- the "issuer" of the certificate is what led me to Social2Search:

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            e6:a8:18:56:e8:20:4c:c1:6b:34:50:ab:ea:30:2a:35
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: emailAddress=info@technologiemounac.com, C=EN, CN=263f0c95ccd5ebab
        Validity
            Not Before: Jan 25 10:08:00 2017 GMT
            Not After : Apr 19 10:08:00 2017 GMT
        Subject: C=US, ST=California, L=Mountain View, O=Google Inc, CN=*.google.com.ph
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
            RSA Public Key: (1024 bit)
                Modulus (1024 bit):
                    00:c4:6d:ad:0e:32:ab:33:8d:52:4d:dc:b6:2d:41:
                    20:5b:f6:0d:96:a0:d4:dc:38:18:38:8e:98:24:8f:
                    67:cd:11:6b:14:8a:1a:3f:a0:8c:73:4c:39:63:d2:
                    81:44:c3:c3:8d:4a:a5:5c:11:e6:ec:c4:b7:60:c2:
                    56:c5:15:33:7b:9f:d5:67:7a:90:40:91:7f:b6:6f:
                    00:14:c8:a6:f0:34:63:22:4a:5c:fc:c9:0e:86:ab:
                    98:39:40:ad:ed:e1:b8:98:38:12:e3:7d:3b:a1:aa:
                    29:a1:55:39:5c:62:06:c9:3e:ad:e4:5a:17:cb:30:
                    d8:d6:94:5f:1f:c0:44:04:0d
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Alternative Name:
                DNS:*.google.com.ph, DNS:google.com.ph
            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Extended Key Usage:
                TLS Web Server Authentication, TLS Web Client Authentication
    Signature Algorithm: sha256WithRSAEncryption
        34:e5:60:c8:99:8f:17:c6:62:c3:b3:68:29:95:95:e4:9c:e2:
        d9:7c:7d:3d:e2:23:71:19:46:cf:84:d7:48:ee:3c:13:c5:9c:
        e2:47:a8:92:c5:fd:04:84:6c:b1:92:be:31:fd:0f:4c:72:19:
        dc:6b:7a:88:a8:b1:c0:7f:98:9e:a9:be:7f:c2:b0:d8:2d:01:
        5d:fb:e3:ab:60:4d:34:12:da:2f:39:47:fb:09:5b:b2:f6:03:
        10:db:a8:73:81:d7:19:a9:b9:8d:42:2b:cc:f7:b9:19:b9:a9:
        7f:af:33:8a:23:0b:5d:b2:8c:a2:7e:1d:ec:cb:50:db:5c:a6:
        84:59:07:60:61:07:80:c8:84:45:5b:cf:e0:a0:1e:ad:33:96:
        f5:fc:4e:8b:ef:c3:e3:4e:22:25:16:a0:32:81:23:c0:8b:49:
        9f:2f:62:cb:ca:1c:6f:cd:a9:cb:8d:64:89:93:0a:5b:59:03:
        41:62:1c:1a:06:b3:62:4e:46:b9:b6:38:0c:a9:9c:00:d0:d2:
        44:f6:05:34:b0:70:40:6c:63:cb:bc:80:b4:f9:eb:99:2f:d9:
        19:7b:81:7f:20:5e:0b:42:92:6b:5c:98:bf:37:11:07:e4:95:
        a1:ca:48:a9:83:45:35:8d:00:cf:55:f5:82:27:e2:08:2d:61:
        45:fc:b0:6d


Why is a system composed of two Bell-LaPadula-secure systems not necessarily Bell-LaPadula-secure? In my lecture notes, it says that a system composed of two Bell-LaPadula-secure systems is not necessarily Bell-LaPadula-secure? Is there an example that demonstrates this concept?

The Discretionary Security Property is an access matrix that is linked to that particular system.

When you combine two systems, you must rigorously review the access matrix that will be assigned to the new composite system.

In cases where the classifications and compartments do not align perfectly, careful consideration is necessary to maintain a level of security that is equivalent or better.

In addition, there is the possibility that the scope of information available in each system is different. The aggregation of information possible after the systems are combined may exceed the intended security level, even if the original classifications and compartments aligned perfectly. The original access matrix was based on assumptions about what the information that the system would hold, and those assumptions are no longer true.

The original Bell-LaPadula model does not address either of these concerns, but any modern efforts should be capable of addressing the issues with some planning.


How to convert 64byte openssh-key-v1 to the resulting 32byte ed25519 private key I wrote an openssh-key-v1 Protocol reader and extracted all fields according to the format definition:
 "openssh-key-v1"0x00    # NULL-terminated "Auth Magic" string
 32-bit length, "none"   # ciphername length and string
 32-bit length, "none"   # kdfname length and string
 32-bit length, nil      # kdf (0 length, no kdf)
 32-bit 0x01             # number of keys, hard-coded to 1 (no length)
 32-bit length, sshpub   # public key in ssh format
     32-bit length, keytype
     32-bit length, pub0
     32-bit length, pub1
 32-bit length for rnd+prv+comment+pad
     64-bit dummy checksum?  # a random 32-bit int, repeated
     32-bit length, keytype  # the private key (including public)
     32-bit length, pub0     # Public Key parts
     32-bit length, pub1
     32-bit length, prv0     # Private Key parts
     ...                     # (number varies by type)
     32-bit length, comment  # comment string
     padding bytes 0x010203  # pad to blocksize

After that is done I stucked with a 64byte uint8 list that somehow needs to be converted into a 32bit 32 byte ed25519 binary private key. I could not find a definition on how to do that.
The only hint I got is that the private key is encoded according to RFC 4253 SSH Public Key format and RSA private keys swap e and n for n and e.
I assume that I have this:
[32-bit length] [RSA exponent or EC type name]
[32-bit length] [RSA modulus or EC x+y pair]

Do I need to calculate the seed on my own now? Is the second 32byte my seed?

In an OpenSSH 'new format' keyfile (as also in the SSHv2 protocol) the number of values, each with 4-byte length, after the 'type' (formally algorithm-name) in a publickey is always 2 but (like the privatekey) it varies: 2 for RSA and ECDSA, 4 for DSA, 1 for Ed25519.
For Ed25519, the privatekey (after the name) has 2 length-prefixed values: the first is a copy of the publickey (32 bytes), and the second is what is labelled the 'secret' (private) key in the code, but actually is 64 bytes of which the first 32 bytes are the actual private key and the second 32 bytes are yet another copy of the public key!
Compare https://unix.stackexchange.com/questions/466179/show-values-of-an-ed22519-private-key-stored-in-openssh-format .


XSS why \n must be replaced by \n I came across the following xss fix. The old code was:

this.commentText = new Text(Sanitizer.sanitizeForHtml(commentText.getValue()));

The xss fix code is:

String sanitizedText = Sanitizer.sanitizeForHtml(commentText.getValue()).replace("\n", "\n
");

Can you please clarify to me how \n can be used in XSS? and how replacing it with \n
 will solve the problem?

It is not meant as a protection against XSS and there is no common context where it would do.

Instead, the authors solve the problem that the newline character (\n) does not display a new line in HTML, so they add the
 tag to enforce a visible line break.

The authors of the code even explain it in a comment themselves here:

//replacing "\n" with "\n
" here is to make comment text support displaying breakline
String sanitizedText = Sanitizer.sanitizeForHtml(commentText.getValue()).replace("\n", "\n
");


Should a hostname ever be considered a secret? I've been told in the past that you should never give out the host names of computers on your network. I can't think of any reason why this would be the case.

Could someone tell me if they should be considered sensitive information and if so, why?

Two reasons I can think of:

Attackers will know which servers are more valuable to attack. e.g. TEST_BOX_04 vs DB_BACKUP_02
Attackers will have better idea of the topology of your network: How many servers you have; which other servers probably exist because semantic implication (host03 implies host01 and host02); what style of application stack you have (eg. web_app_server implies 3-tier; cloud_proxy may imply 4-tier); and which company assets are being allocated dynamic vs static IPs (valuable assets tend to have static IPs)


Can I complete SSL Certificate Domain Control Validation (DCV) We host sites for multiple companies and sites are hosted with custom domains.
For Example

news.CompanyX.com
news.CompanyY.com

We have complete control on hosted site but do not have control over "CompanyX.com" or "CompanyY.com" and emails of these domains. These companies add CNAME DNS entries for sites that we host.

Tried to search little bit and as per this link https://support.comodo.com/index.php?/comodo/Knowledgebase/Article/View/791/0/

"We look for the file at every valid Authorization Domain, i.e. we start with the FQDN and then we will strip one or more labels from left to right in the FQDN and will look for the file on each intermediate domain."

They have said that they will strip labels and look for files on each intermediate domain. But we don't have access to web servers of "CompanyX.com" or "CompanyY.com".

Is there any way, we can complete DCV (for news.CompanyX.com single domain certificate) on our own without contacting CompanyX or CompanyY.

The preferred method of domain control validation is usually to receive the email address registered in the whois database. However, Comodo does provide a couple alternative validation methods:

  Validation by alternative methods of DCV – There are currently 3 alternative methods you can pick from. The first two involve uploading a .txt file containing hashes of your CSR to your web server. The third involves adding the hash of your CSR as a DNS CNAME for your domain. In all cases, Comodo will run an automated test to ensure that you have completed the task.

Since you control neither the registered email address nor the DNS, the only validation mechanism that you can do is the one where you serve a certain text file on the domain. So yes, you can pass domain validation for the subdomain you have control of. Your domain control validation will only be considered valid for the subdomain you control.


When using VeraCrypt, can't someone just tell I have a hidden container by sheer file size? I've just read that with VeraCrypt it is impossible to determine whether there are hidden files or not. Sure, the rest could be free disk space. But couldn't a nasty coercing person that is scornful and envious about not being able to access your files force you to not only give the password to the non-secret container, but also force you to write so much stuff into it that the stuff from the secret container will sure be overwritten, so you will lose all your files?

... and of course the other thing the malicious coercing person could do, is say "fine, I don't believe there's no other hidden files in this container, so, copy everything out of the container and delete the container."

This would completely defeat the purpose of the hidden stuff in the container. If that stuff is nowhere else, you could lose everything! Just imagine!
Thanks.

You've just described Rubber-hose cryptanalysis. And yes, someone can force you to do all sorts of nasty, nasty things to your containers. think of it this way -- how do you defend against a malicious actor who wants to smash your laptop hard drive to bits? Backups, and lots of them.

Every program has its limitations. But backing up your containers frequently (or simply making the data in your hidden containers disposable) can mitigate the risk. Or get really good at bluffing.


non-MiTM Reverse SSL Do non-MiTM Reverse SSL Proxies exist? Or do all proxies that do SSL-SSL mappings decode and then re-encode HTTPS traffic?

If this is the case and I want to map https://mypublicdomain.com -> https://myprivatedomain.com how do I go about building a network where only the server at myprivatedomain.com can decrypt the HTTPS request.

There are two fundamental facts to know about SSL/HTTPS:

HTTPS is HTTP-within-SSL. In particular, URL don't exist at the SSL level. From the outside, without decrypting the contents, one can see that "this is SSL" and also that "this is for host www.example.com", but not "this is for URL https://www.example.com/foobar/index.html". The "foobar/index.html" can be discovered only by the SSL end, where decryption occurs.

In your case, this means that any redirect will have to be all-or-nothing: the complete site hierarchy, not a subtree thereof.
The HTTPS client (the Web browser) insists on finding in the server certificate the server name it expects, i.e. the one from the URL.

In your case, since you want the client to see a URL starting with https://mypublicdomain.com then the server certificate will need to contain mypublicdomain.com. Since you want the decryption to occur on the private server, then this means that the private server must use a certificate with the name of the public server in it. And since you want the decryption to occur only on the private server, then the corresponding private key must not be known to the public server.

The bottom-line is that the private server owns and controls a certificate with the name of another server, and that other server does not control the corresponding private key. Usually, Certification Authority call that "fraud" and try real hard not to let that happen. So you should be able to do that only if you own and control both servers, and the separation you try to enforce is some security-related isolation, not an ownership difference.

So what you seek to do may happen only if you:

Accept that the proxying occurs for a complete site, and do the proxying down to the level of IP packets or TCP connections. In fact, when this occurs, we normally say that this is virtual hosting, not proxying (this can work with SSL, e.g. see this, provided that the client supports the Server Name Indication TLS extension).
Somehow find a way to have a certificate with the public name in it, but the private key is known only to the private server. If you own both, then that's easy and up to you. If the public server is some hosting provider of whom you are only a customer, then this may be difficult.


How can wrong time synchronization be exploited? It happened to me a few times that I installed a Windows PC after the CMOS battery has been replaced and all sorts of things stopped working or threw security warnings, only to realize that I just need to set the clock, or click on the sync button.
From the above experiences I deduced that time synchronization is important for security. Intuitively I feel like time synchronization is important, e.g. a certificate can be valid at a certain time, but revoked at a different time, but it's unclear how dangerous time missynchronization is.
If we consider the certificate example, I can imagine that the conversation between my browser and some certificate server goes like this
me: is this certificate legit right now (my current time: 1st of January 1970), cause I need to know if I can safely write my password on the bank's website?
server: this certificate is not legit right now (by the way, the current time is 29th of November 2020).
From the above conversation we can see that we can figure out whether a certificate is legit "right now" by asking about its "right now" status, regardless of the absolute time associated with it, so regardless of how wrong my time is set.
So, what kind of vulnerabilities exist on a PC with a wrong time, but otherwise as safe as any other PC with an up to date windows, and perhaps some antivirus software?
Assume the PC is used in a typical scenario, say, an office with important documents, but still human operated. The PC in question is not the one operating nuclear attacks, nuclear reactors, anything with nuclear in its title, or anything that can be considered a gun, or a bomb.
There is a similar question asked, but it only deals with a hacker having access to setting the time on a PC, I am more asking of the dangers of just having a wrong time set, which is otherwise working correctly.

If your time is wrong, this can lead to a system no longer being accessible. So the "otherwise working correctly" is limited. Many security protocols (ok, TLS not so much, except for CRLs) rely on time being synchronized more or less. For example: most Windows 10 systems fail when they are more than 5 minutes off (best practice Kerberos value).
Forensics is also a lot harder; you need to keep your time differences at hand when you are correlating logs. Also, when it comes to a court case, your explanations become hard to follow for non-technical people (f.e. judges) if the times don't match.
The same problem, for example, with a contract with a file date years back. To find the latest document: sort by date. Too bad that the contract with all the amendments you made has an earlier date than the original contract.
And your incremental backup may go wrong too.
So all sort of things go unpredictably wrong, sometimes in a way that will be detected much later. The influence will probably be more on the integrity and availability than on the confidentiality.


Are there any contactless (RFID/NFC) card vulnerabilities that are still unsolved? even minor ones The title is pretty self explanatory. The market is pretty secretive about these kinds of matter since companies won't give out vulnerabilities for attackers to abuse and will give out vulnerabilities that are solved and attackers would think the same way, but maybe an unsolved attack was leaked somewhere and I'm interested to find out about it.

The NFC relay attack is still unresolved. Most of the attacks discovered against contactless payments work on top of the relay attack. The identified security issues result from flawed implementation of the standard. Others stem from failure of the issuer and the terminal to validate EMV transactions which is highly flexible in terms of card authentication modes, cardholder verification methods, and online/offline authorizations.
[1] The most recent vulnerability is found to be in VISA contactless payment in which the attacker modifies the unauthenticated conversation between the card and terminal to bypass PIN verification. It executes relay attack using 2 NFC enabled smartphones. One modifies specific bits in transit and another relays it to the terminal by pretending to be a tokenization app (like Google Pay and Apple Pay). Both smartphones are connected over wifi but they can also carry it out from large distance from each other (see [6], optimised relay attack).

In a Visa contactless transaction, the card’s response to the terminal’s GET PROCESSING OPTIONS command carries the Card Transaction Qualifiers (CTQ) whose integrity is not protected. The CTQ is a 2-byte data field that instructs the terminal which Cardholder Verification Method (CVM) is to be used.

The smartphone exploits this and implements a man-in-the-middle attack that:

Clears the 8th bit of CTQ’s first byte, which tells the terminal that online PIN verification is not required.

Sets the 8th bit of CTQ’s second byte, which tells the terminal that the CDCVM (Consumer Device Cardholder Verification Method) was performed.

[2] Last year in Blackhat Europe 2019, First Contact - Vulnerabilities in Contactless Payments presented another man-in-the-middle attack that also bypasses Visa’s PIN verification with very similar exploitation.

In the TTQ sent to the card, the CVM required field (byte 2, bit 7) is changed from 1 to 0. This field indicates whether to require additional cardholder verification for the transaction.

In the response from the card to the terminal CTQ, CDCVM performed (byte 2, bit 8) is changed from 0 to 1. This tells the terminal that cardholder verification has already been
performed on the device.

TTQ is a terminal-sourced data field passed onto the card within the payload of the GET PROCESSING OPTIONS command..

This attack is carried out with 2 microcontrollers performing relay attack. [1] can be assumed to be its optimisation and more scalability.

Neither of them works on MasterCard because the card’s support
for the CDCVM in MasterCard is defined by the 2nd bit of
AIP’s first byte and AIP is sent with authorization request to the issuer as shown in Book 4, 12.1.1, .Authorization Request, Table9. Physical cards have this bit cleared. Setting this bit for contactless cards will result in a declined transaction.

Terminal has higher floor limit for mobile wallet (£5500) than for contactless card (£30) above which the terminal requests online PIN verification regardless of CDCVM. As both [1] & [2] pretend to be a transaction coming from tokenization app, £5500 is the maximum payment they can make without triggering online PIN verification.

Pre-play Attack
[3] In BlackHat 2015, Crash & Pay: How To Own And Clone Contactless Payment Devices shows how legacy contactless Magstripe mode can be used to trick MasterCard and VISA card to generate cryptograms which can be stored unused by the attacker. The nonce that is used in this mode is 2 digits which takes 0.25 minutes to store 100 unused cryptograms for all 2 digit nonce. For 4 decimal places, it takes 25 minutes to store 10,000 unused cryptograms. Then the attacker generates a fraudulent Magstripe mode contactless card to spend these cryptograms.

With generation of cryptogram, Application Transaction Counter (ATC) of the card is also incremented and is integrity protected by the cryptogram. The jump in ATC instead of next incremented value at the time of using stored cryptograms can decline the transaction but the issuers don't detect this jump.

[4] In USENIX 2013, Cloning Credit Cards: A Combined Pre-play and Downgrade Attack on EMV Contactless shows the same exploit on MasterCard. [3] extends this attack to MasterCard as well as VISA.

Pre-play attack on Google Pay
[5] Hack In Paris - Talk 16 - NFC Payments The Art of Relay & Replay Attacks by Salvador Mendoza shows pre-play attack on Host Card Emulation (HCE) backed Google Pay. HCE produces token to request transaction authorization from the issuer. These tokens can be stored unused by the attacker as shown in [3]. Google says it's an intended behavior for HCE based contactless payments.

It doesn't work on modern smartphones with Secure Element (SE) because SE implements EMV like transaction over NFC.

Optimised relay attack
[6] In Blackhat 2016, Relaying EMV Contactless Transactions Using Off-The-Self Android Device shows an optimised relay attack with transaction completion time equal to that of actual contactless payment. This allows relays to carry out the attack over large distance without being identified as suspicious.

[7] Guessing PIN code of smartcard using brute force and offline reader
The specifications for contactless transactions specifically exclude the use of offline PIN verification (full details in Book A, section 5.9.3). Many of the contactless cards were/are in circulation in the UK allow access to offline PIN verification with PIN Try Counter resets each time the payment card is used in a Point of Sale terminal or ATM. This way attacker can have unlimited attempts to guess a card’s PIN.

How many have been fixed?
There's no effective countermeasure against relay attacks. The recommended completion time is 500ms but there's no hard limit on the maximum completion time above which the transaction should be either timed out or declined. 24C3: Relay attacks on card payment: vulnerabilities and defences (24:12) talks about Distance Bounding Protocol to combat relays. Distance bounding is in the EMV Contactless specification and Mastercard has taken up this defence, meaning its cards (at least) are protected.
Magstripe contactless payments are already being deprecated by issuers. In countries where contactless payment is recently mandated, legacy contactless Magstripe mode does not even exist in cards. Issuers are too secretive about their detection methods to combat fraudulent transactions which is often the time where flaws exist due to their out of specs implementation and logically flawed verification.


Secure installation of KVM VPS? This question has also been asked on Server Fault, but was not taken seriously. I hope this is a better place for it

I'm going to install Debian Wheezy on a KVM VPS. VNC access to console is enabled, and by sniffing network traffic when connecting, I see VNC password is encrypted but everything else is sent in plain text. It's possible to install Debian remotely over SSH by loading the "network-console" component early in the installation process. After configuring the network, a dialog asks for "Remote installation password"

I can then connect to the installation with ssh installer@x.x.x.x and continue the installation over an encrypted connection. However, the remote installation password has to be typed while connected via VNC, and is therefore sent in plain text. An attacker who sniffs the password can then compromise the installation.

What is the best method in this case to avoid an attacker compromising the installation?

Before typing the remote installation password it's possible to execute a shell. However, the installation environment is very limited so only few commands are availiable. I think the best option is to restrict SSH connections to only my IP address, but this do not seems to be possible.

Another option I have thought about is quickly connecting to the installation after typing the remote installation password, and then remove the "installer" user from /etc/shadow thereby avoiding others from logging in, but not sure if this is safe enough. I hope there are more options I haven't thought of.

Presumably by KVM you mean KVM rather than KVM.

So in this case, you should have a Linux host and N virtual machines, potentially accessible over VNC.

If your Linux host is not trusted, then nobody can save you. So we'll assume network traffic can't be sniffed within the kernel. So in that case, SSH-ing to the server and forwarding the VNC connection over your SSH tunnel effectively encrypts your traffic from the server to your SSH console on your own machine.

While the VNC connection is unencrypted at both ends of the tunnel, the first in is on your own computer (presumably trusted) while the second end is within the kernel on the Linux server (also presumably trusted), and at no point is VNC traffic sent over the network; it stays within the SSH tunnel.


Encrypting data in a load-balanced application - am I doing this right? A web application I'm developing needs to store some sensitive data in a database. I need to be able to retrieve and use this data later on so hashing isn't enough.

The web application might, at some point in the future, be load-balanced, so I'm trying to get things done correctly now instead of battling this later.

I've created a two-step process for this using standard technologies:

The sensitive data is encrypted using AES in the SQL database.
To make sure the AES key/IV values are as secure as possible, they are encrypted by the IIS web application using DPAPI (user scope) and stored in a file in App_Data.

This is because I don't think I can make use of the DPAPI alone if load-balancing will be in use - am I correct?

I'm wondering if I'm not overcomplicating things with the second step, but I don't like the idea of keeping the AES key in plain-text in some web.config file in the IIS application.

Is this approach OK and relatively secure?

The ideal for a situation like this is to use an HSM, but baring that as an option, using the software equivalent in DPAPI is probably your next best bet.  I also don't see an issue with storing each server's copy of the key encrypted with the DPAPI key for that server/service user.

You certainly do not want to simply store the key, unprotected, in the file system.  Almost any compromise at all of your server would leak it without further protection.

One possible enhancement, though it would require a bit of programming to retrieve, is to store the key itself in DPAPI.  It's only a small level of extra protection, since the key is still stored (in encrypted form) on the system, but it makes it marginally harder to find and may make it slightly easier to access from within your program.  Without looking in to it in depth, I think that is probably what I would do.


Unauthorized access to a page - when or if you should return 401 HTTP status code When a user requests a page that they don't have access to; should you return a 401 HTTP status code and a page to notify the user.

In the past I have worked under the idea thats bad practice, as when doing a security audit of a website gleaning information like this is a real page, you are just not authorized access it, is valuable information that could be exploited.

How should this be handled or is it just on a case by case basis?

Sounds like you mean 403 forbidden, not 401 unauthorized (since you say authorized access, not authentication). This source explains it in better detail: Daniel Irvine

401 Unauthorized, the HTTP status code for authentication errors. And that’s just it: it’s for authentication, not authorization. Receiving a 401 response is the server telling you, “you aren’t authenticated–either not authenticated at all or authenticated incorrectly–but please reauthenticate and try again.” To help you out, it will always include a WWW-Authenticate header that describes how to authenticate.
Receiving a 403 response is the server telling you, “I’m sorry. I know who you are–I believe who you say you are–but you just don’t have permission to access this resource. Maybe if you ask the system administrator nicely, you’ll get permission. But please don’t bother me again until your predicament changes.”

I've never heard of a 401/403 status code being bad practice. In non-attack scenarios, it serves the important function of letting a user know that they need to request a privilege upgrade or go to somebody with higher privileges to complete some task. In many of these cases a user needs to know that the resource exists.
It does reveal to attackers that a resource does exist, potentially enlarging the attack surface of your app. However if you're depending on an attacker not knowing about a resource to keep it safe, you should probably improve the defenses around it instead. The usability advantages outweigh the slight security disadvantages.


Is sql where queries in authentication prone to timing attacks, if one or no database rows are returned? Say I have this code for authentication.

   $me = mysql_query("SELECT * from users WHERE id='$_COOKIE[userid]' && password ='$_COOKIE[pass]'") or die (mysql_error());
   $me = mysql_fetch_array($me);

To authenticate a user to a website, something on the user's computer has to match what's on the server (this question is not about preventing cookie stealing as all websites can have cookies stolen regardless), but is there a way to do use sql where to check if it matches in the database without it being prone to a timing attack?

What if someone modifies their cookies to a different userid and password to try to find out someone else's password using a timing attack? If $me produces 0 results instead of 1 result, does that change the average time it takes to run the query?

If yes, how should I change my code, because I can't figure it out? Should I add a random delay to the code above, and does it make a difference as I read it wouldn't.

One way to protect against timing attacks when querying an indexed database field, would be to hash the value server-side. It's similar to how an attacker can't login if they obtained hashes of a password because the server still applies the hash before checking the database.

The original code (from the question above) has a number of issues, as marstato's answer pointed out, so let's start with this code instead:

$token = $_COOKIE['token'];
$db->query("SELECT COUNT(*) FROM sessions WHERE token = ?", $token);

The attacker can indeed incrementally find a valid token. It is typically hard or impossible, but in theory, this works. The attacker would query "A" and the server would ask the database for "A". Then they try "B" and the server asks the database for "B". If "A" was faster, they now try "AA" and "AB". If that is slower, they might try "BA" and "BB", etc. There's a lot more to it, but to recap the general idea of a timing attack, that's how it works.

To fix the issue, you could do this:

$secret = 'qJHcsgkED0egeuljhsZr'; // randomly generated
$hashed_token = hash_hmac('sha256', $_COOKIE['token'], $secret);
$db->query("SELECT COUNT(*) FROM sessions WHERE hashed_token = ?", $hashed_token);

Let's try the attack again: the attacker tries "A" and the server queries the database for "a661024ef...". The attacker tries "B" and the server queries the database for "5407624cb...". The timings are equal (or at least random) because neither will exist and it will never lead the attacker to a valid token.

This is, of course, dependent on the $secret remaining secret. It would be best practice to change this regularly so that an old employee cannot know the secret and apply the attack, but this does mean that you have to also change all values in the database. If the database can do HMAC, you could work around that by doing something like this:

$secure_rnd = openssl_random_pseudo_bytes(16);
$randomized_token = hash_hmac('sha256', $_COOKIE['token'], $secure_rnd);
$db->query("SELECT COUNT(*) FROM sessions WHERE hmac(token, '$secure_rnd') = ?", $randomized_token);

Security-wise, this is the best approach for three reasons:

While it is equivalent in speed to a non-indexed field, it prevents a future database admin from accidentally indexing the field. Typically, one would index a field when it is used for lookups. This leads to a timing attack, but how would you tell your future database administrator? Better have code in place such that it does not matter whether the field is indexed
If the field were merely non-indexed, there may still be an attack: the database will go through each row and compare the values. Going through each row and comparing the first character is O(n), but if the database compares more characters (because more than zero characters match), it will take slightly longer, so an attacker could (again, theoretically) observe this slower response and learn that they guessed more than one character correct of any token. Using a $secret or $secure_rnd is not vulnerable to that.
It does not depend on a static $secret that may be known to old sysadmins.

The downside is that it is an O(n) slow query.

A hybrid approach, to take advantage of an index while avoiding a static $secret, might be to use a $secret that is changed daily. During the transition period every night, the application server could first try today's secret and, as a fallback, yesterday's secret. Since your tokens as well as the hashing method should be secure (otherwise you have bigger problems), looking for two values should never lead to collisions with other tokens. Once every database record is updated, it can stop querying for the old $secret. The cron job that updates the database can write the secret(s) and upgrade status to a config file.

That said, I have never heard of anyone using a timing attack like this. Comparing passwords in a language like PHP, yes, but not with a database query. Most session token systems I know work in this theoretically-insecure way and yet they never seem to get hacked. That doesn't mean it's impossible, and especially if it seems 100% possible in theory, someone will probably make it work in practice sooner or later. While I'm not sure all this effort is necessary today for a small website, it would be good to protect high-security systems.


How does an encryption master key work Apparently the 'secure' cloud-encryption service BoxCryptor supports master keys for encrypted files.

  Decrypt every file which is accessible by any member of your organisation.

How would a 'master key' be securely implemented in practice, not specific to BoxCryptor? Would each file be encrypted twice: once with the user's key and once with the master key? Or is there some way to encrypt a file such that either of two keys, but only those two keys, could decrypt the file? Short of encrypting twice, I don't see how that is possible.

In regards to Boxcryptor, every user has its own RSA key pair which is generated locally on his device and the private key is encrypted with a so-called password key. The password key is derived using PBKDF2-SHA512 from the user's password. The encrypted private key and the public key are stored on Boxcryptor's servers for Boxcryptor accounts or in a local key file for Local accounts.

The master key is a separate RSA key pair and the private key is also encrypted with a password. In order to "activate" the master key for a user, his password key is encrypted with the public master key and the encrypted password key is then stored at Boxcryptor's servers.

Whenever the company needs access to a user's files, it can use the private master key to decrypt the user's password key and then use the password key to decrypt the user's private key.

You can read more about it in the official technical overview:
https://www.boxcryptor.com/en/technical-overview#anc05