Why do CVSS scores change? In National Vulnerability Database page (https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2016-0778), from the change history, we can see CVSS v3 scores has been changed overtime. For example, CVE-2016-0778 has this CVSS score when it was added:
AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H. After sometime, they updated it to AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H. Here, AV - Attack Complexity is changing from Low to High. I think it means, the vulnerability is more difficult to exploit. why these changes are needed?

Generally speaking, vulnerabilities are rescored as they become better understood.  It seems that Mitre often scores something in a worst case scenario and then lowers the score as the issue is studied some more.

As to the this particular vulnerability, it's not 100% clear, but the scoring was changed at the same time they made several other changes - one of which was adding the vendor advisory.  That advisory states "The matching server code has never been shipped, but the client code was enabled by default and could be tricked by a malicious server into leaking client memory to the server, including private client user keys."  So, for someone to take advantage of this vulnerability they would have to 1) write the appropriate server code and 2) get a server to use the modified version and 3) get a client to connect to the compromised server.

Now, take a look at a CVSS v3 calculator, for a low attack complexity it says "Specialized access conditions or extenuating circumstances do not exist.  An attacker can expect repeated success against a vulnerable component."  That clearly isn't the case as the attacker must have a compromised server (i.e. a specialized access condition).  Now look at the description for high attack complexity, it says in part "a successful attack ... requires the attacker to invest in some measurable amount of effort in preparation of execution against the vulnerable component before a successful attack can be expected."  Based on the advisory, that certainly seems to be the case.

Disclaimer: I had nothing to do with the scoring of this vulnerability by Mitre (though I do write advisories and score vulnerabilities for my employer), but given the information available, this change makes sense to me.


What would be the scenario if P = NP for RSA algorithm? Suppose I am using RSA for my security system. Now someone discovers find a polynomial time algorithm for RSA. Then what measure should one that such that RSA never breaks. Maybe large number of used bits or something else.

If it is proven that P=NP then this means that a polynomial time algorithm for breaking RSA exists. Finding that algorithm might be challenging, though. On the other hand, P could be distinct from NP and yet factoring could accept a polynomial-time algorithm. Integer factorization is not proven to be a NP-complete problem.

Moreover, "polynomial" is an asymptotic behaviour, which describes how the running time of an algorithm behaves on sufficiently large inputs. Nothing says that common RSA key sizes are "sufficiently large" for the asymptotic behaviour to be a reasonably accurate estimate of performance on these key sizes. Finally, "polynomial" does not necessarily mean "fast"; an algorithm with cost O(n12) (for a RSA modulus of n bits) would have cost 2120 for a 1024-bit RSA key, i.e. totally unachievable in practice.

That's the problem with reasoning on poorly-defined hypothetical scenarios: anything can happen, really. So the question cannot be answered, except by gut feelings. My own guts tell me that if a polynomial factorization algorithm is found, then it will probably be quite expensive for "normal" integer sizes, and use sufficiently advanced mathematics that we will have a few months or years before practical implementations appear, which should give use enough time to switch to something else (e.g. elliptic curves). But, of course, my guts are just digestive organs, good at breaking down food into nutriments; what do they really know about cryptography ?


How could someone create a Facebook account with my email address without stealing it? Someone with the same name as my sister seems to have inadvertently created a Facebook account with her email address. The funny thing is that this person doesn't seem to have ever accessed my sister's Gmail account. My sister tipped me off that emails from Facebook were appearing in her inbox. I took a look, and saw the following:

"Just one more step to get started on Facebook"
"Welcome to Facebook - get started now!"
"Getting back onto Facebook"

By clicking the link in one of these emails, I was able to log into the new Facebook account, and change the password.

The strange thing is, a Facebook account with an unverified email should show that yellow bar at the top of the screen, but this one didn't; yet, in the account settings, my sister's email address is listed as the primary address, but not verified.

Any ideas how this could have been done? Or if you need me to check something on the account, let me know. Thanks.

Besides the fact the facebook account could have been created there is also the posibility that the emails are phising attempts that only look like they are coming from facebook.

So do not follow links in the emails, it may not be facebook they go to.

The idea in another answer to reset the password to prevent the account from being accessible by those who created it is good, but go to facebook directly to do it. You may find out that facebook have no knowledge of the email address (a recover password mail may never appear).

If you follow a link in the mail and alter the password to your usual password, you may very well just have given phishers access to all your online logins.


How are viruses attached to files? How do viruses attach to files? How does it infect applications? I'm talking about down to the binary level, how does code get added to a file to make it infected?

Obviously, if we hash check the original, it will have a different hash from the infected file. Does that mean it has extra data added to the file? How does that work?

Forgive me if my question is not very clear, I find it difficult to portray my meaning. Just to ensure my point is made, this is how I view it right now:

< IMAGE BINARY > + < virus > = < IMAGE BINARY < virus > >

Depends on the virus, and on the type of file. Also, bear in mind that a "virus" technically describes a self-replicating form of malware - there are other forms of malware which can be concealed within files using similar techniques. So:

Executables: Most executable files are relatively sparse - there are big gaps between the legitimate code and data for various reasons. Can be for performance reasons, or to take advantage of compiler optimisations, or just because various compiler flags weren't set to squeeze the output size to the minimum. Some viruses take advantage of this, and insert their instructions in these gaps, which changes the resulting hash of the file (note that a different hash means the contents are different, not just that the file size has changed). By hijacking the program entry point to execute the virus code before or instead of the legitimate code, a virus can be executed when the application is started.

Note that in this case, executable files include things like DLL files - they are essentially Windows executables which expose functions, rather than being self contained applications. There are some technical differences, but in terms of infection, they are pretty much identical - just hijack a call and make it point to your code rather than the original.

Linux executables are very similar, in having empty space, but the file system may also attempt to enforce rules as to whether specific files are treated as "executables" or "data", which can slightly complicated the issue.
Data files: Some data files, especially media files (images, sounds, videos), use a block structure, where a number of distinct types of data are stored in distinct blocks. For example, a PNG file is comprised of, at minimum, three "chunks": a header, the image data, and an end of file marker. In these files, it's often possible to add extra blocks using the correct form, and add arbitrary data: in a PNG file, this could be adding an "iTXt" chunk, which is just a block of Unicode text.

However, data files generally can't execute themselves, so there will normally be either a modified executable file as well, or a targeted flaw in a processing application. For example, if there was a command line image processing tool which took a folder of images and processed them in some way, it might be that a flaw could be found that meant by providing a specific input file it added data to all files in the folder processed after the "evil" file making them behave in the same way. This could be classified as virus-like behaviour, but wouldn't meet some definitions of a computer virus.

For some file types, it's valid to add data after the legitimate file content too. For example, JPEG files can still work if you simply append text files to them - exactly as your mental image. This could be used by a virus, but due to the the lack of executability, is unlikely to be the only part of a virus.

Other forms of malware make use of similar techniques: there are whole families of malware which are inserted into PHP files and then execute when someone accesses the related page. Ransomware is often distributed by hijacking Javascript files and adding malicious code to them. In these cases, though, the code isn't usually self-replicating, so doesn't meet all the technical details of being a virus.


What should I look for when auditing a Firefox extension / plugin? I've been asked to do a security audit on a Firefox add-on developed by a third party. I am a web developer with a reasonable grasp of JavaScript but am not a browser security expert.

What kinds of things should I be looking for in the source code which might represent a security risk. Also, are there any effective tools for obfuscating browser extension source code?

IMPORTANT: This is in noway a full list of the things you should look for, use this answer as an example, a first step in your path and research on your own. I've had a similar task long time ago. I had to security-wise review the code of a Firefox addon, I'm sure you'll easily find Chrome/other browsers' equivalents. Also have in mind the Extensions in Chrome run in a Sandbox.

1. Anything that interacts with local files:

Whenever the FileUtils.File object is created and any of its methods is called

Check if the local file access is a documented behavior. What are files being accessed? Why? Are they released successfully?
Check if any local files are being modified. Is that a documented behavior? What are the modified files? Why?

2. Anything that interacts with Windows Registry:

Whenever an instance of nsIWindowsRegKey is created or any of its methods is called

Is Windows Registry access a documented behavior? What keys are accessed? Why?
Is Windows Registry modification a documented behavior? Is the modification temporarily? What keys are modified? Why?

3. Anything that interacts with the cookies

Whenever nsICookieService is used

Is accessing cookies a documented behavior? Why?
To which domain do these cookies belong? Why?

4.Any commands executed in the user's shell

Whenever nsIProcess is created and any of its methods called (closely watch .run() and .launch())

Is executing commands a documented behavior? Why?
What commands are being executed? Where is the output redirected?

5. Any window/tab being accessed

Whenever window is accessed and/or any getElement* method is called (closely watch createElement calls that inject <script> elements.

Is accessing a web page's DOM a documented behavior? Why?
What are the elements added/removed/modified? Why?


Easiest way to secure my home network from work pc I am about to start a work at home position using a mac. I will be using my own personal internet to connect to their servers through their VPN.

I want to isolate my work PC from accessing my home PC internet use; is there an easy way to acheive this? From what I understand I can isolate my work PC from the network which will effectively hide my home PC's history, what would be the easiest way to do this?

Buy a small OpenWRT router with a WAN ethernet port and LAN wifi and/or LAN ethernet port.
Plug the WAN port of your OpenWRT router on your home network.
Plug your work computer on the LAN port of your small OpenWRT router.
Configure OpenWRT router's firewall with a strict ruleset allowing only internet access and denying every access to your LAN.

And that's it.
This is basically the cheapest and simplest solution for a poor-man network isolation ;-)
A manageable switch with VLAN support would be the ultimate solution, but the price isn't the same (a small OpenWRT router with dual ethernet and wifi will cost you about 20$).


Apple ID scam, gave control of my computer for a few minutes I was called from what appears to be a legitimate apple phone number and I was told there was suspicious activity. Then I said I wanted to speak to someone and I was connected to a someone with an Indian accent. This person made me type www.fastsupport.com\apple into the run command and I installed something that gave this person control of my computer, similar to teamviewer.

I got an email from apple.care@techie.com which was in the spam folder and the guy opened netstat in cmd. Told me some stuff I didn't understand. Then he did something which started bunch of lines appearing on the command line. At that point I got spooked and closed the cmd and the connection.

What might be compromised, what should I be doing now?

Worst case.

Strictly speaking, a machine where someone got to run something you don't know - whatever it actually did - is to be treated as "compromised", i.e., all accounts on it have to have their password changed, the data saved to backup before reformatting the machine, reinstalling the OS and restoring the documents - if you're really paranoid, the documents first need to be converted in a less vulnerable format (so for example all PDFs to Jscript-less PDFs, all Word DOCs to macro-less RTFs, and so on), and the backup virus-scanned from another, known good machine.

Also, any home banking accounts need to be re-secured, and all sensitive information (credit card numbers, emails etc.) checked and, if necessary, invalidated and re-issued.

Even apparently "innocuous" information might be used to impersonate someone even weeks after, and there are actually scamming "firms" that purchase such information from lesser criminals and "groom" them for weeks or months before striking (bottom line: you being scammed by an apparently innocuous "small fish" out of potentially sensitive information might end up, much later, with that information in the hands of those who can make the most out of it).
In its most visible form this is called "CEO email fraud". I have been personally involved in investigations in two such (much smaller, around USD 100,000) cases, but the latest case I know of is just days ago ("The CEO mail was false: 17 million USD lost"). So if you're involved with a large and possibly vulnerable firm (head accountant, books reviewer, CEO, lawyer, consultant etc.), take care to warn them. The market is so juicy that people are working hard at such heists.

Likelier (in MY opinion) case.

It is possible - I suspect "likely" - that nothing got compromised, and the guy at the other end of the line just typed some command like DIR /S or TREE to cause a lot of "computerish-looking" output.

The next step would have been to tell you that your PC had been infected, whatever antivirus you were using was no good, and you needed the new and enhanced antivirus from Apple Support.

Sometimes they also insist that if you refuse, they have no choice but to disable your Apple ID since it may be used to commit fraud, rape, arson, murder and rape.

At this point you are directed to a website where you can purchase said antivirus for a reasonable fee. And that is when you get it in the neck.

There several flavours of this scam:

"almost honest" scam: you are buying a semi-fake product that will also try to have you purchase additional plugins, enhancements, add-ons and so on.
credit card fraud: you enter your credit card details to make the purchase, and, well.
the application you're buying is not an antivirus at all but mainly a backdoor. Your system is now well and truly compromised, in addition to the financial damage. The backdoor access might also later be sold to worse criminals. Usually it gets immediate use as spam relay, cryptocoin mining and distributed denial of service, all services that are commonly marketed on the dark Web. It goes without saying that all interesting information on the machine will get pillaged (up to and including the worst case, above).


Is it advisable to create a system that stores passwords? Please bear with me, I'm a total newbie about security.

I work in a company whose main goal is to maximize profits and use free stuff as much as possible. It's effect is that we use tons of freeware web apps that helps us the production with the efficiency.

Also with regards to reports, we mostly use excel to pass around information or dashboards.

Couple of months ago, the company needed to adhere to data privacy act which required everything to be password protected which scopes the excel files.

Now, everyone keeps forgetting their passwords. So a solution was raised, to create a system that centralizes all the passwords of a certain group. Basically it's a notepad containing all the passwords of a team for their reports.

Is this even a good idea?

From a developer POV, there should be systems that helps people do their stuff not using excels and SSO must be implemented but since the company won't provide budget for technology we are in this situation.

You are right in suspicion that storing all passwords in unencrypted notepad file is a bad idea.

Good news is, systems you seek exist and they are called password managers.

Password managers store passwords in secure way.
They make you remember only login and a master password that gives you access to all the rest.

For your case I'd recommend KeePass. It's open source, free and tested by various security audits.

In company I work for we use KeePassXC, because it's open source, works on windows aswell as linux and supports browser addons that ease access (we use KeePassHelper addon). The addon we use provides 'bonus' layer of defense against phishing sites - as it displays something along like "domain unknown" (which I cannot emphasize enough how helpful it is in my company).

KeePassXC also supports synchronization across devices and can use iCloud, Google Drive or Dropbox as cloud service for password database - but please note that this doesn't mean you share your passwords with Google, Apple or w/e as the the password database is heavily encrypted.

KeePass also has android and iOS apps but since I don't use them, I don't really know how they operate.

Please note that there are other password managers like 1Password, LastPass and recently widely advertised Dashlane. Some of them offer bonus paid features (like synchronization across devices in their cloud) so make research what would suit your company the most.


How to set X-FRAME-OPTIONS where 3rd Party frame is required to be loaded? We have set the set X-Frame-Options in the header as ALLOW-FROM same origin but there is a requirement to open below page from some 3rd party website. Do you see security issue here?

HTTP::header replace X-Frame-Options "SAMEORIGIN"

From: The X-Frame-Options response header:

SAMEORIGIN
The page can only be displayed in a frame on the same origin as the page itself.

You know this already, but I mention it to let you know that there has been, AFAIK, any vulnerability around this. By doing that, you rather added a layer of security to your web application by preventing clickjacking but this may not be enough:
X-Frame-Options is worth less than you think.


What is the attacker trying to do? (maybe just spam my form) I have a PHP-included form that tells me the URL the customer was visiting when they fill it out. The content of the message was either jibberish or poorly handled by the form. (it looked mostly like this: Ð£Ñ‚Ñ€Ð¾Ð¼ ÑÐ...) The URL that was reported was URL encoded, I had to decode it twice and this is the (anonymized version of the) result:

http://www.example.com/?param1=value1 [PLM=0] GET http:///?param1=value1 [0,9536,24405] -> [N] POST http://www.example.com//?param1=value1 [PLM=0] GET http://www.example.com/?param1=value1 [0,9536,24405] -> [N] POST http://www.example.com/?param1=value1 [0,0,25521]   0

I have tried searching Google, but all I find are others asking basically the same thing going back to 2008. What is this?

It looks like the attacker is trying to get your page to spit out some information, such as the full path of your webserver.

For example, if you start using multibyte data in most functions (in PHP at least) which don't start with mb_* then it will throw an error, something along the lines of:

Function does not accept Mutlibyte characters in "/var/www/site/script.php" on line 132

Which then gives the attacker a lot more information about your server, which you don't want them to know.

You can mitigate this by turning error reporting off, or have your own error capturing mechanism.


How secure is TOTP key on phones? Our company is considering several options in moving to MFA with software OATH TOTP or yubikey OATH OTP. In regards to where the secret is stored, I'm aware that a yubikey or similar hardware device is hardened to physical attack on the stored memory to retrieve the key by force.

Do iPhones or Android device have a secure memory location to store the key, or is it just sitting there on the same partition as other data? We are specifically considering Google Authenticator if there are any specifics you can give regarding its security.

As far as I'm aware (and I don't have any concrete facts about this), iphone/android phones do not have any special storage area for secure data. However, if you use an OAUTH type app as a 2nd factor authentication, then this shouldn't normally be a huge concern (this is not the only means of authentication - you need a password too). Of course it depends on the situation.

Comparing to something like yubikey, I would imagine the following pros/cons or considerations to take into account:

Lost device - People easily notice when their phone is missing. Also they don't stay away from their phones for too long. Not necessarily so with something like yubikey, which you have to use only specifically for authentication (might not be very frequent)
Yubikey probably has better hardware protection and it's a dedicated device
With both, you should have good, quick procedure in place to revoke access. If someone lost their phone/key they should notify and the access blocked for this device as soon as possible
Cost - yubikey will cost extra if you already have a smart phone, but much less for people who don't
deployment - might be trickier to distribute the shared keys to smart phone users rather than buying a bunch of yubikeys and handing them to people
education - depends on your situation, people might be happier with an app on their phone, but some might prefer a separate device.
user-friendliness / mobility - as George Bailey pointed out, it should be easier to use the yubikey as it will automatically type in the key for you. However, if you want to access the app using your mobile phone, then yubikey is probably not usable at all without a USB port.


What is the point of encrypting the home directory? If I have selected a good password and kept it secret, what is the point of encrypting my home directory, as a setup option with some flavors of Linux offer during setup?

Won't the Linux permissions keep unwanted eyes away from my stuff?

The point is to protect against your disk being accessed outside of the OS.

Encryption is useful against attackers who have physical access to your computer. Without it, it would be trivial to read out the content of your home directory, for example by plugging in a live boot USB stick.


Does the endianness used with an encryption algorithm affect its security? I'm implementing the AES block cipher, which reads/writes data in 16 byte blocks. The implementation I'm working with usually read data in the little endian format. But in my platform the endianness I'm using is "network order" big endian. Can I use BE for the encryption algorithm? Does the endianness usually change the way the algorithm works? Does it matter at all? I assumed it does not, since it could have simply been different data that you are reading.

Firstly, let's make sure we get endianness:

// needs a C99 compiler like gcc. Will work with msvc as well.
#include <stdint.h>
#include <stdio.h>

union endian_test
{
    struct
    {
        uint8_t a;
        uint8_t b;
        uint8_t c;
        uint8_t d;
    };
    uint32_t x;
};

int main(int argc, char** argv)
{
    union endian_test e;
    e.x = 0xAABBCCDD;
    printf("%x %x %x %x", e.a, e.b, e.c, e.d);
}

If your system is little endian, you'll get DD CC BB AA as the output and big endian will give you the opposite. All we're doing here is allowing the processor the opportunity to represent an integer in whatever endianness it uses, then using  a little C trick to output the bytes in the order they are represented in memory.

AES works on 128-bit blocks, which is kind of convenient, really, since if you multiply all the field sizes in that union by four, you'd get an AES input block.

So now your question boils down to:

  If I were to reverse the order of the input of my block, would that create a security problem?

Well, that depends on the output. Let's assume something naive, like reversing the order of the input produces a reversed ciphertext, so if the input is AABBCCDD that encrypts to 12345678 and DDCCBBAA encrypts to 78563412.

This is a problem for a certain class of cryptographic vulnerability called CCA2, or a chosen adaptive ciphertext attack. As a result of the fact that the ciphertext is malleable you can then request various decryption operations be performed and whilst you do not know the plaintext, you would be able to deduce something about it. You might like to read a little on ciphertext indistinguishability.

As such, a cryptographic scheme should not be affected by endianness. If it is, or is malleable, it has some security concerns which may need to be addressed (and are, in some implementations, for example, by not providing a decryption oracle).


Can a bluetooth mouse be controlled by another bluetooth mouse? Is it possible to have bluetooth in my machine being controller or (if not interfered) by another bluetooth mouse in nearby computer?

What prevents it? What if they have same pairing code?

I'm not so aware with the bluetooth security. Please can anybody enlighten my curiosity?

The pairing code is not for authentication but merely for identification: two devices shows the same pairing code to let you know you are pairing the correct devices. Not all Bluetooth devices have a screen, so it's also possible to pair devices without the code.

In short, paired communications are encrypted and there's a key exchange, invisible to user and not related to the pairing code. Actually there are four security levels and two modes, explained well by Mark Loveless:

  Security Level 1 supports communication without security at all, and applies to any Bluetooth communication, but think of it as
  applying to unpaired communications.
  Security Level 2 supports AES-CMAC encryption (aka AES-128 via RFC 4493, which is FIPS-compliant) during communications when the devices
  are unpaired.
  Security Level 3 supports encryption and requires pairing.
  Security Level 4 supports all the bells and whistles, and instead of AES-CMAC for encryption, ECDHE (aka Elliptic Curve Diffie-Hellman
  aka P-256, which is also FIPS-compliant) is used instead.

Therefore, what you suggest wouldn't happen by accident. But there have been security holes in bluetooth pairing, too. (Also, it's a good prank to mix all wireless mice at the office, but that's on the physical layer.)


Transmitting private keys between devices? I have an app where a users' device create a public/private key and all communication to this user is done by encrypting against their public key, which is stored on a server and sent to other clients that request it.

Now I'm trying to make it so that this works across multiple devices.

I'm thinking I can just have the new device generate a key pair ("temp key"), encrypt the user's private key against the new device's public key, send it to the new device, and wipe out the "temp key".

Are there any issues with this?  Is there a better solution that doesn't require sending new versions of the public key to everyone that already has it?

One of the primary purposes for this is to be able to say "We (as a company) have absolutely no way of decrypting your communications", so that's a no-go. It needs to be device-to-device, or encrypted with the private key of a device, etc.

Well, in that case, we have established that both devices must be able to communicate with each other, bidirectionally and in real time, in order to complete the transfer.

In that case, there is really no need for elaborate public-key encryption schemes. In fact, they are more likely to introduce problems.

We also know that lots of people aren't really prepared to physically destroy media, have the capability to do so securely, or even understand why it might be important to do so. Instead, most people tend to just delete the file through the OS, leaving all of the data intact on the media for anyone who comes around to look. So M'vy's suggestion of letting the user copy the key onto media they have physical control over, while good in theory, isn't really a great idea in practice.

Instead, use a key exchange algorithm such as Diffie-Hellman Key Exchange (Wikipedia, RFC 2631) to allow the two devices involved to interactively agree on a shared secret. Since we don't want to reinvent the wheel, use whatever TLS or perhaps SSH/SFTP/SCP libraries are available for your target platform to do the heavy lifting. (Generally speaking, never write crypto code yourself. Odds are great that you will get it wrong, introduce subtle bugs, and leave your users' data at risk of exposure. Let someone else make those mistakes.)

Although unrelated to the cryptography itself, make sure this process involves the user authenticating on both devices in some manner.

Once the two devices have agreed on a shared secret consisting of, say, 32 random bytes, use that shared secret as a symmetric encryption key. AES-256 is good enough for most purposes these days, the 256-bit key having the added benefit of providing a safety margin also in a post-quantum cryptography world, and for a given work factor AES is not very computationally intensive.

Once you have transferred the long-term key from one device to the other and verified that the copy is good, just wipe the temporary encryption keys from both devices and possibly wipe the long-term key from the device it was transferred from (this last is likely to be your biggest problem).


Is it safe to mix authentication methods? Is it a good idea to "combine" authentication methods?
Example we can use username/password method to authenticate a user from a server.
What if we used this as a first authentication step to get another token to use for subsequent authentication?
The token could be anything e.g. client's x509 certificate
Example:
Client sends password over SSL. Password is correct and server stores the client certificate send over SSL as trusted. From now on we have client authentication

If entering a valid username+password pair grants access to a "token" which is used to authenticate with regards to another server, then you are mostly propagating the first authentication. It then really depends on the specifics of your setup.

For instance, suppose that you have a certificate-with-private-key file (as a PKCS#12 file, aka "PFX") available on a server. The server will send it to any user who successfully authenticate with a password. The user can then import the certificate into his own machine, and use it to connect to another server which requests a client certificate. For the overall system, you are using password-based authentication, because an attacker just has to guess the password to obtain the certificate, and then be granted access to the second server. However, the attacker could also try to hack into the first server, and will get the certificate, and then will be able to authenticate to the second server.

As the example above illustrate, this is a generic rule: when you link authentication methods as a chain of successive steps, you tend to obtain something which is as weak as the weakest of the links (for once, the "chain analogy" works well).

There are other ways to combine authentication methods, and are known as multi-factor authentication. This is what happens when a server requires several authentication: you may access the data if you type a valid password and you show a valid certificate. Contrary to the example above, the second authentication method is not unlocked by the first one; instead, the server requires both, independently of each other. In the "chain analogy", the authentication are not successive links in a single chain (the attacker just has to break one link), but nested reinforced tubes (the attacker must pierce them all).


What is the different between CMP and SCEP protocol? What is the different between CMPV and SCEP protocol?
Which one is better ?

CMP is a generic protocol which aims at covering most (if not all) network exchanges involving a Certificate Authority; e.g. it includes messages for a CA who wants to announce that it has a new key pair. The protocol is rather complex, and has been around for quite some time (first published version is from 1999).

SCEP is a specialized protocol which has a smaller scope; it concentrates on enrollment and CRL obtention, and is definitely client/server (all messages are requests sent to the CA, and responses from the CA, while CMP allows for CA-driven exchanges). SCEP is not a formal standard; it is not even a RFC but still a draft which is 1. expired, and 2. destined to become an "historic" RFC. SCEP, though, is a big de facto "standard" by being what Cisco hardware tends to do.

The second paragraph of the latest SCEP draft says it all, so let me quote it in extenso:

  This specification defines a protocol, Simple Certificate Enrollment
     Protocol (SCEP), for certificate management and certificate and CRL
     queries in a closed environment.  While widely deployed, this
     protocol omits some certificate management features, e.g. in-band
     certificate revocation transactions, which can significantly enhance
     the security achieved in a PKI.  The IETF protocol suite currently
     includes two certificate management protocols with more comprehensive
     functionality: Certificate Management Protocol (CMP) [RFC4210] and
     Certificate Management over CMS (CMC) [RFC5272].  Environments that
     do not require interoperability with SCEP implementations SHOULD use
     the above-mentioned, PKIX-standard certificate management protocols.
     In light of the functionality gap between this specification and the
     two IETF standards track protocols, this specification is being
     published as Historic.  Even when interoperability with the installed
     base of SCEP implementations is needed, implementers are encouraged
     to support one of these comprehensive standards track certificate
     management protocols in addition to the protocol defined in this
     specification.  This implementation strategy balances near-term
     requirements for interoperability with longer term security goals.

So there you have it: you are encouraged to support and use CMP, and you should envision SCEP mostly for compatibility with legacy deployments, and even then you know that SCEP won't do everything that can be done with CMP.


How to protect a login page redirect I have several web based applications that will redirect unauthenticated users to an ADFS sign-in page. ADFS will subsequently redirect users back to a web application once authenticated with a token.

Since the web application issues a browser redirect - someone who hacks the web application could update the sign-in page URL with a fake sign-in page URL and capture a user's credentials.

What steps could I take to secure the URL?

It sounds like you are worried that your users enter their credentials on another page than your real login page. In your case this is because the web application is hacked, but this is more commonly achieved by phishing attacks, so you may want to look into solutions against phishing.

There are a couple of ways to ensure users only authenticate on the correct domain:

U2F hardware tokens. This is a USB dongle with a cryptographic key on it.
Using a password manager that only autofills credentials when on the correct domain.
Training users to recognize phishing pages, such as checking the URL.

Edit: Using two-factor authentication such as TOTP or SMS tokens don't prevent phishing, since the phishing page can also ask for these. It makes it a little bit harder since the attacker can only log in once with the captured credentials.

U2F is different in this respect, because of crypto. The token creates a signature of the domain name. The captured credentials only work on the phishing page and not on the real login page, so the attacker can't log in.


How can we secure communication of an unchangeable app (Zoom)? During the COVID-19 pandemic, many of us are working from home using meeting apps like Zoom. It's all over the news that Zoom is lacking in its E2E encryption. Let's assume we're using Zoom and can't switch apps.

Considering only the traffic, how can we make these meetings secured/encrypted?

The solution can be hard on 1 group (the company using Zoom) but should be easy on the users (employees of the company). My 1st thought here is to have the company set up a VPN server (in the company or with a 3rd party) and have everyone connect to the VPN before joining a meeting.

You cannot magically secure applications like Zoom without changing the application and the infrastructure it relies on.

The missing end-to-end encryption you want to have fixed is due to the basic architecture of Zoom, in which media streams are processed and mixed together on a central server (which is owned by Zoom). Only this architecture actually allows it to perform well without stressing bandwidth and CPU of endpoints when many users are involved. With E2E instead the requirements for CPU and bandwidth at each end would grow linearly with the number of users and thus would quickly overwhelm clients.

These kind of restrictions apply to any video conferencing solution. This means that you will not get real E2E with any other solution too, at least not if you want conferences which scale to many users without having excessive requirements regarding bandwidth and CPU power. The best you can get is that you control the central mixing and forwarding server yourself and thus don't need to trust a third party.

Even the broken AES ECB mode could not be fixed without changing application and infrastructure since the server actually expects the encryption to be a specific way and if you change it the communication will fail.

Usage of a VPN would not magically solve the problem. The data would still need to be processed on the servers owned by Zoom.


Are HTTPOnly Cookies submitted via XmlHTTPRequest with withCredentials=True? I have a two part question here.

I have a javascript webapp accessing privileged REST endpoints. I would like to protect against CSRF.

Currently, I have a login system built which returns a login cookie containing an encrypted payload (encrypt-then-MAC). I am reasonably sure the cookie contents cannot be tampered with or forged without my knowledge.

I know that using said cookie to protect my endpoints is vulnerable to CSRF, since the cookie is automatically submitted by the browser with any request. I also believe that the Double Submit Cookie pattern is discouraged because it requires setting the cookie HTTPOnly value to False, which elevates the risk of certain attacks.

What I would like to do is set the auth cookie (used for persisting logins over the medium term) to HTTPOnly and Secure. Then, I would like the javascript client to make an XHR GET request to a token endpoint where the cookie can be validated and a short-term token (which contains a handle pointing at information I have stashed in my DB) can be issued directly back to the client, without User Agent redirection. The javascript client would then use the short-term token to authorize calls to my REST endpoints.

My first question is, are there any obvious flaws with this flow? It seems like a reasonable adaptation of the Synchronizer Token Pattern for REST, but I would like to know if there are serious flaws or if there are other best practices around the procedure.

I have considered implementing the OAuth 2.0 Implicit Grant flow but I would like the auth cookie to be present so I can persist logins for a moderate amount of time.

The second question is: will the HTTPOnly cookie be submitted to the token endpoint by the browser with my XHR if I set withCredentials=True? I know HTTPOnly restricts the ability of the javascript to read the cookie, but will the cookie tag along in the request, invisibly to the client?

I have scoured google for the answer, and my google-fu has failed me. All I could find were numerous articles about reading HTTPOnly cookies, but not submitting them.

Thanks in advance for any help or advice!

Yes, they are submitted.  See the W3C spec.

HTTPOnly is intended to mitigate attacks like XSS, but if an attacker has an XSS in your site, they don't need a CSRF.  Have you considered the Encrypted Token Pattern?


Are there any known concrete cases of Cloudbleed attacks? CloudFlare's Cloudbleed seems like a big deal, with thousands of websites compromised.  CNN on February 24, 2017 mentions that it "doesn't appear anyone has exploited it yet." Was CNN right? And a few days later, still no known cases of hacks based on Cloudbleed?

This is an active threat that Google is actively removing leaked information from their search engine.  Although there has been no known exploit from this leaked information, it was still available via search which is hard to track what users/bots reading this data is doing with it.

"The bug may have been active since September 2016, but researchers say it was definitely from February 13 until it was discovered on February 18. Of the leaked data, researchers said they found private messages from dating sites, full messages from chat services, online password data, frames from adult video sites and hotel booking details."

source: http://globalnews.ca/news/3275517/cloudflare-bug-affected-sites-data-leak/


Is the connection between Gmail server and Apple server encrypted? When I send an email from my gmail account to another mail server (apple, microsoft, yahoo...), is the connection encrypted in the path between the two servers?

Let's see:

$ host -t mx gmail.com
gmail.com mail is handled by 5 gmail-smtp-in.l.google.com.
[...]
$ telnet gmail-smtp-in.l.google.com 25
Trying 74.125.142.27...
Connected to gmail-smtp-in.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP ab10si598143icc.38 - gsmtp
ehlo example.com
250-mx.google.com at your service, [24.114.93.99]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250 CHUNKING

See that "250-STARTTLS" ? It tells me that the SMTP server which handles incoming emails for Gmail supports SSL/TLS, and is ready to use it.

If I try again with apple.com server, I also get an announced SSL/TLS support. Therefore, servers on both sides are apparently ready to use TLS and ought to use it when talking to each other.

That's about the best that can be inferred from the outside. You cannot really know whether a specific email will be protected with SSL while in transit between the two servers, or even whether a given email was SSL-protected, because that's not written in the email itself. Similarly, SSL protects against Man-in-the-Middle attacks only as long as the SSL client duly validates the SSL server's certificate, including revocation checks, and nothing tells us whether Apple and/or Google does that properly. Without such protection, SSL is good only against passive attackers.

Also, remember that SSL is only for data in transit, between two SMTP servers: within the SMTP servers themselves, emails are not encrypted, and won't be encrypted in the destination mailbox (an email service could encrypt emails before storage, in a way precluding decryption by the server itself; Lavabit was doing just that until it was shut down recently; but Gmail does not do that, in particular since they quite openly scan email contents in order to make targeted ads for each user).


How does iOS screenshot prevention (ScreenShield by Confide) work under the hood? Official blog: https://blog.getconfide.com/introducing-screenshield-ios-screenshot-prevention-for-confide-and-beyond-692bbae2c31d
More coverage: https://9to5mac.com/2018/01/10/confide-messenger-screenshield-screenshot-prevention/

I could always take DSLR picture of the phone.

I'm curious how does the screenshot prevention work under the hood.

Of course patented, rocket science, secret sauce - surely there are more people are interested in the inner workings of the hack.

It's a security theater. It's a way to sell people products based on the appearance of security, without really adding any security.

I'd be really wary about any security claims made by products that touted such security theater. And yes, according to security researcher Quarkslab, the actual security implementation in Confide seems to be severely lacking to the claims made by the app. The encryption, while using the technologies similar to those used for end to end encryption, is effectively broken and doesn't really provide the same security property as a properly implemented end to end encryption.

With that out of the way:

  how does the screenshot prevention work under the hood.

They're simply checking for events/conditions that happens to coincide with a screenshot. I'm not familiar with the exact implementation on Confide, but detecting screenshot in iOS, while not straightforward, isn't that difficult. According to chpwn:

  How to detect screenshots on iOS (like SnapChat)

  The process is pretty simple, and relies on a quirk of iOS: taking a screenshot cancels all touches on the screen. Because of that, anything that you want to protect will require you to have the user to touch the screen to see. If that works for your purposes, the general solution is to simply intercept the touch cancellation, and quickly remove any sensitive information from the screen.

No, Confide wasn't the first to figure out a way to detect screenshot in iOS. I very highly doubt that their patent is worth anything other than marketing talk.


Loading code securely in the Trusted Execution Environment (ARM) I am reading up on TEE in ARM. I am looking for pointers for the following questions:

How does the TEE load code from the OS securely and guarantee that its not malicious code?

I am guessing the code is signed and the TEE can verify the signature. So that brings up other questions --

Who is loading the code? The loader in the OS or does the TEE have its own loader that allows it to load into the OS' environment?
If the OS loader is loading it how can it be trusted on a rooted device?

I feel like I am missing something here. Can some one point me to the correct literature may be?

In a nutshell, the TEE does have its own bootloader.

The basic idea is that the CPU boots from ROM. This ROM is programmed to load a software image from persistent storage, verify that it is signed by a public key which is stored in the ROM, and transfer the execution to this software image. On an ARM platform with TrustZone, the CPU starts in secure mode, so this first software — the TEE — is executed in secure mode. At some point the TEE switches to non-secure mode and loads another software image: the “rich OS”, i.e. the main OS running on the platform.

The MMU with TrustZone separates a secure world running the TEE and a non-secure world running the rich OS. The non-secure world is less privileged than the secure world, so it cannot access the secure world's memory, in the same way a userland program cannot access the kernel's memory (though the technical details are somewhat different).
There isn't much publicly available documentation about TrustZone and associated technologies, but you can find some on ARM's website.

As real life is never so simple, what happens in practice is a chain where the ROM loads a first bootloader which loads a second bootloader, etc. As long as each stage verifies the signature of the code image of the next stage, only authenticated code can be executed. One of these loads a non-secure, non-authenticated bootloader in the normal world which in turn loads the main operating system (e.g. U-Boot and Linux). This is a secure boot chain, similar to what Microsoft requires for Windows 8. A secure boot chain ensures that only code approved by the hardware manufacturer can run. The idea of the TEE separation is to apply secure boot to the TEE, but not necessarily to the main OS.

Note that what secure boot guarantees is that only authenticated code runs. Malicious code can run if it got signed by the hardware manufacturer for whatever reason.

A Microsoft paper §6.7 gives an overview of an example secure boot chain. A Texas Instruments whitepaper describes a secure boot chain in more detail.


Certificate serial and thumbprint number spacing We have a Microsoft PKI setup at our organization. As per just about all certificates I've ever seen, new certificates issued by our issuing CAs will put the serial number and thumbprint in a HEX format with each byte separated by a space. Recently we had an HSM upgrade, no real changes made to our CAs aside from getting them setup with the HSM. Now all new certificates are being issued with serial numbers and thumbprints, still in HEX (I see letters), but no spaces anymore.

Could this be something the HSM is doing (its a Thales device)?

Is there some place in a Microsoft PKI to change the formatting of these numbers?

Should I even care?

I know how an application uses a certificate serial/thumbprint number is specific to that application. Some require you take out the spaces and some don't. But some applications read it directly from the cert store and I wonder if the atypical format would mess them up. Are there any known issues with having the certificates issued in this format?

At the moment we haven't had any reported issues. Smart card AuthN and our SCCM workstation certs seems to be working just fine with the new certs.

I would assume the serial number and thumbprint are stored in some fixed number of bytes in the file and thus this formatting was purely a result of whatever viewer I'm using. At first I thought this may just be something new with the Windows certificate viewer and Windows 10 1809, but older certificates are still displayed with the spaces, so it doesn't appear to be the viewer that changed and I have to assume it is something with the format of the certificate file.

It is solely certificate viewer, nothing else. Microsoft time by time tweak/change certificate viewer. Prior to Windows 10, hex values were printed in octets separated by a space, now they removed space. Though, public keys and public key parameters are printed in octets with spaces.

The fact that you see spaces for some certs is related to certificate store. Certificate Viewer uses store-attached properties to fill fields in cert viewer. Since property value wasn't changed, it is shows as it was written (when spaces were used). Unlike certificate contents, certificate properties often use formatted strings instead of byte arrays.

I wouldn't care about this.


What alternative standard for ISO 27001 can be used in Australia? I am looking for alternatives, that are less strict and less time consuming, than ISO 27001. Australia is in the Commonwealth, so maybe Cyber Essentials Plus could work, but I do not know if that plays a part in it being recognized by the Australian Government. Any suggestions? Thanks!

Agree, it's kind of a broad question.  If you're looking for general principles, I wouldn't be looking past the ISM - https://www.cyber.gov.au/acsc/view-all-content/ism
If you're looking for specific hardened templates for servers as part of your framework / standards, then maybe CIS is worth a look.  CIS can be quite light touch depending on which level you choose to aspire towards - in theory.  I've found that there's no one-size solution - there's parts of CIS for example, that they'd mark as level 3 - or the highest level of maturity - but which for our business are no-brainers.  In other areas, we struggle to achieve level 1.
Documenting which standards you want to achieve, those standards you're excepting yourself from - that can be a pain.  I've used SAM for compliance, which seems to make it as easy as anything else I've come across.  https://www.samcompliance.co/
Not affiliated in any way, etc...
Good luck!


How can the impact of cold boot attacks be minimized? Short of powering down and maintaining physical security for sufficient time, what are effective strategies for keeping keys from being disclosed by cold-boot attacks, and can anything be done without hardware designed to prevent such attacks?

http://citp.princeton.edu/memory/

One approach is to use highly non-redundant key schedules. For instances, if you can recover any large piece of AES's expanded key schedule in memory you can run the expansion in reverse and recover the original input (which then allows you to generate all of the round keys, even if you were only able to recover the values from a single round, or even portions of different rounds). To some extent, this is intrinsic to AES's design, so it's hard to avoid, but for contrast consider Blowfish's sbox expansion design - it seems quite difficult to recover the master key or the entire sbox if you manage to recover, say, half of the sbox values.

Another approach, one that works with AES, is to simply ensure the key never hits RAM by keeping the entire state in SSE registers or debug registers. This approach is only usable by an OS kernel, but often the kernel is going to be doing the crypto that is most prone to a cold boot attacks, like disk encryption, so this could be a promising approach.


Why is Pastebin still widely used by malicious actors for sensitive data dumps, given that it's public and easily parsable? If you scrape Pastebin for research or even just out of curiosity, it quickly becomes apparent that there is an abundance of compromised data that is uploaded there by unknown malicious actors.

My question is, why is this still done given that there are alternatives that offer better support for covering one's tracks and are a lot less poplar and hence less monitored?

Here are the reasons I know why Pastebin is popular in terms of doxing among Malicious actors :

It can handle large text files
Easy to use
Doesn’t proactively moderate postings
Publishing there doesn’t require registration
Its heritage is rooted in IRC networks

They might be other reasons I'm not aware of. This SE site community should comment/edit this answer or post a better one if it's the case.


Aireplay-ng deauth has no effect I am trying to deauth my laptop which is connected to my home wifi. aireplay-ng has no effect on my laptop.
The commands I used are in order airmon-ng start wlan0 then after getting the mac address of the access point and my laptop i use aireplay-ng -0 1000 -a (mac address of AP) -c (mac address of laptop) wlan0mon this will repeatedly output 01:23:38  Sending 64 directed DeAuth (code 7). STMAC: [84:3A:4B:0B:3C:A8] [ 0| 0 ACKs] however the right zero will go above zero if I do a google search or use the internet in some way. But the left zero will never change from zero. My laptop uses 802.11n and operates on the 5Ghz band, my current theory is that for some reason I cannot deauth devices on the 5Ghz band. What leads me to belive this is that I am able to deauth my ps4 which operates on 2.4Ghz while most other devices in my home operate on 5Ghz.

Go into your router config page and turn off 5ghz. Leave on 2.4ghz. and it should work, if your goal is to take down 2.4ghz.


What is the lifespan of a C2? I've been working on setting up dynamic blacklists, and one question that came up is how long typical entries should be kept on a blacklist. In the interest of equity, there should obviously be some point at which entries are aged out to prevent blocking legitimate traffic to or from an IP that's been reassigned.

I searched around, but couldn't find any specific information about the lifespan of a C2 server (also known as C&C or Command and Control).

Obviously it will vary from case to case, and there's no way to be 100% certain because there are so many unknown factors; but I'm curious if there is any research-based information out there that I just haven't been able to find.

The Anti-Phishing Working Group (APWG) has statistics about how long it takes, after notification (e.g., through MarkMonitor or similar), for a dead-drop site (e.g., malware or botnet C2) to go down. Take it with a grain of salt though, the APWG tracks criminal actors, but nation-state actors have been found to keep their C2 running for 4-5 years, perhaps even longer.

http://docs.apwg.org/solutions.html
http://docs.apwg.org/ipc.html
http://docs.apwg.org/resources.html

Some payloads do not utilize standard, IPv4-based communications (some common examples include Address Routing Protocol covert channels or even SMB named pipes) -- and some payloads have no network communications (not even RF or speaker-based) at all because they are programmed to do damage (or degrade systems, deny access, et al) as logic bombs.


About SSD secure disposal for conforming to iso27001 To be compliant with ISO27001 secure disposal controls with a magnetic HDD we could degauss it before disposal. In SSD scenario, what is the best way for secure disposal which is compliant to ISO27001 standard?

ISO 27001 does not mandate a specific way SSDs should be destroyed, it just requires that the process is consistently applied after it has been approved by the business risk owners.

That being said, depending on the size of your business and the volume of devices you might consider the following:

Make use of a secure disposal service
Use a SSD shredder - Costly but quick and efficient and you might be able to hire a device depending on where you are in the world
Depending on your risk profile, consult the manufacturers of the SSD
for secure software erase techniques


Where can I find the specs for the X.509 certificate used in client-authenticated TLS handshake? The TLS specs define how the handshake between client and server must be performed when the client wants to use a certificate to authenticate itself. There is a lot of documentation onlin that assumes that the username is put in the CN field of the x.509 certificate, but no one of the documents I found gave a reference to the specs that mandate putting the username into the CN.

Is putting the username in the CN mandated by some RFC or standard? If yes, could you please point me to that document?

As I understand it, validation of the client side certificate is implementation specific. Generally, it boils down to asserting that the client certificate is in a trusted PKI from the server's point of view. It may decide extra validation schemes as defined by the certificate policy.


How to generate the most secure private key? I need to generate the most secure private key.

Usually I use a command:

openssl genrsa -des3 -out mykey.key 2048

Is triple DES secure enough?

Is 2048 large enough?

Are there any other ways to make the private key stronger?

Using AES and 4096 bit RSA would certainly help. At least openssl uses 3 key triple DES but that means both the triple DES and the RSA private key are stuck at a security strength of 112 bits. See https://keylength.com for information on key strengths. 112 bit is just enough but a bit too close for comfort; I'd sleep better with 128 bit security.

openssl genrsa -aes128 -out mykey.key 4096

Note that 3DES is used in CBC mode, offering confidentiality only. That means that an adversary could change the value of your private key without you knowing it. If that's OK depends on your situation - an attacker may not be able to reach your private key or maybe you're just interested in keeping the private key / messages confidential.

You might consider storing the keys in a PKCS#12 container instead, which offers just a bit more security. You'd need a certificate with the public key to do so though. Unfortunately the genrsa command doesn't seem to allow any authenticated mode of encryption such as AES-GCM. Possibly you could place a signature over the generated private key (in case you have a different private key used for code signing around). Or you could store a hash over the private key file somewhere safe and compare before using it.

The weakest point of password encryption is always the password. Older command line openssl, before 1.0.0, uses a pretty weak password based key derivation function (with a single iteration count). Newer openssl fortunately uses PBKDF2 with a - still low but better - iteration count of 2048 (see the comment of Dave below). You may increase this count using -iter N command line option. More importantly, you can avoid issues by generating a very strong password, storing the strong password in a password manager of some sorts. Chances are that you won't be able to remember a really strong password (or the password may simply be not as strong as you assume).

Above advice can be used to generate a more secure private key; there is no such thing as a most secure private key. If there would be such a thing, then I would doubt that you could use (software only) OpenSSL command line to generate it.


Compiler Parameters to isolate a C++ program Is there any set of compiler parameters that can be used to prevent a C++ program from having any access to most system functions, leaving it with access to read/write to stdin/stdout, but otherwise unable to harm the system.

This strikes me as being useful for systems such as a homework submission server or an online "tryit" server.

Providing such restrictions are usually not considered the task of a compiler and it would be very hard to do anyway. Even if only a restricted set of libraries would be available for linking it is still possible to directly call into syscalls, i.e. no library needed.

For the use case you envision (homework submission) one should instead execute the generated program inside some restricted environment, i.e. sandboxing it within a virtual machine, containers or similar. In the simplest case you might run the code as a different and restricted user but then you should be really sure that your system is not exploitable by a low privileged user.

But there is another interesting use case where the developer itself wants to restrict the abilities of the program in order to reduce the impact of possible bugs in the program. Here technologies like pledge, seccomp or similar allow the program to explicitly give up the ability to do specific system calls (which can never be gained again) so that a bug in the program cannot be used to cause much harm.

Using the last idea where the program restricts itself could be also used in your use case to enable such restrictions before main gets called. One might do this to have a different compiler runtime or have other ways to execute code before main. Personally I would have much less trust in such a solution since much more can go wrong compared to running inside a real sandbox.

See also this questions at Unix & Linux where the OP tries to solve a similar problem and where a solution using seccomp is described in detail.


Best way to keep private PGP keys? What is the most secure way to store my private PGP keys?

You could look at one of many Key Management standards like the following NIST guideline but ultimately the level of security is probably dictated by the value of what is being protected.

http://csrc.nist.gov/publications/nistpubs/800-57/sp800-57_part1_rev3_general.pdf

Given I have no context as to what these keys are used for, or their value, or frequency of use it's hard to make recommendations.

One thing I do recommend is that you keep them encrypted and ideally not directly on a computer connected to the Internet unless it's something you will use constantly. I also recommend having one local encrypted backup (same building) and at least one off-site encrypted backup of these keys.

You may also find that the use of several keys (low security, medium security, and high-security) may be helpful because you may find that you are ok with having your low-security key on one computer whereas you may decide that your high-security key will never be used on a computer connected to the Internet and that you keep it on a USB flash drive locked in a safe or something.

Again, the data being protected needs to be driving your decisions. Once you determine that data's long-term value then choose the appropriate way to protect it.


Platform Identification In Bug Bounty What is the importance of identifying our target's web platform?

I have recently watched the video 'DEF CON 23 - Jason Haddix - How to Shot Web: Web and mobile hacking in 2015' from youtube and he highlighted the importance of platform identification using Chrome extensions such as Wapplyzer, Builtwith and etc. How will this help me in detecting vulnerability in my target's web?

If you do not know what you are attacking, you have no choice but try out all the tools you have in your arsenal.
If you know more about your target, your attacks can be better targeted and tailored to whatever you want to achive.

For example, if you only know that there is some database behind that login form, you have to try all the possible SQLi's - but if you know the exact version of the webapp, database etc you can skip everything that is not fitting on that.

In addition, you might learn that there is a trivial to exploit vulnerability available and can go straight to the core, without having to probe around.


How to decrypt file that was attacked by ransomware? there are a ransomware attacking on of my computer and most of the file has been renamed to something like

  id-2832SGndfDcbv.supportfriend@india.com.xtbl

The file isn't corrupted as the file still has the exact size, the attack was on yesterday 3AM(GMT+6) and asking for ransom via email. As the file still being same size, I tried rename the extension but somehow doesn't work.

After Google-ing for sometime, it was attacked by so-called "CrySiS" ransomware, I was trying to find some solution and decryptor online but sadly couldn't find any of it. Plus, I'm not going to take risk of download and using some unpopular third party decryptor which may make my current situation worse.

these file being attacked contain most of personal information. I wonder is there any solution or way to decrypt the file that being attacked?

It depends greatly on the malware that attacked you.  Like any software, some malware is written better than others.  Some use poor encryption that can be broken.  Some can be fooled into decrypting your files just by tricking them into believing their payment server was paid (the "Jigsaw" ransomware is stupid like this.)  But others are using high security approaches that can't be so easily thwarted.

The best approach is always to recover the lost files from a backup (on an uninfected computer, of course!), and wipe and rebuild the infected box.  If that's not possible, you may have to decide whether or not to pay the ransom, and quickly.  Ransomware typically comes with some kind of evil countdown clock that will permanently delete more and more files as time elapses and the payment deadline approaches; they may also delete a large number of files in retaliation if they detect a reboot or if the ransomware is killed, restarted, or tampered with.

If recovery isn't possible, your next best bet is to use a different computer to find out what kind of ransomware you were infected with, and google for specific advice for recovering your data.  If self-recovery isn't in your comfort zone and the encrypted data is extremely valuable, consider calling a computer security firm.

Remember, once you're infected don't shut the attacked box off, don't reboot it, just work quickly to preserve what you can.  If you do need to power it down, make sure you physically kill power instantly.  You should remove the battery or unplug the power cord, instead of pressing the power button and waiting for it to shut down, or using the 'Shutdown' menu option.  Use the powered down time as an opportunity to make a backup of the disk image before you restart it. This will preserve additional files from being deleted by the malware when it comes back up.


Tracking down rogue wireless device on network I have an unknown device that is connecting to my wifi router, and can't figure out what it is to save my life. I've never seen it before and haven't bought any new devices lately, it seems to have appeared out of the blue.

From my router admin page I can see the device reports as:

name: BRWD44B5EFDBFA0
MAC: D4-4B-5E-FD-BF-A0

I have looked up this MAC address and it reports the maker as:

TAIYO YUDEN CO., LTD.

Ok fine, you can check out their website and see they make wifi/bluetooth chips that are used in various devices. Not very informative.

I also tried using nmap to scan the device, I have never used nmap before but tried a command I found in a similar answer:

nmap -v -Pn -p 1-65535 192.168.0.4

Starting Nmap 7.12 ( https://nmap.org ) at 2016-05-31 20:14 MDT
Initiating Parallel DNS resolution of 1 host. at 20:14
Completed Parallel DNS resolution of 1 host. at 20:14, 0.02s elapsed
Initiating Connect Scan at 20:14
Scanning 192.168.0.4 [65535 ports]
Completed Connect Scan at 20:14, 1.85s elapsed (65535 total ports)
Nmap scan report for 192.168.0.4
Host is up (0.000017s latency).
All 65535 scanned ports on 192.168.0.4 are filtered

Read data files from: /usr/local/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 1.93 seconds

Which seems to indicate all ports are unreachable, so no luck determining what services or OS is running on this device.

In the statistics section of my router I can see this device is still connected and regularly transmitting a packet or two every second, but still have no idea what it is or what it's sending.

I know I can block this device by changing my WPA2 password or by filtering this MAC address, but I really need to know what it is first. What else can I do to find out what this device is or where it is physically located?

Rass, yes I remembered 4 years ago my network guy reported the very same problem. The accounts department went and bought a Brother wireless printer & connected it via wifi. turns out it's MAC points to a Japanese NIC maker of Brother & Toshiba printers. Man check your bomboclate print fleet first.


Why do we even use passwords / passphrases next to biometrics? In the last couple of days there were a lot of talking about passwords and passphrases, not only here, but on several blogs and forums I follow (especially after XKCD #936 saw the light of this world). I heard quite a few pros and cos of both of them and this got me thinking.

Why do we use password and passphrase at all instead of biometrics? I know biometrics are not the holy grail of authentication and/or identification, but (And the most popular password is... from ZDNET) at least I can be pretty sure that majority of users won't have the very same and easy to guess biometrics.
Also I can't forget my finger or iris (while I can forget password / passphrase). With the era of cloud coming, the major strength of passphrases (length) might easly be ephemeral.

Like I said, I know biometrics are not perfect, but if we know that passwords / passphrases are the Achilles' heel of almost every system, why are biometrics underused?
According to Tylerl (Biometric authentication in the real world from this site, second answer), biometrics is used even less than it used to be.
I mean, even if fingerprints are easily forged, it's still better than having many users with password 123456 or qwertz, at least from my point of view (feel free to prove me wrong).

So, in short, what are the biggest problems / obstacles which are stalling widespread adoption of biometrics?

EDIT

I won't comment each reply, but put my thoughts here. Also I would like to clarify some things.

Problem of normalization

I don't know how is it in USA, but in UK law states that you need at least 5 (or 7, I'm not sure) referent points used in matching. This means that even if you don't have perfect scan, system can still do matching against vector (which is representing fingerprint) stored in DB. System will just use different referent points.
If you are using face as biometric characteristic EBGM can recognized person even if face is shifted by ~45°.

Problem of not-changeable (characteristics)

Well, you can actually change characteristics - it's called cancelable biometric. It's working similar as salting. The beauty of cancelable biometric is that you can apply transformation daily is needed (reseting password every day could result in a lot of complains).

Anyway, I feel like the most of you are only thinking about fingerprint and face recognition, while in fact there are much more characteristics which system can use for
authentication. In bracket I'll mark the chances of fraudery - H for high, M for medium and L for low.

iris (L)
termogram (L)
DNA (L)
smell (L - ask dogs if you don't believe me :] )
retina (L)
veins [hand] (L)
ear (M)
walk (M)
fingerprint (M)
face (M)
signature (H)
palm (M)
voice (H)
typing (M)

Ok, let say biometric hardware is expensive and for simple password you have everything you need - your keyboard. Well, why there aren't systems who are using dynamic of typing to harden the password. Unfortunately, I can't link any papers as they are written in Croatian (and to be honest, I'm not sure do I even have them on this disk), however few years ago two students tested authentication based on dynamic of typing. They made simple dummy application with logon screen. They uploaded application on one forum and post the master password. At the end of this test there were 2000 unique tries to log with correct password into the application. All failed.
I know this scenario is almost impossible on the webpages, but locally, this biometric characteristic without need of any additional hardware could turn 123456 password into fairly strong one.

P.S. Don't get me wrong, I'm not biometric fanboy, just would like to point out some things. There are pretty nice explanations like - cost, type 2 error, user experience,...

Passwords and biometrics have distinct characteristics.

Passwords are secret data. Data is abstract: it flows quite freely across networks. Cryptography defines many algorithms which can use secret data to realize various security properties such as confidentiality and authentication. The shortcomings of passwords are due to the fact that they are meant to be memorized by human beings (otherwise we would just call them "keys") and this severely limits their entropy.

Biometrics are measures of the body (in a wide sense) of a human user. Being measures, they are a bit fuzzy: you cannot take a retinal scan and convert it into a sequence of bits, such that you would get the exact same sequence of bits every time. Also, biometrics are not necessarily confidential: e.g. you show your face to the wide World every time you step out of your home, and many face recognition systems can be fooled by holding a printed photo of the user's face.

Biometrics are good at linking the physical body of a user to the computer world, and may be used for authentication on the basis that altering the physical body is hard (although many surgeons make a living out of it). However, this makes sense only locally.

There is a good illustration in a James Bond movie (one with Pierce Brosnan; I don't remember which exactly): at some point, James is faced with a closed door with a fingerprint reader. James is also equipped with a nifty smartphone which includes a scanner; so he scans the reader, to get a copy of the fingerprint of the last person who used it, and then he just puts his phone screen in front of the reader; and lo! the door opens. This is a James Bond movie so it is not utterly realistic, but the main idea is right: a fingerprint reader is good only insofar as "something" makes sure that it really reads a genuine finger attached to its formal owner.

Good fingerprint readers verify the authenticity of the finger through various means, such as measuring temperature and blood pressure (to make sure that the finger is attached to a mammal who is also alive and not too stressed out); another option being to equip the reader with an armed guard, who checks the whole is-a-human thing (the guard may even double as an extra face recognition device). All of this is necessarily local: there must be an inherently immune to attacks system on the premises.

Now try to imagine how you could do fingerprint authentication remotely. The attacker has his own machine and the reader under his hand. The server must now believe that when it receives a pretty fingerprint scan, it really comes from a real reader, which has scanned the finger just now: the attacker could dispense with the reader altogether and just send a synthetic scan obtained from a fingerprint he collected on the target's dustbin the week before. To resist that, there must be a tamper-resistant reader, which also embeds a cryptographic key so that the reader can prove to the server that:

it is a real reader;
the scan it sent was performed at the current date;
whatever data will come along with the scan is bound to it (e.g. the whole communication is through TLS and the reader has verified the server certificate).

If you want to use the typing pattern, the problem is even more apparent: the measuring software must run on the attacker's machine and, as such, cannot be really trustworthy. It becomes a problem of defeating reverse engineering. It might deter some low-tech attackers, but it is hard to know how much security it would bring you. Security which cannot be quantified is almost as bad as no security at all (it can even be worse if it gives a false sense of security).

Local contexts where there is an available honest systems are thus the contexts where biometrics work well as authentication devices. But local contexts are also those where passwords are fine: if there is an honest verifying system, then that system can enforce strict delays; smartcards with PINs are of that kind: the card locks out after three wrong PINs in a row. This allows the safe use of passwords with low entropy (a 4-digit PIN has about 13 bits of entropy...).

Summary: biometrics can bring good user authentication only in situations where passwords already provide adequate security. So there is little economic incentive to deploy biometric devices, especially in a Web context, since this would require expensive devices (nothing purely software; it needs tamper-resistant hardware).

Biometrics are still good at other things, e.g. making the users aware of some heavy security going on. People who have to get their retina scanned to enter a building are more likely to be a bit less careless with, e.g., leaving open windows.


Magic hash attack in JavaScript In PHP a magic hash attack happens when loose type comparisons cause completely different values to be evaluated as equal, causing a password "match" without actually knowing the password. Here is an example:
<?php
if (hash('md5','240610708',false) == '0') {
  print "'0' matched " . hash('md5','240610708',false);
}

If you execute this you will see:
'0' matched 0e462097431906509019562988736854

Would this be possible in a JavaScript application that's using using the loose equality == operator to compare two hashes?
JavaScript is a weakly typed language, so I would naturally assume the type coercion can be taken advantage of and therefore present various security holes.

Being loosely typed with a crazy == operator, JavaScript is vulnerable to type juggling. But it is not  as vulnerable as PHP.
Here are a few things that are equal in PHP, but not in JavaScript:

'0e111' == '0e222' Even though both are strings, PHP will treat them as numbers. JavaScript needs one of the operands to be a number before it tries to coerse anything into a number.
'0eaaa' == 0 PHP will interpret anything beginning with a number as a number, while JavaScript will not. Note that even PHP needs the other operand to be a number in this case.

However, this will be equal in both PHP and Javascript:

'0e111' == 0 One operand is a string containing only digits after the 0e (very unlikely that will happend at random), and the other must be an actual number (not just a string looking like a number).

This makes it harder to find type juggling vulnerabilities with hashes in JavaScript. That doesn't mean they don't exist, though. Use ===.


Is there any security issue when removing a LUKS partition without luksClose? An external hard disk drive is connected to a Debian system via USB.
The disk is encrypted using cryptsetup LUKS and is properly opened
and mounted using luksOpen.

Now, if somebody just unplugs the drive an tries to read the data,
does she have any advantage from the fact that the device has not been
properly unmounted and closed with luksClose?

No.

But your RAM or swap could perhaps be used to pilfer the key. In the RAM case this requires special hardware IIRC.

There are those complex sidechannel attacks which are no longer so theoretical, but not common. For evilmaid, there's anti-evilmaid, or just control boot from removable media with a password.

I've had some love by hibernating systems, doing a few things, and popping them back on. This is also prevented with a boot password.


Extending on-premise security to a virtual machine used in Home Office environment The environment

Our company has a reasonable (from the point of view of a regular employee) security policy consisting of, among other things:

Sophos suite covering both local antivirus solution and Internet access screening (corporate proxy with a MITM proxy for https),
Windows 10 with disk encryption,
automatic log out (lock) timer per domain policy,
central control of installed software (both installations and compliance checks of user-installed sowftware),
no single-sign-on, very few if any mandatory programs continuously running,
users can be local admins (devs and such) but can't override domain policies (like the automatic lock after preset time),
VPN access for field workers.

In place are legal measures as well, like non-disclosure agreements signed by every employee.

Users have full physical access to their machines (from plugging USBs to opening the box and fiddling with stuff, though usually nobody does the latter).

The question

Given the situation described above, is it reasonable to assume that giving an employee a Virtual Appliance for a common virtualization environment (VMWare, VirtualBox, KVM...) is no different than giving them a laptop with same configuration to work remotely? The VM would be run either on a throw-away computer or the employee's private computer*. Am I missing something important here which would disqualify the VM run on arbitrary hardware?

One thing I can think of is poorly secured VM host on which a malware program (for example a keylogger) can sit between the user input and the VM, which would not be the case for a better secured physical computer (but admittedly would work with a remote desktop from said poorly secured computer). I'm interested in possible problems like this one.

There are considerable differences once you begin to look at support, help desk, patching, upgrades, lost hardware, incompatibilities with security settings or applications on the personal hardware etc...

I'd suggest if they don't offer this the best you can do is ask if they will consider it. They may implement a solution that works for you, if it makes sense for them to do so.


Does returning a 401 error from an API leak information? I'm developing an API for an application I'm working on and I've come across an interesting question:

Imagine an API endpoint like this:

GET /customers/123456

which returns a single customer object. Now, in our organization, customers can belong to sales organizations. Each API user is associated with an organization and I want to restrict a user's access to customers associated with their organization.

So, given a user who belongs to organization ABC and customer 123456 who belongs to organization XYZ, what should my API return when this user attempts to get that customer?

404 Not Found - if a user queries a non-existent customer, it returns a 404 since no resource was found at that URL.
401 Unauthorized - if you query a resource to which you do not have access, you should get an "unauthorized" response.

It seems to me that if the API returns 401 Unauthorized or existing customers from other organizations and 404 Not Found for non-existent customers, my API is leaking information. For example, a user from organization ABC could query the API and determine which user IDs exist and which don't.

Additional notes:

Customer IDs are generated sequentially and there are no gaps, so the type of information that would be leaking would be:

what will the next customer ID be?
how many customers were created in a time period?

The sales organizations are generally restricted to particular geographic areas and are not usually in direct competition. But some territories do overlap and there are rules in effect to govern "poaching" each other's customers. So, all in all, it's a mildly competitive environment where we don't really want sales organizations to know about each other's clients.

First off, if these user IDs are actually sensitive information as you say, do not put them directly in the URL. Why not just make opaque URLs instead and solve the problem before it even occurs? If you remove the relationship between the URL and the user(s), it will be next to impossible to deduce any relationships from a returned status code.

For example, instead of:

GET somepath/customers/123456

just implement some sort of small hashing system with a 2-way look up table and you can use a different URL such as:

GET somepath/DC884298C70C41798ABE9052DC69CAEE

Sure, this takes a bit more work, but if you are legitimately concerned about the issue, it's really a trivial implementation.

Back to your actual question, the W3C states that if someone attempts to access a resource, but is not properly authenticated, then it is OK to return 404, rather than 403 (Forbidden):

  If the server does not wish to make this information available to the
  client, the status code 404 (Not Found) can be used instead.

By the same logic, I don't see why it wouldn't be fine to return 404 instead of 401 if the client is authenticated but not authorized. But keep in mind that, with this approach, someone who is actually trying to work with your API may be confused and just assume that the resource doesn't exist and not realize that they just don't have sufficient authorization. This is ultimately up to you to decide. I will say that, in my experience, I have seen both methods implemented before. If you do choose to return a 404, make sure that you specify this somewhere in your API docs so that other developers are aware.

Source: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4


Encrypted container on top of a copy-on-write filesystem The way I understand it, when you write to a copy-on-write filesystem, data never gets overwritten in place, instead new data is written to a new location, and the old data will only be overwritten when the filesystem runs out of space.

If I put an encrypted container (luks for example) on top of an zfs filesystem, and then keep writing different data to the encrypted container, then I would end up with lots of different versions of the state of the encrypted container on disk.

Does this weaken the encryption? If so, how much of a threat is this in practice, does it make it easy to break the encryption?

Assuming your encrypted container is using a secure algorithm in a secure manner, this won't let the attacker break the encryption.  In the worst-case scenario (writing files provided by the attacker), this is giving them information for performing a chosen-plaintext attack.  Any good encryption algorithm (eg. AES or Twofish) is strongly resistant to this sort of attack, so much so that you could spend millions of years writing to the disk without giving the attacker enough information to perform the attack.

The big risk is not to the encryption itself, but that it provides a side channel for gathering information about the data stored in the container.  For example, if all of the discarded blocks belong to one part of the disk, it's a good sign that a hidden volume is in use.


With the existance of CORS, what further purpose does same origin policy serve? I've been using CORS for a while and I think I understand it. But as far as I can tell, because the allow-origin header is provided by the server being called, which an attacker can control as they see fit, same origin policy cannot prevent an injected script from calling an attackers server.

Furthermore, by using my own server as a proxy, and spoofing headers, I can essentially make any HTTP call to any server in the world, regardless of their CORS settings.

Assuming an attacker can do whatever they want with their server, does this mean that same origin policy is dead?

I think you are misunderstanding where and why CORS is used. It is not intended to prevent a script from calling out to an untrusted server (with an Access-Control-Allow-Origin: * header, for example), since that is often a valid use case. The default, restrictive policy doesn't even restrict whether data can be sent; even without that header from the server, a client can send arbitrary data that will be received by the server.

Here's an example where the default policy is helpful:

Say you have an intranet website that provides sensitive company information. An attacker knows the website exists, and crafts some cross-origin AJAX requests in JavaScript to exfiltrate data from the website if any company users browse to the attacker-controlled website. When this happens, the JavaScript will reach out to the intranet server, but will refuse to return any data due to no Access-Control-Allow-Origin header.

Another scenario is where an attacker knows you are logged into a social media website, and wants to read your private chats. The attacker writes some JavaScript to pull messages from whatever user is logged in, using cross-origin requests when you visit their website. This is also prevented without the aforementioned header.

In either scenario, the attacker can't read any cross origin data since the target websites do not bear the necessary header to relax the policy. The attacker does not control these headers, as they do not have access to the systems in question.

  Furthermore, by using my own server as a proxy, and spoofing headers,
  I can essentially make any HTTP call to any server in the world,
  regardless of their CORS settings

Maybe, but what does this gain you? You can't accomplish either of the two scenarios I provided above, especially since credentials won't be sent to the wrong domain.


Compression and Encryption against security issues I'm having a hard time knowing whether the following setup is vulnerable to CRIME/BREACH type attacks (which target HTTPS).
I am running a Wireguard VPN that tunnels VXLAN protocol, using ChachaPoly20 encryption.
I would like to add CPU cheap compression (LZ4) on the VXLAN frames (RFC3173 likewise).
Would the fact that I add LZ4 on my VXLAN frames make the encrypted VPN tunnel vulnerable to a potential attacker?
Side question: Since CRIME and BREACH target HTTPS specifically, are there any more generic versions of those attacks?

To exploit the compression, as in CRIME/BREACH, the attacker must perform a chosen-plaintext attack. In other terms, this means that the attacker must already have an exploit on your computer:

Either a RCE, in which case your VPN, encrypted or not, will not help you as you are already pwned;
or a CSRF or similar, which is fairly uncommon on classical desktop software.

Avoiding compressing data before encryption is a "defense in depth" protection, in the sense that a prior exploit must be used. Compression exploitation can only be used to improve on an attack, on some very specific scenarios.
Also, as mentioned in this answer by MechMK1, you will most likely not gain much by compressing at the VPN level.
In conclusion, do as you wish, the impact in performance and security will most likely be minimal either way. If, however in your particular situation you know that you will gain a lot by adding compression, or that a CSRF is likely and unavoidable, then you now know what to choose between compression and security.


Is maintaining multiple keypairs for different services worth the effort? Assume a machine with id_rsa and id_rsa.pub.

The machine has to authenticate to multiple services via keypair.

The first service for example is password-less ssh access to another machine by copying the public key to the other server's authorized_keys file.

Now the same machine should authenticate via ssh keys to a second service, like github for example.

Is there any security benefit to create another keypair only for github, and adopting the mentality of a a different keypair per service, or can I just use the same public key everywhere? I guess the question boils down to how much potential damage am I exposing myself to if I use the same keypair for multiple services?

In the latter, if one private key gets compromised it would damage that service alone. But in the former, if that private key gets compromised, I would be exposed to damage from a lot more services at once. So it just seems to me that multiple keypairs is the way to go, but does the administrative overhead justify the added security?

Think of key pairs as an administrative range of systems and data that access is granted too.

If an attacker gets access to one what does he/she gain access to across everywhere this key pair is used?

If you used different key pairs for different services how would this limit the attacker's access?

Finally as an example, if you used one key-pair to move public images for a handful of web servers to and from a public image providing service (let's call it GifHub) and another key-pair for moving credit card data to a separate set of systems hosted by your credit card processor (ignore PCI for a moment). Can you think of any reason why you wouldn't want to give your public image providing service access to your credit card processing database? In this hopefully fictitious example, you might notice that one key-pair is protecting data that is public whereas the other key-pair is protecting credit cards. The reason you don't want to use the same key-pair for both is if someone attacks your image moving application you don't want them to be able to have access your credit-card database. Hence having multiple key-pairs provides a level of defense in depth which is something you want. So using separate key pairs for each service is generally wise.

Note: There are a LOT of other reasons you would want to use different key pairs for different applications or even data moving in different directions. It would take too long to cover all the issues here but yes there is a security benefit and it comes in the form of defense in depth.


How to optimize the diffie hellman key exchange algorithm I am making a chat feature in my app where I want to encrypt it E2EE, but the problem is when I start to calculate the public key (public key = g^private % n) it takes a decade to get it done. I need to know how to simplify it for the CPU.

DON'T ROLL YOUR OWN CRYPTO

Writing a crypto implementation is hard: not only does it have to "work" in the sense that the math is right, you're properly handling big ints, etc; but it has to be "secure" in the sense that you have no buffer overflows, you handle all error conditions correctly, your code is completely timing invariant, etc.

Put it this way: if I was a dev manager and we needed to write and harden a production-quality Diffie-Hellman implementation, I would want 1 - 3 PhD level crypto engineers and I would give them ~ 1 month to write and harden the implementation. If that doesn't describe your team, then I would suggest using a cryptographic library instead.

For what you're describing, I would use the Signal Protocol (there are libsignal libraries in most major programming languages). If you really want to use DH directly, then I would use the crypto package for your language, or OpenSSL. In addition to security, you'll get the side-benefit that these implementations will be much faster than yours since they will use advanced mathematical and assembly language tricks to make the exponentiation and modular reductions more efficient.

DON'T ROLL YOUR OWN CRYPTO