Would MITM be able to manipulate the X-Frame-Option I was wondering if the following scenario was realistically achievable.

We have a Network with a Computer that is used by Bob. He is security conscious person and uses a password manager. His computer is connected to the internet through a router which Bob got from his ISP. The ISP and the manufacturer of the router have not deployed updates for critical vulnerabilities that his router has.
Then there is Trudy who really wants to know Bobs passwords. She gets full access to his router through an exploit. There are a couple websites she is interested in so she manipulates the DNS entries to point to a webserver under her control. As Trudy has a lot of time, it is assumed that the DNS cache of Bob's computer will eventually be updated to contain the manipulated entries.

Bob happens to connect to a website Trudy is interested in. He thinks he is establishing a connection with https://www.safewebsite.com, but in fact he connecting to Trudy's webserver. The webserver downgrades the connection to plain http, just to establish the connection. Then the webserver performs a redirect to the actual URL of itself, e.g. https://safewebsite.evil.com for which Trudy has a valid (simple) SSL Certificate. Assuming Bob does not look too closely he doesn't see the difference in the address bar.

Alternatively Trudy gets Bob to visit her webserver in a way that does't trigger an invalid certificate exception.

What Trudy needs to do, in order to extract Bobs password, is to embed the valid website Bob wanted to visit. This also happens to be less work for Trudy as she doesn't want to code a phishing website, but wants to trick Bob's password manager. When Bob would visit Trudy's malicious website the password manager enters his credentials into the embedded website, because he believes that this is a valid connection. Then a script from Trudy's website grabs the content of the password field and username, sending both to the webserver.

Now Trudy does have a thing she is struggling with, a lot of websites have the x-frame-option set to deny. This foils Trudy's attempt in many cases. She has the idea to let the Router sniff for packets containing the x-frame-option. It would then be modified or removed. So if Bob visits Trudy's malicious website, he requests the embedded real website and the router performs an active MITM. This means the router connects to https://www.safewebsite.com and only hands Bob the http version. Bob would still see the https://safewebsite.evil.com, not indicating a visual change compared to the previous version of the attack. The question is if the router would be able to remove or modify the x-frame-option in a way that doesn't impact Bob's browsing experience.

Hopefully the idea is clear. If you spot something that is unrealistic, please leave a comment. Maybe you have an even simpler idea how to achieve this.

This is a attack scenario against a specific password manager (which will not be named here) that I would like to use in a presentation for a course at university, but only if it is plausible.

Update
Even though I knew and have thought this through several times, the written idea above has a crucial flaw, www.safewebsite.com would need to be loaded as https  otherwise the password manager would not fill in the data. I will work on the scenario and post an updated version.

Update 2
It seems that the password manager does have a security issue filling credentials into iframes. The scenario is flawed though and the answers given are correct for the original question. If the new scenario does work, I will first contact the developers and later release more information about the problem.

Over HTTP a MITM could manipulate any request header.

Over HTTPS a MITM would NOT be able to do that without having a valid certificate or generating a certificate warning in Bob's browser.

www.safewebsite.com could mitigate some parts of this attack by using HSTS which would tell Bob's browser to only visit over SSL after the initial connection.  The site could also refuse POST requests over HTTP (but that wouldn't stop Bob's browser from sending them).


why a client authentication is not commonly performed in the TLS protocol? Is there any reason for this other than key/certificate management on the client-side?

What is authentication ? That's making sure that whoever is at the other end of the tunnel is who you believe. It really depends on the kind of identity that you want to use.

For most Web sites, the interesting notion is continuity. They do not really care who is connected; indeed, the point of a Web site is to be readable by everybody. The kind of authenticity that a Web site wishes to achieve is to make sure that two successive requests are really from the same client (whoever that client may be). This is because the Web site experience is that of a logical succession of pages, driven by the user's actions (the links on which he clicks), and meddling with that movie-like framework is what the attacker is after. The user and the Web site designers think in terms of sessions and the attacker wants to hijack the session.

This authenticity is achieved by several mechanisms:

Successive HTTP requests from the same client go through the same connection (with the "keep-alive" feature).
SSL offers a session resumption mechanism, which reuses the negotiated shared key (that's the "abbreviated handshake" described in section 7.3 of the SSL/TLS standard).
The HTTP request can include a cookie which the server chooses; typically, a random, user-specific value is sent as a cookie to the user, and, upon seeing it coming back in subsequent requests, the server is convinced that the requests come from the same user.

The cookie is sufficient to ensure continuity.

What extra value would client certificates add ? Well, not much. Certificates are a way to distribute key/name bindings. There are mostly three scenarios where client certificates (in a Web context) are relevant:

The Web server needs an extended notion of user identity, which is defined by someone else. For instance, imagine a governmental service that can be accessed by citizens, but only after proper authentication, e.g. an online election system. What makes the citizen, with his definite name and birth date, is managed by the State at large, but not the same part of it than the one running the service. Client certificates are then a way to transport the authentication from the PKI which issued the certificate to the citizen, to the online election system which is not at all entitled to say who is named what, but must nonetheless keep clear records of who connects.
The system designer has little trust in the robustness of existing Web browsers. If a user's browser is hijacked, then the secret cookie can be stolen and the user has basically lost, forever. On the other hand, if the user has a smart card, and that smart card stores a private key (which is used in combination with a client certificate), then a complete browser hijacking is still a big issue, but it is more contained: since the smart card will commit honourable seppuku instead of letting the precious private key be revealed, the situation can be recovered from. Once the mandatory format-and-reinstall has been performed, things are secure once again.
The Web site does not only want authenticity, it also wishes to get non-repudiation. Non-repudiation is a legal concept which needs some support from the technical parts of the system, and that support is digital signatures. We are outside of what SSL/TLS provides, here. In no way can a SSL/TLS client authentication be a proof which could be used to resolve some legal conflict between the user and the server itself (a bank server cannot show the transcript of the connection and say "see, that user really asked me to buy these actions at that price", because the bank could easily have fabricated the whole transcript). For such things, one needs client certificates and some client-side code which uses the certificate to sign the actual data. However, once the hard work of issuing certificates to clients has been performed, it makes sense to just use them for HTTPS.

In the common case of a Web server, none of these scenarios apply. So client certificates are not used, because they would raise practical issues while not adding any extra value. That would be a solution in search of a problem.


What happens to a pass vault when the GPG key expires? Say I were to use the Linux tool pass as my password manager and the corresponding GPG key were to expire. Would I still be able to get in?

Yes*, you would still be able to get in. Expiring a key tells people not to use it anymore, but anything already encrypted with the public key can still be decrypted with the private key.

A GPG key's expiration can also be extended at any time unless it's been revoked.

*The software may prevent using expired or revoked keys, but if so this limitation isn't necessary and could be removed.


How long shall a certificate be valid? See title. Are there any sources where there are recommended validity times of certificates (based on length, algo, etc)?

I'm particularly interested in validity of RSA certificates...

The expiration date for a certificate should be set to the date at which you would like the certificate owner to come back for a renewal. This is a matter of trade-offs:

Each renewal operation entails some action from some human somewhere, so it has a cost which can be non-negligible.
Commercial CA use a business model which entails selling certificates, and frequent renewals mean more income.
Expiration of certificates allows you to remove the corresponding entries from CRL (Certificate Revocation Lists) so you do not want to make certificates live really long.
Some jurisdictions mandate specific validity ranges for reasons which are often obscure and sometimes wholly irrational. But the Law is the Law.
You do not want to make certificates whose life extends beyond the date at which you estimate that the public key might become crackable due to technological advances.

There are various "estimates" for "key strength" depending on its length, and these sometimes come with recommendation of key lifetime. This kind of job if 10% science, 90% "educated guesswork", which is a kind of divination. See this site for a lot of data. In particular, NIST says that a 2048-bit RSA key ought to be fine until at least year 2030. But the difference between a "maybe crackable key" and a "maybe not crackable key" is very fuzzy, so don't expect hard data here.

In practice, key strength far exceeds actual certificate lifetimes. Typical lifetimes for end-entity certificates range from one to three years; make that five to ten years for intermediate CA. For a root CA, make it expire in 2037 (i.e. as far as possible in the future but without crossing the fateful Y2038 problem).


How can you use the information from Gmail's "Show Original" feature to check if an email really came from Google? I received an email saying that someone logged into my Gmail account from an unknown device. How can I verify that this email (security alert) actually came from Google and not from a malicious source? I clicked on "Show Original" and it says:

SPF: PASS
DKIM: PASS
DMARC: PASS

Does that mean that the alert really did come from Google?

If you are reading in Gmail and use the "Show Original" option, and the from address is from a Google domain (should be no-reply@accounts.google.com), then yes those three indicators are enough.

For a more in-depth review of the mail path, you can copy all the headers (everything above Content-Type: in the block below where you see those pass marks) and use a 3rd party analyzer to see the in-s and out-s.  I like MX Toolbox (https://mxtoolbox.com/EmailHeaders.aspx) -- just paste the headers in there and click "Analyze" to receive a full break down of what it all means.

Also, to be "phish proof", even if the message is from Google, you should manually go to your account settings to take remediative action.  This is a rule for every web site/service; never ever trust an emailed link that asks you to update security information.  Login to your account by hand, then go to your account security and take action from there.  It is a super easy rule, and a sure-fire way to avoid being tempted/trapped by a well-crafted spear phishing message.  Just head to accounts.google.com and take care of it from there.


XSS Risk to server behind Firewall Scenario:
publicserver.com is a publicly accessible web application, which does not filter input, allowing javascript/XSS attacks to be stored in the database.

privateserver.lan is only accessible from the inside of a firewall, on a private LAN, and not accessible from the internet.  It has a limited audience. privateserver.lan reads data from the publicly accessible servers DB (publicserver.com), and does not properly filter output, allowing Stored XSS.

Barring any intentional attacks from users with direct access to privateserver.lan, what are the XSS risks to the data on privateserver.lan, and to the users of privateserver.lan, keeping in mind that outside users are unable to gain access to this server through the firewall?

Also, to be clear, this is something We will be fixing, I'm only trying to assess the risk to determine the priority of the fix.

XSS doesn't run on the attacker's computer; it runs on the target's.  Thus, the fact that public internet attackers cannot access the internal site where the attack happens is irrelevant.

As an example, imagine this scenario:

Attacker adds XSS into the database via publicserver.com.
Company employee visits vulnerable page on privateserver.lan.
Employee is hit by XSS attack.

This attack could grab sensitive cookie information and send it to the attacker's external server.  Or maybe it queries a number of local IPs looking for vulnerable servers, then sends that information out to the attacker (who makes use of that to update the XSS to attack those servers).  There are any number of attacks that can happen, and merely being inside the local network while the attack happens doesn't protect you very much.

This is one of the reasons you might consider configuring egress rules into your firewall, rather than only blocking incoming traffic.

This is a very valid vulnerability.


How to login to websites with Google Authenticator using new phone? I know this question has been asked before - or similar. I really don't understand Google Authenticator. If I have set up 2FA on my old phone and can no longer use my old phone - how do I login to these various websites (e.g. cryptocurrency exchanges) with my new phone?

I think I misunderstood Backup Codes - I thought if I downloaded these backup codes I would be able to use them to access my favourite crypto website. But these are 8-digit codes, and my crypto websites require 6-digit 2fa codes.

Some websites will help you if you don't have access to your 2fa. I thought the point in the backup codes was to enter with new 6-digit codes, but clearly not. Is it possible to see on a new phone all the logins I had previously set up on my old phone? I mean, if I had 15 logins set up on old phone - How can recover all that entire set-up?

Chris

Solving the Existing Problem

Hopefully, you still have the old phone. Google Authenticator is not meant to be transferred, but you could use a backup utility (possibly requiring root access) to back up the data files from the old phone, and restore them on the new one. Also, many sites offer SMS as a backup way of verifying a login (even though this is not as secure), so you may be able to access some accounts this way, if set up.

If you can't exercise either above option, you will likely need to recover those accounts (possibly using backup codes; if they don't fit where you put the 2FA token, perhaps there is a "use a backup code" button like some sites have).

Preventing This Next Time

Google Authenticator, as mentioned, does not have backup capabilities at time of writing. The only other solution would be to use a 3rd party 2FA app. There are probably many options in the app store, but the main ones I'm familiar with are Authy, which syncs your tokens to the cloud (supposedly encrypted and only recoverable by you, but can you trust them?), or the open source AndOTP, which lets you import/export the data. However, I'd suggest you do your own research.


Will two intermediate CAs signed by the same root CA trust each other's signed client certs? I have two intermediate CAs that each sign certificates for their client users, like this:

             ROOT CA
             /      \
            /         \
           /           \
   Intermediate A    Intermediate B
     /                  \
  Client A               Client B

I run a service, Service A, that validate clients using Intermediate A's certificate chain.  So, Client A connects to Service A and is authenticated.  I want to set up a Service B that uses Intermediate B's chain so that it doesn't trust clients who present certs signed by Intermediate A.

If Client B has a cert signed by Intermediate B and this person attempts to connect to Service A (which uses Intermediate A's chain), will it be authenticated?

TL;TR: it depends on the exact configuration of which CA's are trusted in each service.

Authentication means that a trust chain to a locally trusted CA can be built. This means:

If service A trusts only intermediate A but not the root CA then it will trust any certificates signed with intermediate A but no certificates signed with intermediate B because no trust chain can be built from intermediate A to certificates signed by intermediate B. Similar is the behavior of service B.
If service A instead or additionally trusts Root CA then it will trust any certificates signed directly or indirectly by Root CA as long as it has knowledge of the necessary intermediate certificates. Thus if client B sends its client certificate and also the issuer certificate (i.e. intermediate B) then service A will trust it because it can build the trust chain.

Note that the last statement is only true if service A does not employ any additional restrictions. These restrictions might include a limit for the length of the trust chain: if service A accepts only certificates directly issued by its trusted CA then sending the certificate and intermediate for B will not make it trust client B. The restriction might also include an explicit distrust of intermediate B in which case it will also not accept the certificate from client B.


How to conduct XSS via message body or HTTP cookie? I am reading Hackers Handbook and in one chapter it says:
"Parameters submitted within the URL query string, message body, and HTTP cookies, are the most obvious entry points..."

I understand that the URL can provide e.g. a XSS. But can somebody explain how the message body and/or the HTTP cookie can be used as "User input" to conduct an e.g. XSS? Please provide an example of such "user input".

The main attack vector for reflected XSS is creating a request with embedded script code - usually JavaScript - which is then taken by the server and injected in the response sent back to the client. How the script code is sent to the server initially doesn't matter, as long as the server takes it and embeds it in the response.

It seems to me that you struggle with the following question: "How does the attacker trigger the victims browser to send such a request?"

In the URL. You mention that you understand this version, so we can work from there. The attacker crafts a URL that he send to his victim. This can be a simple link, that the victim clicks on, or some kind of redirect from another website. When the victim clicks the link, a GET request is sent with the payload, the server embeds it in the response, and the browser executes the malicious script.
In the message body. If you cannot use a GET request to perform XSS (because the server requires a POST request), you cannot provide the script code in the URL. You still use the same principle, but instead of putting the parameter in the URL, you put it in the message body. It's basically the same, but now you cannot craft a simple link with the payload. Instead you must trick the victims browser to send a POST request. An easy way for an attacker to do this is luring the victim to a website he controls. On this website, he uses e.g. JavaScript to create a form with auto-submit, which includes the payload as a POST parameter in the message body. When the website is visited, the browser executes the JavaScript code which sends the post request with the XSS payload to the vulnerable website - voila!
In a cookie. This seems tricky at first, because you cannot set a cookie for another domain in the victims browser. But that is already the solution to the problem - it does not work usually. What you need is a special use case, that allows you to set the vulnerable cookie through a mechanism in the website. Imagine a cookie that defines the language of the website. The website could implement a simple request that allows the user to store his language preferences in a cookie, allowing an arbitrary value. The server answers with a Set-Cookie response header containing this user defined value. This arbitrary language value is stored in the browser and sent as cookie with every future request. If the website is vulnerable to XSS, meaning it reflects the cookie value without sanitation, an attacker can craft an easy attack by forcing the browser of the victim to send two requests. The first one will store the cookie payload in the browser, the second one will be another request to the website, where the cookie gets reflected.

In the end, the concept of XSS stay the same in all three scenarios, only the attack vectors look slightly different. Providing specific user input, as you requested in your question, doesn't make sense though, because the payload is always the same. If you can do it with a GET parameter in the URL, you can do it with any other form of user input as well.


Security of sending information to stdout By default, something like gpg -d file.gpg sends it's output to stdout. What happens to input that is sent to stdout? Is it possible to recover this?

Really, stdout is just a unix pipe.  Essentially, it can keep some amount of the data in memory, and then blocks on input until the other end of the pipe is read from.  Often, this is the user's shell, which will read from the pipe and print to the user's terminal (or pseudo-terminal).  Of course, it can also be redirected to file output or to another program.

In the normal case, where the output is displayed on the user's terminal, the data is of course in memory, so if the memory is swapped to disk, it might be recoverable.  Also, if you have the running system, it might be possible to recover in-memory if it hasn't been overwritten yet.


Understanding VPNs : How VPNs can be used for anonymization? Previously, I asked the question Why is it difficult to catch “Anonymous” or “Lulzsec” (groups)? I understood every answer except the VPN thing. Its because I never knew what VPNs were. Any how that answer said:

  With the VPN, all your traffic is relayed through it so wherever you
  connect it can only track back the IP addy to the VPN itself and no
  further (unless the VPN is keeping logs in which case you shouldn't
  use it anyways).

So, I thought VPNs are like some kind of private proxy servers and usually they don't keep logs.

Then I encountered Which VPN Providers Really Take Anonymity Seriously? which compares the list of VPN providers who keep logs and who don't. Nice! I wanted to learn more about these VPNs and try one of these out.

So, I bought a book on VPN Beginning OpenVPN 2.0.9. I'm through the first two chapters. And I'm completely lost! He changed the entire definition of VPNs.

According to the author and wikipedia:

  VPNs are actually used for connecting different branches of an organization and forming a private network (virtually) over an real network using some encryption protocols and firewalls.

Now, I'm confused! If VPNs are used to avoid leased lines and establish a network between the different branches of organization. How can these help in anonymity? How exactly are these black hats use to hide their identity?

PS: Also, can any one kindly suggest a good book on VPNs? Most of the VPN books on amazon have poor rating. I don't know why.

"VPN" is a large umbrella concept for a variety of situations; they all have the following common points:

there is a need for confidential communication;
involved parties should, ultimately, behave as if they were part of a common shared network;
however, there is no physical separation between that private network, and the rest of the Internet; the same wires are used; separation is done cryptographically, hence the "virtual".

A typical VPN situation is when an organization wants to link two sites together. Users of computers should be able to connect to all computers on both sites as if they were all on a single LAN; but all data which has to go over the Internet (to cross from one site to another) is channeled through an encrypted tunnel. From the outside (i.e. someone eavesdropping on the link between the sites), all that can be observed is that data flows from one site to another; but the encryption covers both the data itself, and the source and destination addresses (the IP addresses of the involved hosts within the private network). The attacker only sees traffic between the external routers of both site, but cannot know which specific machines within both sites are currently communicating.

This is the level of privacy that a VPN offers: if hides both the exchanged data, and the true source and destination addresses. Attackers can still infer the amount of data, and which sites are active, but not the exact machines.

This model extends to traveling salesmen, who connect to their home office from their hotel room. They open a VPN connection, at which point their laptop is "as if" it was in the office, connected to the office network. But eavesdropper only see that the laptop is linked to "the office" in general, not what specific office server is contacted.

The distinction between VPN and proxy servers is kind of fuzzy; do not try to read too much in it. When we say "VPN", we want to emphasize that the encryption layer should work for all protocols, because the VPN is supposed to transmit IP packets; whereas a proxy is normally dedicated to a single protocol, or a small set of protocols, such as HTTP.


Is there any College, State or Government ID that transmits a offline verifiably encryptable data blob? I'm looking for any way to digitally verify a user, ideally with a photo and link PII to that user.

My use case is that a user will extract and send an encrypted data blob (say from a passport) to my server, and my server will verify it's authenticity, and approve access.

From what I can tell, the NFC/passport approach doesn't really encrypt the data in a way that works the way I need it.

I am curious if there are other standards, ID cards that support this.  I assume Germany or the Netherlands has something like this, since they have other similar projects.

Passports does not encrypt data, instead it uses Basic Access Control, as a authentication layer, to prevent access to passport data without authorization. The authentication data required to access the passport is written in the MRZ, so ideally, you would need to optically read the passport to get the "password" to open the RFID chip.

However, passport data is x509 signed, so you can still use it for verification if you want to authenticate a user via its passport, to ensure personal information and passport photo is not fraudulent.
Note that you must encrypt the data in transit. Note also that someone can copy the details from the passport and send to your server to impersonate a user if you only do static authentication.

However, passports also support a form of dynamic authentication to do challenge-response authentication of the passport, to ensure it has not being copied, but that requires a Active cooperation of your server, eg your server must actively talk to the passport through a link , for example a mobile phone with NFC that is held against the passport in several seconds during the "signup" process.
Basically, its the passport that signs your challenge using a certificate that is embedded in the passport, and thus you can verify the response is correctly signed, and the certificate used for signing is signed by the static certificate that you can verify against the ICAO root.

A mobile phone can be a excellent resource to allow anyone to signup for your service with a passport. They just photo the MRZ with the camera, then they hold the phone against the passport while your server talks to the passport to verify its authenticity, and then, the signup is complete. I guess you then only save the photo and name of the user.

Depending on your security requirements, it might be enough with static authentication.

Note that the password cannot be used itself for any signing or encrypting activites, so if you for example would want the user to be able to use his passport to sign or encrypt anything, you will have to create a key for the user and link it to the user.


Bitwise cipher Cryptography I'm doing an online cryptography course. There is a question in which it is given that the encrypted text for;

OwBPAAQXAE9UC0FVBQxODgZSCUUMAQwCCApYRBJZBR0LDhoAGApPHQAUAQNZRAJPGwQbDQBDDREKQA==

Is

  We need to use more complex systems to safely communicate.

They are asking the decrypted text for

JQtPDRMLFBtPAxNBBgEXT0lUBABPHQgfFANFRDlvJEkNChlICRdPBxJSBU9UHRFFVgYIQwhECAwbBxcXRAxJFAlFBEkaCwhUTBAcCxJSBU9THQxNEx0cCgoABwAWQEE7EE9JChdPGh8LEElQCRcJARMfDQFHRAAAFAAaFABTCUU3ITNSCx9FFgBUHwYAQwtFGBIKCw9SEAdFRAxFBRoPBAwADQsLTgoXHU9UC0FDBAwPFwwAGA0KTgIbFAdFFhVFDh1CQwhOCEUZBwIXRBlFFhJBVh0BQw5FGEUbBgRSCQpTFwBHE0kIEQZNTAYGHgkXFhtFHBUOVj0GBklGAAQITggBRBwBCRFMRRFeEQ==

What I have figured out:

After converting

  We need to use more complex systems to safely communicate.

To base64, I got another string with the same length as the string they have given, so now I have to find a relationship between both these strings. But, I have been unable to find any relationship so far. The hint given in the question is bitwise cipher. Any help would be appreciated.

String they have given;

OwBPAAQXAE9UC0FVBQxODgZSCUUMAQwCCApYRBJZBR0LDhoAGApPHQAUAQNZRAJPGwQbDQBDDREKQA==

String I get after converting

  We need to use more complex systems to safely communicate."

To base64:

V2UgbmVlZCB0byB1c2UgbW9yZSBjb21wbGV4IHN5c3RlbXMgdG8gc2FmZWx5IGNvbW11bmljYXRlLg==

I am unable to find a relationship between the above two strings.

The phrase "bitwise cipher" is most likely XOR'ing the base64 of the plaintext with a key of the same length. This is the most basic kind of symmetric cipher.

Try XOR'ing the base64 of the plaintext with the ciphertext they give you to get the "key". Then XOR this key with the challenge text to decrypt it.

And yes, I am aware this is an old question and the course is probably over by now.


What are the differences of checking a self-signed certificate vs ignore it? I'm doing an integration with a system that has a self-signed certificate. For initial development, we choose to ignore the certificate checking to bypass some errors:

  Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

because we first need to understand how to add the certificate using the Java keytool on a docker environment.

But, my question is: what is the advantage in that case to import a self-signed certificate as a "Trusted Certificate" when I could just ignore it?

If it's an official service you are integrating with the provider should really have a valid, publicly signed certificate installed for the sake of security.

Assuming that you need to continue on with your provider using a self signed certificate, the big difference between ignoring the certificate and adding it as trusted is the following scenario. This ues DNS poisoning as an example of a man in the middle attack.

Take the following example:

api.example.com has a self signed cert with thumbprint XXX listening on the IP 5.5.5.5.
Adding it to your trust store makes your system expect the thumbprint to be XXX when connecting
If someone was able to poison your DNS - make api.example.com resolve to 6.6.6.6 - the thumbprint would be YYY.
By adding the cert to your store your product would refuse to connect to the malicious site.
By disabling the check entirely, your product would happily connect to the malicious api.example.com at 6.6.6.6.


What makes Adobe formats so vulnerable? Tools that deal with SWFs, PDFs, OTF... seem to suffer from a disproportionate amount of vulnerabilities. Is the a characteristic in the formats that Adobe creates that makes them more susceptible to be broken?

Related:

Why are Adobe Flash exploits found so often? Note: I'm not asking why, rather what is common to all of these Adobe technologies.

What was behind the surge of Adobe Flash Player vulnerabilities/patches in 2015?

There are many factors but these are some:

They're non-standard binary files. Not based on XML/JSON/YML/etc, which means that each Adobe product developer has to reinvent their own parsers, which is one of the most difficult and tedious tasks for programmers.
These files are often designed with efficient processing, with little thoughts given to ease of writing secure implementation. For example, PDF contains an xref table, which contains the byte offset that programs have to seek() to find sections. If that's not bad enough, this xref table is located at the end of the file, necessitating PDF parser to read the file backwards from the end of the file. To add even more to complication, there can be more than one such xref tables in a single file, and some entries can be inactive or overridden by later entries.
The binary format can contain conflicting information. For example, a PDF section can be specified in different ways: each section contains the length of the section in ASCII numbers, an "endobj" marker, and entries according to the xref table. These conflicting informations means that different parts of Adobe's product and different implementations may rely on different ways to interpret the same section.
These file formats can contain Turing-complete executable code. A PDF file can contain Javascript code, a SWF file can contain ActionScript. Like any other document macro language (e.g. VBScript in MS Office files, JavaScript in HTML), these Turing-complete languages are a source of bugs of their own.
PDF touts itself as a format that should look the same everywhere, and you can open ancient PDF and expect it to render the same in modern readers. Some ancient PDF generators produced faulty PDF, which happens to rely on a bug in the old Reader/Acrobat. Rather than fixing the program and rejecting these faulty files as corrupted, Adobe programmed these hacks to keep these faulty files readable. Unfortunately, these hacks aren't documented, so it makes it difficult for other implementations to keep up with Adobe on how exactly to parse these malformed documents.
The formats have massive amount of features that's tangential to document formatting. Rather than using separate layers, Adobe like to implement everything in their own format specification. For example, many document formats like ODF, DOCX, JAR are simple XML/Class or and other metadata in a regular zip file. PDF intermixes compressed format into regular data stream, you can't just use a regular zlib decompressor to get uncompressed PDF. Same thing with digital signatures and version control.

Adobe is still making a lot of money despite these problems, which is probably the biggest reason why they don't really feel the need to care to change their developer culture.


Am I legally required to give passwords or keys for encypted data during an criminal investigation? During an investigation where one is  a suspect or one may have information about a suspect, is one required to relinquish passwords or keys to personal encrypted data to the authorities?

For example maybe someone has data on their personal computer in an encrypted container, data that is used or pertaining to a crime, stolen media, stolen government documents, or data that can be used to solve a crime.

The authorities have evidence that is beyond reasonable doubt that the encrypted data contains such files pertaining to the crime. This container may contain other sensitive data that does not pertain to any crime such as Social Security Numbers if that makes a difference. Does that person legally need to relinquish password or keys if asked by authorities?

This question makes me think, how secure is an encrypted file in a world run by people? Can the police come in my door, steal my computer and hold me in jail until I give up my passwords?

This question can also pertain to a company and consumer relationship where the company may hold encryption keys to consumers data.

UPDATE
I'm not involved in any criminal trail nor do i have anything illegal. When does legal intervention require someone to relinquish the security of encryption? I am not one to judge when its ethically right to give up encryption keys i was just wondering when its required.

This depends on the jurisdiction and local laws.

In some countries, you may be detained or fined for refusing to surrender encryption key or to decrypt encrypted data. This is called either key disclosure or mandatory decryption laws. In most civilized countries, enacting such laws requires warrants or court orders and may not be enacted with just probable cause. On others, even customs officer may be able to force you to decrypt data.


Is there a security issue on Linux that allows any application to monitor the screen From what I understand /dev/fb0 holds information of data displayed on the screen.
Isn't it a security issue that I can read from it as an unpriviledged user? Doesn't this mean any application can spy on the screen?

Also, is there a similar issue on other operating systems?

Hah, interesting. I just tested this on a console and you're right:

unprivileged $ echo "ABABABABABAB" > /dev/fb0

(writes a few pixels into the upper left corner of the screen)

unprivileged $ dd if=/dev/fb0 of=read_fb.dat bs=12 count=1
unprivileged $ cat read_fb.dat
ABABABABABAB

So an unprivileged user can write into and read from the framebuffer. It didn't work under my X server because I haven't configured it to use the framebuffer, but it might work if I changed my configuration (then again, since X has no isolation to speak of and an application can listen in on any another (including mouse movements and key strokes), this doesn't really add anything to the attack surface if you're running under X - Wayland should make this better).

So if I managed to get an unsuspecting user to run a program which read the screen, I could get his plans for world domination (or the parts of it
which are visible on the screen, anyway):

$ cat my-secret-plan-for-world-domination.txt
$ ...
$ program-which-reads-screen

Or even worse:

unprivileged $ sudo /bin/bash
root $ output-some-privileged-information-to-screen
root $ exit
unprivileged $ program-which-reads-screen

But if you think about this, this really isn't very surprising, because every time you take a screenshot, you're doing the same (on Linux, a quick search reveals fbgrab which takes a screenshot using the framebuffer). So I'd say that any operating system that lets you install programs that are able to take full-screen screenshots has the same issues.

The thing to be aware of, I think, is that someone could install a screen recorder without your knowledge, which would then record your whole session, even if you're not running under X and not expecting it. It's the pendant to a keylogging scenario.

In Qubes OS, the framebuffer is handled by the dom0, so I'd assume that the other vms cannot get access to the whole screen, but just to the part of it that displays their windows. This still means that applications running in the same VM can spy on each other, but not on output generated in another VM, and only a dom0 process could record the whole screen.


Does code obfuscation give any measurable security benefit? I've always firmly held the belief that obfuscation is essentially useless. Obfuscated code is not impossible to read, only harder to read. I had the belief that a sufficiently skilled attacker would be able to bring the obfuscated code back into a more readable state.

However, OWASP recommends the usage of obfuscation for mobile clients, which makes me wonder if there is more credibility to obfuscation than I had given to it.

Hence my question: Does obfuscation give any measurable security benefit? Specifically, a benefit that outweighs the added cost, complexity and reduced performance.

Note: When I say "obfuscation", I am talking about deliberate steps taken to prevent reverse engineering. Compiler optimizations, even though they make the assembly less easy to read, are done for the purpose of improving performance, not to prevent reverse engineering.

There are two benefits to code obfuscation:

It weeds out the shallow end of the attacker pool.  Script kiddies who struggle to make sense of your code will go somewhere else.
It increases effort required of skilled attackers.  No matter how skilled they are, obfuscation is cheaper than de-obfuscation, and the result is generally less comprehensible than the original (variable names will remain generic, for example, where the originals were descriptive).

@SteveSether is doubly right in his comment - actual measurements will be almost impossible to find, and many code bases are obfuscated for proprietary reasons* rather than security reasons.

But for both security and proprietary reasons, code obfuscation's value is tied to its asymmetric quality - it's cheaper to obfuscate than it is to de-obfuscate.

*By "proprietary reasons" I mean "the desire to keep one's code and algorithms more private, or harder to reproduce, in the interest of maintaining competitive advantage in the market."  Companies and individuals are both prone to this tendency.


Practical steps for encrypting an encryption key for data stored in MySQL So I'm working on my first project where user data is stored as encrypted using the user's password as (part of) the key. I have read many similar things about best practices, but the details seems to be glossed over for someone like me who isn't as familiar.

I have read that it's best to:

Have a strong hash (bcrypt) of the user's password for validation. Stored in DB
Encrypt private data with AES using a random 256-bit key ("KEY1"). Not stored
Encrypt KEY1 with AES ("Enc_KEY1") using a strong hash derived from the user's password as "KEY2". Different salt than Step 1. Store Enc_KEY1 in DB. Do not store KEY2 anywhere.

There are a two issues I'm not able to find answers about:

The string length of a bcrypt hash isn't compatible as an AES key because of length and illegal characters such as periods and dollar signs. How does one deal with this problem?
When it comes to decrypting Enc_KEY1, I have to first generate KEY2 from a hash (bcrypt) of the user's password... how exactly do I recreate the hash? Am I supposed to store the salt? It seems like bcrypt wants to create a random salt each time... but unless the salt is stored, there's no way to recreate the same hash... Is it bad to store the salt? What am I missing here?

Thanks for the help.

The string length of a bcrypt hash isn't compatible as an AES key because of length and illegal characters such as periods and dollar signs. How does one deal with this problem?

Base64 encoding is your friend.  Base64 encoded character are all legal characters with AES

  When it comes to decrypting Enc_KEY1, I have to first generate KEY2 from a hash (bcrypt) of the user's password... how exactly do I recreate the hash? Am I supposed to store the salt? It seems like bcrypt wants to create a random salt each time... but unless the salt is stored, there's no way to recreate the same hash... Is it bad to store the salt? What am I missing here?

Yes, you need to store the salt (and optionally pepper if you are using AES to encrypt the password hash).  Without it there is no way to re-make the hash.


dnsspoof not spoofing (requests and forwards real DNS packet) I was trying to use dnsspoof but it did not work as expected. These are the steps I followed:

Set IP forward in kernel to 1
arpspoof -i eth0 -t 192.168.1.39 -r 192.168.1.1 and arpspoof -i eth0 -t 192.168.1.1 -r 192.168.1.39. Checked with arp -a and it works
Create a file.txt with: 137.222.0.38   *.hello.com
dnsspoof -i eth0 -f file.txt

From victim computer 192.168.1.39 I browse to www.hello.com and it is redirected to the real site. Output from dnsspoof is:

dnsspoof: listening on eth0 [udp dst port 53 and not src 192.168.1.35]
192.168.1.39.1113 > 8.8.8.8.53:  3864+ A? www.hello.com
192.168.1.39.1113 > 8.8.8.8.53:  3864+ A? www.hello.com

I have checked on Wireshark and it seems that the victim is receiving responses from the same IP with the router MAC (first) and with the attacker MAC (second). I have flushed the DNS and tried fresh requests, even though this should not be necessary in theory. My questions are:

1) Why is this not working? Someone has suggested using iptables to block packets from the router, but it seems strange that dnsspoof does not do it by itself, and none of the tutorials I have checked (1, 2, 3, 4) requires this step. Also, I cannot get the right iptables rule to make this work correctly.

2) Many tutorials seem to use dnsspoof without arpspoof. Is the latter really necessary? I mention because once (by chance) the DNS spoof seemed to work in another computer which was not "arpspoofed".

3) How does dnsspoof work? Just by listening for DNS requests in the whole LAN and then sending the resolution back?

EDIT

With the iptables command iptables -D FORWARD --match string --algo kmp --hex-string '|68 65 6c 6c 6f|' --jump DROP the router is not queried, and only the spoofed DNS is sent. However, the victim browser stays loading forever and finally it says it cannot access the site(?). Without the iptables command I am able to see how the request goes like this:

victim --> attacker --> router  and answer:  router --> attacker --> victim

And just after this the attacker sends twice the spoofed DNS to the victim. Again, I am still confused about this behaviour and have not answered yet any of my three questions. I kind of believe the answer for (2) is that dnsspoof spoofed the whole network, but only if you did arpspoof before you can guarantee that the spoofed packet will get to the victim before the legitimate one. However, in my case, this is not working because the petition is forwarded.

EDIT

This is a network capture with the same example over another network (10.10.10.0). The legitimate DNS is forwarded first and, later on, the spoofed DNS. In this example, there were other petitions in the middle of both responses but quite often I get the packets one after the other.

Try installing libpcap0.8 and libpcap-dev. There was a bug and this should fix it, although it didn't work for me. I use kali on my tablet with a Linux deployment and there are many issues.


Capturing sensitive data within legal restrictions? As a web development agency we're currently taking on a site rebuild for a recruitment agency. The current site allows applicants to register as temporary workers for the agency ( our client ) who will then be assigned short-term contracts as and when required.

The application form on the current site for these workers captures and enormous amount of really sensitive data including bank details, contact details, education and even detailed medical history of the applicant. Amazingly it does this on a regular HTTP connection without SSL, and the data is stored in a mysql DB also used by the site. IMHO it's negligent at best.

Our client wants the same behaviour on the new site we're developing, but obviously we have strong concerns about the legality and the security concerns of implementing the current business logic.

Can anyone give any guidance about what can legally be stored, how best to store the information and maybe any alternative scenarios that we can put to the client? To clarify we're subject to UK (EU) data protection laws for this site.

Obviously the first step we're taking is to serve the new site via HTTPS, but other than that the best we can come up with so far is to just capture the non-sensitive information, and require the recruitment agency to make separate enquiries of the applicants to obtain the nasty stuff like bank account numbers and medical history.

any help much appreciated......

When talking about data protection, you can refer to this page for the UK. The gist of it is below:

  Everyone responsible for using data has to follow strict rules called
  ‘data protection principles’. They must make sure the information is:

  used fairly and lawfully
  used for limited, specifically stated purposes
  used in a way that is adequate, relevant and not excessive accurate
  kept for no longer than is absolutely necessary
  handled according to people’s data protection rights
  kept safe and secure not transferred outside the European Economic    Area without adequate protection

  There is stronger legal protection for more sensitive information,
  such as:

  ethnic  background
  political opinions
  religious beliefs
  health
  sexual health
  criminal records

Now the part that says "kept safe and secure" is to be implemented based on the interpretation of the person implementing the security. The fact is that a judge will look at the measures you took and then deem if those measures were adequate.

There is no law that says you need to use HTTPS perse, but not using it might be considered as not inline with the industry good practices. Therefore meaning you are not adequately protecting the information.

Note that there are many other things to consider as well such as regular patch management, controlled change management,etc... . With regard to medical info there will be even more stringent measures they would expect to be in place, including a good auditing and accounting system to supervise who accessess what records at what time.

In terms of fines the GDPR which supersedes the DPA  prescribes penalties – up to 4% of annual global turnover or €20 million.


Why MSS is needed in SYN cookies? I was reading RFC4987 describing SYN cookies and seems Maximum Segment Size (MSS) is encoded in the SYN cookie and I am not sure why that is the case? Can someone explain why we need the MSS in the SYN cookie?

This has something to do with MTU and Path MTU Discovery (PMTUD).

Let's assume your MTU is 1400 and MTU of your server is 1500. When you try to download the file, without MSS or PMTUD, server would try to send you file in around 1500 byte packets which would be dropped since your MTU is only 1400.

With Path MTU Discovery, server can discover what is the MTU size, the thing is, it relies on ICMP. So when packet is dropped, the ICMP message is sent back. However, if ICMP is blocked, server must rely on MSS value included in SYN packet. So if your lower your MTU, your MSS value in SYN packets will be lowered as well so the servers will now know how to size the packets.

Your router can also be altering MSS field in SYN packets to adjust to MTU of your broadband line like ADSL. It's iptables feature "SYN TCPMSS clamp to PMTU". This is because if your broadband line MTU is lower than your WIFI MTU (which is normally 1500), router may need to clap it for you so the packets coming back from the internet servers are sized for your Broadband and not WIFI.


Is it safe to upload & scan personal files on VirusTotal? I had an idea to make a plugin for one of my email clients where my users will be able to upload & scan attachments using VirusTotal service, but then again I was worried about their privacy and security of uploading personal files which may have been exposed to someone.

My question here is; how safe is it to upload personal files, could they get exposed to someone beside owner of VirusTotal?

Paid subscribes to virustotal can download files uploaded by others. If you consider this still safe for your users depends on what you consider safe.

See also their Privacy Policy which clearly says:

  Information we share
  When you submit a file to VirusTotal for scanning, we may store it and
  share it with the anti-malware and security industry ... Files, URLs, comments and any other content submitted to or shared within VirusTotal may also be included in premium private services offered by VirusTotal  to the anti malware and ICT security industry

Still, I think that your idea of offering a simpler access to a useful service directly from the mail client makes sense. I would though recommend that you add an easy to understand but not easy to ignore warning about the privacy implications before the user uploads a file. And it might be less invasive to first check if the hash already exists at VT before uploading a file (and not upload if hash is known to VT).
Ideally you also make it easy for users to remove an accidentally shared file (thanks to @Mirsad for this suggestion in a comment).


Using this path traversal security issue I used zap to scan one of my websites and found a path traversal issue.

These are the informations:

Attack: c:/

URL: www.example.com/example.php

Parameter: mail

I am now tinkering around in the browser and in CMD with curl and try to get access to the root, but nothing works. Could it be a false positive?

I have done tons of tests now, but shouldn't these give some results:

www.example.com/example.php?mail=../../
www.example.com/example.php?mail=..%u2216..%u2216
www.example.com/example.php?mail=..%c0%af..%c0%af (I tried even more encodings)
www.example.com/example.php?mail=c:/

Here is an example with cURL:

curl --path-as-is -X POST --data "mail=..%c0%af..%c0%af" https://www.example.com/example.php

I found where ZAP displays which request has been done:

mail=c%3A%2F

But the response looks correct. Its the HTML site.

EDIT:

If I execute this cURL I get an empty response, there is nothing.

curl --path-as-is -X POST --data "mail=c%3A%2F" --url
"https://www.example.com/example.php"

EDIT:

If I make the same request through the browser and look at response I see:

Failed to load response data

EDIT:

Wow... it was a false positive. So here is what happened.
I had an inline html comment, which looked like that:

<!-- enemies, boulders, etc. -->

I noticed that zap has marked (grey color) the word etc. I assume because its usually part of an important file system path.

I have no clue how this could be connected to path traversal, but after removing the comment zap does not alert this issue anymore.

It was a false positive. So here is what happened. I had an inline html comment, which looked like that:

<!-- enemies, boulders, etc. -->

I noticed that zap has marked (grey color) the word etc. I assume because its usually part of an important file system path in unix-based systems.

After removing the word etc there were no more path traversal issues in the report.


javascript:alert("test"); command does not work Hello! As I have done before and also have read in many web sites, that just simply writing:

javascript:alert(document.cookie);

should work on any web page.
But now, I was not able to execute it. I have checked it with firefox and chrome. Why it is not possible to do it?

javascript: URLs have been used frequently enough in a malicious fashion ("Hey! There's this new cool thing! Go to your Google Mail inbox and copy and paste this into the address bar!") that recent browser releases have taken steps to change the way they work.

In Chrome (tested v20 on OS X), a copy and pasted "javascript:alert(document.cookie)" url has the javascript: portion removed (MSIE 9 reportedly does similar). Manually re-adding it causes it to work as I'd expect, and shows the (available to Javascript) cookies for the page.

In Firefox, as of ~ Firefox 6.x, javascript: (and data:) urls no longer inherit the security context of the document in the current tab.

See Mozilla Bug 656433 - Disallow javascript: and data: URLs entered into the location bar from inheriting the principal of the currently-loaded page  for more background and some debate.

Some alternatives to javascript: URLs:

Browser tools such as the built-in Firefox "Web Console" or
"Scratchpad" can be used to inspect and execute Javascript in the
context of the current document.
Firebug is a wonderful browser plugin that offers Javascript
inspection/execution and more.
In Chrome, the Developer Tools and Javascript Console can be very
useful.


Yara condition count operator with wildcard I have a yara rule that looks for multiple strings in a file and fires if the count is greater than 3. But how would I change the condition statement to only fire if greater than 3 but less than 5?

Essentially I want something like this

3 < (#var_*) < 10

But this statement is not valid syntax. Is there a way to use the count operator # with a wildcard *?

rule strings
{
    meta:
        notes = "testing"
    strings:
        var_01 = "string1"
        var_02 = "string2"
        var_03 = "string3"
        var_04 = "string4"
        var_05 = "string5"
        var_06 = "string6"
        var_07 = "string7"
        var_08 = "string8"
    condition:
        3 of ($var_*)
}

Your rule condition will match if at least 3 of the string found, not the count of all the string found. Because Yara doesn't mix the wildcard identifier(*) with counts(#), you can only use regex to simplified the count.

rule countstr
{
    strings:
        $a1 = /(string1|string2|string3|string4|string5|string6|string7|string8)/
    condition:
        #a1 > 3 and #a1 < 10
}

Bear in mind that regex cannot compete with plain string matching. For performance concern, you need to resort to something like the following.

rule countstr2
{
    strings:
        $a1 = "string1"
        $a2 = "string2"
        $a3 = "string3"
        $a4 = "string4"
        $a5 = "string5"
        $a6 = "string6"
        $a7 = "string7"
        $a8 = "string8"
    condition:
        (#a1+#a2+#a3+#a4+#a5+#a6+#a7+#a8) > 3 and (#a1+#a2+#a3+#a4+#a5+#a6+#a7+#a8) < 10
}


How to protect yourself against OSINT? I recently watched a video about OSINT and learnt it can be quite a powerful agent.  I've been on the internet for years, and at this point I'm not sure what I've posted and where.

Given this is now a form of recon in cybersecurity, do you have tips on how one can protect themselves against it?

Open source intelligence has been around for sometime even though it's received attention only in the recent past. Here's what I do to keep a check on myself.

Step 1: Hack yourself

Have you ever googled yourself? Try to gather information on yourself using OSINT techniques. Start somewhere, perhaps your most common username you use to access this website and move on from there. There are various tools available to search for usernames on the internet. You'll be able to find where you've signed up with that alias. Many times, it will be in places you don't even remember signing up at. Read through the posts and see how much information about you is given out.
In the meanwhile, start making a profile of yourself based on the information you've found. You'll be surpirsed what you end up with for each post you might've made or replied to will have something unique to tell about you. You might sometimes even find older usernames you used to use somehow having a connection. Branch out from there, search around for that now, all while noting your findings down. By now, you have a fair idea on the person's likes, dislikes, interests, views, etc. Now, in my opinion, things get dangerous when you can connect a person's online identity to their real identity. In some cases, you do it intentionally, in other cases, it happens unintentionally. You find a post that leads you to a username, that leads you to a blog post, that leads you to the user's LinkedIn profile. And now you have rich information on that person.

There are many great tools for reconning people. Google search filters being the first best example to really help you narrow down results. Your info is out there, it's just a matter of finding it. Here are some other tools that can help.
http://pipl.com
http://192.com
http://searchpeopledirectory.com

Step 2: Recalibrate

Once you've gathered a good amount of information on yourself, you need to start evaluating what do you want everyone to know, what should be seen with limited access (friends on facebook, connections on LinkedIn, etc), and what is up there but really shouldn't have been. Once you have this, you can backtrack, find these sources and tidy them up. You can also get a close friend to do the same recon on you to get a different perespective, maybe she finds something different about you.

Step 3: Control

I make it seem like the internet is bad, it really isn't. Some people like sharing and interacting with the community, posting things, tweeting their opinions, sharing experiences. And this is fine, as long as you know what you're doing and are okay with it. The internet is absolute, once it's up there, if you forget about it, it's going to be up there forever. So know that if you post something, don't be surprised if someone you've never met knows a lot about you. Even if it is a private forum, share assuming everyone is watching.

This entire thing is not a one time effort. I like doing it every now and then for I do a lot of things without realizing the impacts of it. As time goes by and your awareness increases, you'll automatically have a filter in your head that raise red flags if you're sharing something you shouldn't be. Some call it paranoia, I call it necessary (in limits).

Bottom line, get used to the fact that what you share on the interent is probably going to be seen by a lot more people than you'd expect and might tell a lot more about yourself than you'd have thought. Once you have this implicit filter in your head, you can control how much someone can gain on you with an OSINT based attack. Apologies if this answer is largely unstructued. There's no right or wrong answer here. Read other answers, get some ideas and make your own model. Goodluck!


When does S/MIME require the other party's certificate and when is their key enough? Trying to understand S/MIME implementation, I see that sometimes you must have the other party's certificate, and sometimes its enough to just have their public key.  I'm confused as to when you need a certificate and when they key is enough.  Can anyone clarify?

(I'm trying to understand the internals here, so my question is conceptual - I know that practically speaking, most email clients use the full certificate).

S/MIME builds on CMS (the standard name for what was previously known as "PKCS#7"). An encrypted email really is a CMS enveloped-data object. The bulk of the data is symmetrically encrypted, with a key which is derived/exchanged using one of the transport mechanisms detailed in section 6.2:

KeyTransRecipientInfo is basically asymmetric encryption with the recipient's public key. That's what is used when the recipient has a RSA key fit for encryption (i.e. not a RSA key tagged in his certificate as "signature only").
KeyAgreeRecipientInfo is for key exchange algorithms which are not asymmetric encryption. You will use that if the recipient has a Diffie-Hellman key.
KEKRecipientInfo is used when there is a shared (high entropy) symmetric key between sender and recipient.
PasswordRecipientInfo is used when there is a shared password between sender and recipient (which thus calls for some extensive password hashing to make up for the inherent weakness of the password).
OtherRecipientInfo is for all other cases, which did not fit in the categories above.

The critical point is that for both KeyTransRecipientInfo and KeyAgreeRecipientInfo, the recipient's public key (be it RSA, Diffie-Hellman...) can be identified in two ways:

  RecipientIdentifier ::= CHOICE {
    issuerAndSerialNumber IssuerAndSerialNumber,
    subjectKeyIdentifier [0] SubjectKeyIdentifier }

  KeyAgreeRecipientIdentifier ::= CHOICE {
    issuerAndSerialNumber IssuerAndSerialNumber,
    rKeyId [0] IMPLICIT RecipientKeyIdentifier }

  RecipientKeyIdentifier ::= SEQUENCE {
    subjectKeyIdentifier SubjectKeyIdentifier,
    date GeneralizedTime OPTIONAL,
    other OtherKeyAttribute OPTIONAL }

  SubjectKeyIdentifier ::= OCTET STRING

When the public key comes from a certificate, then the public key can be identified using either "issuerAndSerialNumber" (a copy of the "issuerDN" and "serialNumber" fields of the certificate), or with the "subject key identifier". The latter is a bunch of bytes which can optionally be included in a certificate (as a Subject Key Identifier extension). Either information is readily extracted from the certificate. You never need the complete certificate, but you need parts of it.

S/MIME also supports public keys which are not obtained from certificates, but from "S/MIME preferences". The idea is (or maybe was ? I haven't seen that in a long time) that a user may have only a signature certificate (e.g. with a DSA key). In that case, that user could generate his own key pair for asymmetric encryption or key exchange, sign the public part, and include it in messages he sends. People who want to respond can then use that public key for key transport or key agreement. Since that key is not contained in a certificate, it cannot be identified with fields from the certificate. Instead, it will be identified with a "key identifier" similar to the "subject key identifier", i.e. a bunch of bytes.

Summary: all the crypto uses only the key, but the message format must include a designation for the key which was used, and that designation will use fields extracted from the recipient's certificate (if the recipient's public key indeed comes from a certificate).


Why is spoofing allowed in reputed VPS services? I just learned about IP spoofing and so I set up VMs and sent spoofed UDP packets (8.8.8.8, Facebook's IP, Twitter's IP) to myself (home PC and mobile) from well-reputed VPS providers like AWS, Softlayer, Intellectica Systems, etc. and I was able to receive them.

I am a novice to networking, but isn't this dangerous? Shouldn't these providers have taken measures to stop this? I would like to know why these well-known providers have allowed this. I mean isn't it a firewall problem and network problem?

The reason why spoofing is allowed may lie in thresholds and risk-based security.

Thresholds because single occurrences do not always imply incidents. A certain amount of packets of some kind are required to cause meaningful damage (e.g. DDoS). Flooding spoofed packets may trigger an action.

Risk because all good security is based on risk versus cost. If a VPS service earns more money (in customers and purchases) and/or saves more money (in staff, equipment and licences) by keeping a feature open than they lose (in bad reputation and responding to incidents), they will probably maintain the feature regardless of ethics and best practices.

Lastly, there may be some legitimate use cases for spoofing though none come to mind right now... Anyone?


User password as offline encryption key I want to store a file encrypted on the user's device for offline access. Since they don't have an internet connection, they can't sign in with their username/password and receive a secret key, so my thought is that I could derive a key directly from their password. They are using a non-windows device, so cannot use something like DPAPI.

The scheme is essentially: User's password is run through some key derivation function like pbkdf2 to get an acceptable strength key. This key is used to encrypt the file locally and can be generated on the fly when offline by having the user input their password.

Questions:

1) You can run a billion iterations of pbkdf2, but if their password is a single character it won't help much. Does this change if there is a mandatory password policy that ensures at least relatively sane passwords?

2) Alternative key generation techniques?

3) Overall thoughts/suggestions?

4) This gives an offline attack method to get their password for the service which has access to a whole lot more than just this file. Seems like this adds substantial risk. Thoughts?

Sounds alright to me. I'll answer your questions and add some thoughts:

  1) You can run a billion iterations of pbkdf2, but if their password is a single character it won't help much. Does this change if there is a mandatory password policy that ensures at least relatively sane passwords?

I personally hate password policies, but I'm not your average user. You could consider warning them (saying 8 characters non-dictionary is a reasonable password) but otherwise leave them free to do what they want. Maybe when they try to use a 3-character password or less, give a pop up going "that one sucks, do you maybe want to leave the file unencrypted instead? [y/n]" ;)

  2) Alternative key generation techniques?

See How to securely hash passwords? for some ideas. They are not strictly key-derivation functions, but I think you can use things like scrypt and bcrypt the same way.

  4) This gives an offline attack method to get their password for the service which has access to a whole lot more than just this file. Seems like this adds substantial risk. Thoughts?

Good point! It does give away offline cracking, but only for one user. In the case that password file gets stolen, the attacker could probably modify the device to include a keylogger anyway.

  3) Overall thoughts/suggestions?

Besides a key-derivation function, also look at how you encrypt the file. You'll want to use authenticated encryption, or at the very least, a block cipher mode of operation (i.e. don't use ECB).
You could also encrypt the file with a randomly generated key (using a CSPRNG) and then encrypt that key with the user's password. If the user wants to change the password, they can do that without re-encrypting all the data. You only have to re-encrypt the key.
Users don't like it when there is no "I forgot my password" option. I am in favor of saying "this is how every file storage service should work anyway so stop complaining" but that's simply not acceptable for many companies. You could encrypt the key (see my previous point) not just with the user's password, but separately also with your public key. Then the password reset feature can use the private key (stored on the server only) to decrypt the key and allow for a password reset. This also means you have access to user's data, though.


Applying IT Sarbanes-Oxley (SOX) to a tool management application Does an application that manages access controls to a suite of tools (Jenkins, Nexus, BitBucket) in a SOX environment need to be considered a SOX application?

The app itself only deals with data in transit and uses authentication to properly restrict how the app is used to manage the the SOX tools settings. The app also has an append only log for audit purposes and to build the state for administrators to view(event sourcing).

Lastly, all the tools make up a CI/CD pipeline are in a SOX environment so that they can deploy artifacts to VMs in the SOX environment.

If the apps can be used to push app modifications to your production environment with regard to financial applications, they will be subject to SOX. Considering your Bitbucket, Jenkins and Nexus all are used for ensuring certain controls (e.g. controlled deployment to prevent pushing unauthorised code), they may be considered as part of the control environment.


POST request no-cache header During security tests/assessments it is often said that you need to set the cache-control to no-cache (and some other things). But as I was looking at this I found that POST requests are not cached (which makes sense) by default.

So my question is: If sensitive data is only send as response to a POST request is it then still necessary to set the no-cache header for those POST requests? This is assuming it is no problem that GET requests are cached as they contain nothing of interest.

Referring, to this answer I would take this to mean that the browser could cache the response, therefore it is good practice to set the headers to inform the browser that it should not.

As that is a an old post, note that we should now be looking at this section of rfc 7234 rather than the obsolete 2616. Many modern browsers now interpret no-cache as no-store as equivalent, although for the small price of setting the correct header I would explicitly set no-store.


Can Zap scan a web app launched as a JAVA applet? I have a target which is a Java applet. When I reach the IP in the browser and enter credentials into a form, a .jnlp file downloads, which I need to double-click on to access the page.
Does Zap have support for scanning this types of Web apps?
Many thanks.

Per: https://java.com/en/download/help/proxy_setup.xml
For a Java Applet the proxy details can be set via the Java Control Panel.

Configure Proxies through the Java Control Panel

In the Java Control Panel, under the General tab, click on Network Settings.
Select the Use Browser Settings checkbox.
Click OK to save your changes.

Network Settings for the Java Control Panel
Close all browser windows. Restart the browser and try to load the applet.
If the applet still does not load and you see the same connection error,
try to configure your web browser's proxy settings.

So yes you should be able to configure either Java or your Browser to use ZAP in order to capture and manipulate the traffic from a Java Applet.


How do I ensure there is sufficient entropy on an embedded system at first boot? I'm working on an embedded system that will generate an SSL key the first time the system boots. I would like to avoid the problems discovered by Heninger et al. and Lenstra et al. where embedded systems with low entropy have a tendency to generate the same keys. My understanding is that Linux gets its entropy from the following sources (slide 19):

Hardware RNG
Keyboard
Mouse
Disk Rotation

The embedded hardware that I am working with will not have any of the above sources of entropy.

What are the best practices for getting good entropy in this case? I'm interested in solutions that can be trusted in production (I'm not looking for science experiments).

A similar question was asked and answered on Stackoverflow. Some ways to generate entropy:

find out time between network packets;
use Fortuna;
check kernel variables which are mostly unpredictable (snmp, w, last, uptime, iostats, vmstats, etc.);
read temperature sensors or other sensors you have on the device.

IBM also has a best practices guide here. It suggests:

Assess quantity of kernel entropy available just
before generating keys. Assessing the quantity of kernel entropy
available immediately before keys are generated helps to ensure
randomness.
Ensure that manufacturing procedures do not clone keys or
entropy sources.
Prevent or limit network access. Improve security by
preventing Internet access or limiting network access, if possible.
Seed, or initialize, the kernel entropy pool with node-specific data to improve key strength.
Increase the kernel entropy pool by adding device
event timing uncertainty. If you build your own kernel devices, you
can increase the kernel entropy pool, and therefore increase entropy,
by adding device event timing uncertainty.
Generate keys just before they are required (instead of
during first boot).


Auto deploy war file (backdoor/shell) to particular folder I am in the midst of a pentest. I have managed to uploaded a war shell (backdoor) in c:\test\ which is automatically deployed in a folder, for example c:\test\tmpbrowser.war.
The application which I am testing and its files which are accessible are installed in c:\approot\extracted\.
Now what I want to arrange is that, when I upload a war file to C:\test\, it will get deployed to C:\approot\extracted\.

Is this possible?

With Linux if you had a shell you could symlink the paths together however I'm not sure if there's any method of doing this on Windows.. can you execute a file to move it for you?

Please define the restraints you are working with and what you have access to


Server gets infected with malicious files I have a lot of php files being inserted to my server with spam mail purpose.

When i check the apache access log i notice the following line:

95.213.177.123 - - [07/Mar/2017:12:28:50 -0700] "POST http://check.proxyradar.com/azenv.php?auth=148891493017&a=PSCMN&i=757631275&p=80 HTTP/1.1" 404 10269 "https://proxyradar.com/" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)"

What does the line above mean exactly? when i interpret it correctly, someone send a POST request to the server, however my server responded with a 404 request. Could this be the bad request that creates the malware php files on my server?

I suspect a misconfigured server being the problem. When i block all ports except for ftp, ssh, 80, 443, etc. the attacks do not happen.

However the some services do need different ports, especially for passive FTP mode there are additional ports required.

I would like to find out how exactly the hackers get into the server.

thanks for any advice/pointer into the right direction!

This is a service testing if your server is misconfigured and you are an open proxy. Nothing to worry about.


Provide CSRF token to the front-end, if not present in the request headers I have a web app in which, when users request a page, a CSRF token is generated and injected into the jsp page in a hidden input field.

The same token is then sent to the server for every AJAX call in a custom header whereas, a session-state token is contained in a cookie (secure + httpOnly).

Now, since the CSRF token is something new in the webapp, if after the update the user was already logged in, and he sends a request, a Filter will determine that he's in fact logged (because of session-state token in the cookie), but a valid CSRF token is not contained in the custom header, and so the defined behavior is to log him out.

I may deal with this, by following this OWASP example.
If a CSRF token is not present, I intend to send a NO-CONTENT request back and somehow provide the token.

Here's the first doubt:

Shouldn't the CSRF token not be placed in a cookie?.

Moreover they are providing a CSRF token back if it's missing in the request, which seems to me a bit of anti-secure: an attacker could have stolen the session token from the cookie, send a request, and magically receive the CSRF token back.

I therefore feel confused here.

Should I just put the CSRF token in the cookie along the session state token?
Should I avoid providing a CSRF token if none is set, but a session-state cookie exists?
What may an alternative solution for my case be?

Notes:

Before checking the CSRF token, I verify the origin and referer headers, as advised here.

I do not plan to implement a use-only-one-per-request CSRF token.

Although irrelevant in this context, the communication happens via HTTPS

There are multiple ways to address a CSRF vulnerability. The implementation that you are looking at, uses a stateless method of managing the CSRF token. This is called the double submitted cookie method. This saves you some effort if you do not wish to track the CSRF token on the server side.

From the OWASP link you shared in the question:

  A double submit cookie is defined as sending a random value in both a cookie and as a request parameter, with the server verifying if the cookie value and request value match.

The security risk arises when your CSRF token resides only in the cookie and nowhere else. This would not be sufficient for CSRF prevention as it would be the same thing as having another session cookie.

In the double submitted cookie implementation you just have to ensure that the token values received from the cookie and from the form parameter are the same. In case of a CSRF attack the forged request would contain the token in the cookie but the token value from the from parameter/custom header will be absent. Hence leading to detection and prevention of CSRF.

To answer your other question about returning a CSRF token if the request is authenticated but does not contain a token already. This entirely depends on the kind of user experience you want your users to have. In some cases it may be okay to redirect the user to a login page.

Let us say you do return the token in the cookie and there is a CSRF attempt. In such a case Same Origin Policy would prevent any malicious domain to gain access to the cookie value directly and hence the subsequent forged request would fail for the same reasons given above.

For additional security considerations in case of a double submitted cookie implementation:

Double Submit Cookies vulnerabilities


Is ssh with public key authentication, no passwords secure enough? I have a web server set up and would like to connect to it from outside using Tor.
The web server simply serves up a simple webpage that will act as an interface for a program running on the machine.
It is not meant to be accessible by anyone else.

If I set up another computer with SSH and set to log in using SSH keys to act as an SSH tunnel, is this secure enough from most attackers?

With the SSH tunnel and Tor in place, is there a reason to use SSL or is all this secure enough?
What attacks are still possible and how do I defend against them?

If you are using public key authentication for SSH, no one can log in to the server without having the corresponding private key. This is as secure, and usually more secure, than password authentication. The encryption OpenSSH provides is state of the art; there is no known way to break it. You can further improve security on the Tor side by using authorized hidden services. This will make the domain inaccessible to all but your client. Note that this only works with v2 hidden services, not the latest v3.

The only remaining attack would be a man-in-the-middle attack. You can copy over the host key from the server to your client, just like you copied a key to make public key authentication possible. This will completely mitigate man-in-the-middle attacks and the client will warn you if an attempt is detected.

See also What is the difference between authorized_keys and known_hosts file for SSH?


Is it possible to securely sign data in a web browser? There is a WebCrypto API in browsers. It allows clients to sign data. However, it seems to me that it does not prevent web page to access the private key.

After key has been generated, it can be marked as non-extractable and can be saved to IndexedDb API.

How to generate the key, that it is clear for the client that web page could not access the private key during the generation?

For instance, web page can generate extractable key and then import it as non extractable and send the private key to the server, which served the web page.

(Is it possible to ensure this without proprietary addons?)

Setting the extract option to false does allow you to extract the public key but NOT the private key.

If you put the below code in JS Fiddle you will get "[object ArrayBuffer]" for the public key and "HEY:Key is not extractable" for the private key.

You can still sign with the protected private key using the reference key_priv later but never read the actual private key.

This is exactly the behavior you are looking for.

window.crypto.subtle.generateKey(
{
    name: "RSASSA-PKCS1-v1_5",
    modulusLength: 1024,
    publicExponent: new Uint8Array([1, 0, 1]),  // 24 bit representation of 65537
    hash: {name: "SHA-256"}
},
false,   // can extract it later if we want
["sign", "verify"]).
then(function(key) {
    window.crypto.subtle.exportKey("spki", key.publicKey).
        then(function(key_pub) {
    alert(key_pub);
        window.crypto.subtle.exportKey("pkcs8", key.privateKey).
        then(function(key_priv) {
                alert(key_priv);
            }).catch(function(err) {
                alert("HEY!: " + err.message);
            });
    });
});

Remember that you only need to send the server the public key that it can use to confirm the signature.


Is ECDH for SEC P-384 and P-521 broken in Windows 10 / Windows Server 2016 TP3? UPDATE: Proof of concept code here, console output shown below and all involved certificates are here.

Just noticed that ECDiffieHellmanCng.DeriveKeyMaterial(...) behaves differently on Windows 8.1 Enterprise (x64) and Windows 10 Prof (x64).

Specifically, when doing something like

byte[] SymKey12 = party1.DeriveKeyMaterial(party2);
byte[] SymKey21 = party2.DeriveKeyMaterial(party1);

the values of SymKey12 and SymKey21 are different on Windows 10 for several ECDH secp384 and ECDH secp521 scenarios that passed just fine on Windows 8.1.

Any ideas?

Windows Server 2016 Tech Preview 3 (version NT 10.0.10514.0) and Windows 10 output (version NT 10.0.10240.0)

'Test ECC Alice secp521r1 SS' <=> 'Test ECC Bob secp521r1 SS'
> FAILURE < ECDH Keys are different!
SymKey12 = 22-46-6B-15-0F-9B-65-B0-D6-7D-AA-0E-C5-8A-7F-F3-18-1F-5F-62-88-26-90-67-DC-99-1B-98-73-3B-58-FF
SymKey21 = FD-C3-24-27-4C-4C-56-01-62-1E-B2-AE-B1-F6-68-64-61-72-EB-2E-6D-F4-30-21-F1-8A-73-C6-85-38-25-FA
------------------------------
'Test ECC Alice secp384r1 SS' <=> 'Test ECC Bob secp384r1 SS'
> FAILURE < ECDH Keys are different!
SymKey12 = F3-55-B0-72-49-DA-A5-6B-D7-3E-B7-F5-87-E7-4B-D1-20-A1-6E-67-EE-FF-C2-A9-12-E4-B0-20-46-F7-A5-FA
SymKey21 = 8C-63-5E-21-AC-BB-C1-AB-17-73-E2-E9-4D-95-20-07-6A-60-69-B1-E6-3B-18-EA-B6-56-FF-38-9F-F8-46-2F
------------------------------
'Test ECC Alice secp256r1 SS' <=> 'Test ECC Bob secp256r1 SS'
Success, ECDH Keys agree
------------------------------
'Alice secp521 test cert' <=> 'Bob secp521 test cert'
> FAILURE < ECDH Keys are different!
SymKey12 = B3-90-1C-1B-B0-66-BB-D8-A2-46-37-A9-E4-84-1F-FE-B8-ED-14-17-A8-D8-0C-EB-20-A0-98-5F-3A-85-73-3D
SymKey21 = 44-62-AD-3F-DA-D4-7E-17-49-05-C4-22-93-DD-36-B7-0D-28-47-93-E5-D4-63-03-00-BC-F8-99-DF-BA-A3-92
------------------------------
'Alice secp384 test cert' <=> 'Bob secp384 test cert'
Success, ECDH Keys agree
------------------------------
'Alice secp256 test cert' <=> 'Bob secp256 test cert'
Success, ECDH Keys agree
------------------------------
Press any key to exit ...

Windows 8 output (version NT 6.3.9600.0)

'Test ECC Alice secp521r1 SS' <=> 'Test ECC Bob secp521r1 SS'
Success, ECDH Keys agree
------------------------------
'Test ECC Alice secp384r1 SS' <=> 'Test ECC Bob secp384r1 SS'
Success, ECDH Keys agree
------------------------------
'Test ECC Alice secp256r1 SS' <=> 'Test ECC Bob secp256r1 SS'
Success, ECDH Keys agree
------------------------------
'Alice secp521 test cert' <=> 'Bob secp521 test cert'
Success, ECDH Keys agree
------------------------------
'Alice secp384 test cert' <=> 'Bob secp384 test cert'
Success, ECDH Keys agree
------------------------------
'Alice secp256 test cert' <=> 'Bob secp256 test cert'
Success, ECDH Keys agree
------------------------------
Press any key to exit ...

Update: Fixed in KB3093266 (https://support.microsoft.com/en-us/kb/3093266)

Run the following in a PowerShell window to see if you have it ...

Get-HotFix -id KB3093266

Sources confirm that this is indeed a bug. The issue related to parsing PFX files in Windows 10 and Windows Server 2016 Beta when the certificates and private keys are initially installed.

The fix should be out in a security update sometime in Sept 2015. Honestly, we're pretty surprised to be the only ones really using elliptic curve crypto on Windows since ours seems to be the original report.


Trusted Platform Module (TPM) secure password I'm trying to set secure Trusted Platform Module (TPM) passwords on a network and would like to set it to the maximum length possible.

How long can the TPM's password be? Is it limited by bits or by characters? Does anyone has information about this?

EDIT: Yes, it's TPM 2.0 modules, embedded on Dell laptops and desktops mostly.It seems that it can be longer than 32 characters but I'm unsure about the (desired) max length. I'm thinking about using a random generator to set up the passwords. Right now I used the Windows' standard password generator for Bitlock.

I do not know much about this, my idea was to set a very secure TPM (and seldom change it) and change the PIN of bitlock protection more frequently.

The TCG spec doesn't impose any characters limit for the SRK and owner passwords as they are processed as hash values. Briefly, this means that for whatever password length, e.g. with TPM 1.2 it will always end up as 20Bytes/160bits (i.e. SHA1 hash).

In reality, the command line tool or the GUI you're using might add some limitations, e.g. the GTK GUI impose a 255 characters limitation on the password field.


How to check if a software is legitimate if I have a developer who wants to install a new software and he ask me to check this software security before installing it what shall I do

You could be asking one of many questions here.

If you are asking "How do I know that the software I have here is
what the vendor made - could it have been altered before I got it?"
then you will want to compare the hash of what you have to what the
vendor has published, assuming they have. (Almost everyone does
nowadays.)
If you are asking "How can I tell if the vendor has put malware or
back doors into this software?" then the key thing to consider is how
much you trust the vendor. (Although that's not a guarantee. Big
companies have accidentally gotten a virus on their gold masters
before now, and the bigger you are, the more likely a government is
to lean on you to put a back door in.) Of course you've scanned it
with a couple of AV scanners, like you do with anything you put on
your network. Talk to other users and see if they have any issues. If
it's open source, you can read the source before compiling, although
that is a huge amount of work. Lastly, you can run it in a sandbox
for a while, monitoring what it does, especially it's network
activity to see if it phones home.
If you are asking "How can I tell if it has programming mistakes
that make it vulnerable to attack?" then again there are various
approaches. As before, consider the reputation of the vendor; talk to other users; and if it's open
source and you have the resources, review the source. Check it's
bug tracking system if this is public, and it's historical release
notes, to see how well security issues are addressed. Think about
what it does and what threats you face, and identify other security
controls you can put around it.


SQL - using String concatenation, how can I exploit this procedure? I have a simple Stored Procedure:

create procedure [dbo].[test]
@str varchar (100)
AS
BEGIN
select * from [AdventureWorks2012].[HumanResources].[Employee] where JobTitle like '%' + @str +'%'
END
GO

Given this type of code, in what ways can I exploit it?

I've always been told that exploits of the sort of

exec test ''' ''; truncate table [AdventureWorks2012].[HumanResources].[Employee];--'

Should work, but now is the 1st time I got a chance to try it practically and it does not work.

The explanation I was given was that

''' ''; truncate table [AdventureWorks2012].[HumanResources].[Employee];--'

When concatenated with the query becomes

select * from [AdventureWorks2012].[HumanResources].[Employee] where JobTitle like '%' + ' ' ; truncate table [AdventureWorks2012].[HumanResources].[Employee];-- + '%'

So, the SELECT query will execute with the jobtitle searching for any character followed by a space. The ; terminates the where condition and then the truncate table statement executes. Where am I going wrong? I'm using Microsoft SQL server 2012.

where JobTitle like '%' + @str +'%'

This is not an SQL-injection vulnerability. It isn't injecting content into the query from a higher level of control such as a string EXEC or a call from C#.

There is an injection error here, however it is not SQL-injection. The concatenation that is being done is a search term into a LIKE query pattern. Metacharacters in LIKE patterns are %, _ and, in SQL Server, [ (non-ANSI-standard).

The upshot of this is that if anyone does a search for, say, 50%, they will get results that contain the substring 50 and not only ones that contain 50%. Use of [ can also probably result in a syntax error. That's undesirable, but it doesn't allow any of the traditional security attacks that SQL injections do.

To fix LIKE-injections, you need to nominate a custom LIKE-escape character, and use it to replace any LIKE-metacharacters, eg:

SET @liketerm = REPLACE(REPLACE(REPLACE(REPLACE(@str, '!', '!!'), '%', '!%'), '_', '!_'), '[', '![');

... WHERE jobtitle LIKE '%'+@liketerm+'%' ESCAPE '!';


Microsoft Office 2013 File Encryption To what extent can the native file encryption provided by Microsoft Office 2013 (Word, Powerpoint, Excel, etc.) be relied upon to maintain the confidentiality of documents, especially within the context of a Windows OS?

It also appears as though encryption does not remove metadata, such as the file's date of creation or date of last edit, and the frequent backups taken by Windows would leave me wondering whether or not an unencrypted version of the file is floating around somewhere on the system.

Can Microsoft Office 2013's native file encryption be relied upon, should an alternative tool (such as 7-zip) be used, or is the ultimate solution full-disk encryption?

When applications process data, they need it unencrypted in RAM, and the data will be copied to many places, including the hard disk as temporary files, or as part of the virtual memory mechanism, or hibernation. If you need to ensure that, once the machine has been powered down, its contents cannot be retrieved by an attacker with full physical access to the machine (the "stolen laptop" scenario), then full-disk encryption is required, with the following caveats:

When we say "full", we mean "full". The disk containing the operating system core files should also be encrypted, and the areas for virtual memory as well. That's what TrueCrypt calls system encryption.
This is valid only for a powered-down machine, not a system in "suspended" or "hibernated state".
Even after power down, some data which was in RAM could still be readable for a few minutes; this is the cold boot attack. For most usage scenarios, this is not a hard problem, but it still pays to keep that point in mind.

File-based encryption tools (e.g. what 7-zip offers) are meant for protections of files in transit, e.g. when the file is to be sent as an attachment to an email, or stored on a USB key. This is not the same attack scenario.


CSRF cookie vs session based tokens I will generate a CSRF token and include it in a hidden form field. When receiving the request, I will check the form value against the value either stored in the user's session or in a cookie.

Is it still considered acceptable from a security perspective to store this token in the cookie instead of the session?

Storing token in a cookie is not a solution to the CSRF problem. The CSRF vulnerability arises from the fact, that browser automatically sends cookies along with the request. As a result application considers that request as coming from valid (and authenticated) user. The only thing that attacker needs is the exact request that should be send. Introducing random Anti-CSRF token (request specific or session specific) causes it impossible (or just very difficult) to prepare valid request (in general case attacker doesn't know the valid value for anti-csrf token) and such a request will be dropped by server.

If you put your token in a cookie, it will be send to the server automatically, just as session cookie, so you don't get any additional protection from that.

EDIT:
I might misunderstood your question. You may be talking about so called double submitted cookies pattern where the same value is sent in hidden field and cookie.

Yes, this approach is acceptable when storing the CSRF token in session is problematic, you can read more about this here: Double Submit Cookies .


Why we store session id instead of user id inside cookies? Would not it be better to store user id instead of session id so that we only lookup database once for extracting other user info instead of twice extracting user id from session db then user db?

That would be a very bad idea because a malicious user could change the id they are sending.

If for example the admin has the id 1, and a user the id 101, that user could simply change their id in the cookie to 1, and thus gain admin privileges.

For the same reason, you would not want to send any other relevant data in cookies, as you cannot trust this data (unless it's signed and thus cannot be altered, eg using jwt).

You could of course generate random user ids. But even if we assume that these are unguessable, this would be problematic. It would essentially be the same as if you were sending the password in a cookie. If an id leaks even once, an attacker would gain permanent access as it is unrevokable. Session ids on the other hand expire after a while or can be revoked.


iOS app - hash user password in-app or on-server? I'm working on an iOS app that will also have a web component. When a user creates an account, their password will be salted and hashed. I already have the hashing algorithm working on the web-side.

When a new user creates an account in the app, should the iOS app hash their password and send that to the server to be directly inserted into the database? Or should their password be sent to the server in plain-text, and hashed there? Should it be encryted in-app, sent to the server, decrypted, then hashed? I'm just not sure what the best and most secure protocol is. I guess the same question goes for authenticating an existing user trying to sign in.

Also, at this point I don't have SSL set up on the server, but I'm certainly willing to do that if it helps with this.

Use SSL to handle the communications over the internet safely, then hash the password it on the server. Otherwise the password hash just becomes the password, as far as the service is concerned, and an attacker that gains access to your database can log in as any of your users as if their passwords were stored in plaintext. SSL is vital in order to prevent your users' credentials from being intercepted on the network.