How to secure usb data storage of Android phones? I just found out that if I connect my phone to a laptop with a cable, the password becomes completely USELESS. So how can I protect the data in my phone from a usb cable?

It's actually very easy to get in my phone, because all it needs is a stupid cable. That's a bit too easy.

So how can I protect the data in my phone from a usb cable? Can I give a password to the screen that enable usb storage? Can I add password whenever I have to access the file?

How can I do that?

Tips: Pattern is pretty easy to hack, not because I know how to hack, but because if you think about the combination of the pattern password, it can only have 9^2 combinations Max (and I did calculate the patterns that cannot be used, like some that you can NOT repeat the same number)

Actually, the maximum number of combinations an Android pass-pattern can have, given that the user must choose a pattern of at least four unique dots and can use up to all nine, is 9!+8!+7!+6!+5!+4! = 362880+40320+5040+720+120+24 = 409104 combinations, about 2^18.6. Child's play for a computer, made marginally more difficult by its being a UI-based entry scheme, and the cooldown period most Android phones have after 3 incorrect tries.

You can "lock" the SD card/SIM with a PIN that only allows it to be used in that phone by someone that has properly unlocked the phone. I'm not sure how easy/hard it is to break that layer; I would hope it's implemented via a decently-secure level of encryption.

In the worst case, Android phones support an option that wipes all data after 3-5 failed unlock attempts; if the data on the phone means more to an attacker than you, do this. Combined with encrypted phone and SD storage, this is about as safe as your phone's data will get. Most phone manufacturers and cell carriers provide offline backups; if your phone were to get wiped, you can simply restore the backup (restoration requires multi-factor authentication by providing a code they either gave you or that you gave them), and most of the things that make your phone yours are back in place. Other companies support remote wiping and/or remote bricking; report the phone as lost and the cell carrier will order the phone to factory reset and wipe the SD card, and/or to brick itself. Of course, the phone has to receive that command; you can work around it as a thief by quickly getting the battery out of the phone or putting it in Airplane mode, and then doing further work with it in a Farraday cage shielded from cell signal (It's really not as farfetched as it sounds, but it only works if the data the thief is after is on the phone itself and not somewhere the phone would give them access to).


How does TLS traffic impact firewalls? If I have an open port on a firewall it means that I can receive traffic on that port. If it's unencrypted I assume that the raw data is just allowed through.

If TLS is being used, does firewall decrypt the traffic before relying it to the client or does it relay crypted traffic to the client which then somehow decrypts it?

How does the firewall act with CRYPTED/UNENCRYPTED traffic?

Best regards,

If TLS is being used, does firewall decrypt the traffic before relying it to the client

Traditionally, no, for most definitions of "firewall."

  or does it relay crypted traffic to the client which then somehow decrypts it?

It just relays the packets, and the client decrypts.

I say "Traditionally" because there are other devices - reverse proxies, load balancers,  Intrusion Prevention Systems - which will decrypt the traffic and either pass along clear text or re-encrypt for the final hop to the client.  And many "Firewalls" today are hybrid devices which wear some of those devices' hats as well.

But in general, a "firewall" should just pass traffic, and doesn't manipulate the encryption.


Session Fixation - Is that even an issue here? Someone stepped up to me calling me out on not assigning a new session-ID on successfull login.

Basically i was told: The fact that i use the same cookie (with the same SID) in the login-page as well as the remaining authorized session makes my website vulnerable to session-fixation.

First of all, i don't even understand the term in this case: This has nothing to do with session-fixation, does it?
My SIDs are sent back and forth using HttpOnly and Secure HTML-Cookies. Meaning fixation by calling an URL with a certain SID wont even happen, because my website doesn't use URL-SIDs.

I could not think of any other way a session could be set by a potential hacker to his desires. The only way he could would require him to execute a JS from my domain and that would require the domain to be XSS-vulnerable, right?

And then again i also always bind a request-IP into a session, meaning once a different request-IP from the one already bound to the session is trying to use that session i will invalidate this session and kick the user out.

Am i being ignorant towards a certain circumstance here or his my website not vulnerable to session-fixation as claimed? I searched through quite a good amount of examples regarding session-fixation and i feel like i have no need to take any actions here?

This is a session fixation vulnerability, even if it may be relatively difficult to exploit.

You make a lot of assumptions before you conclude that everything is fine. Your assumptions are:

“An attacker cannot set a cookie in the victim's browser, except through an XSS vulnerability.”
“There are no XSS vulnerabilities anywhere in my application.”
“IP addresses are never shared.”

I disagree with those statements.

Setting a cookie in the vicitim's browser doesn't necessarily require an XSS attack. For example, if there's a subdomain hosting a different application, then this application may also set cookies for the main domain.

XSS vulnerabilities do exist in many applications, even when all programmers do their very best. What makes you think you're the exception?

IP addresses do get shared. There are proxy servers and VPNs with thousands of users, there are public WiFis, there are large networks behind a single IP address (thanks to NAT), there's the Tor Project routing its entire traffic through a few exit nodes, there are ISPs which constantly re-assign their IP addresses. So one IP address does not equal one user. How difficult it is for an attacker to actively take over the victim's IP address depends entirely on the concrete network environment, and that's obviously not under your control.

Of course you may be lucky and not fall victim to any of the above problems. However, relying on luck is a bad idea in security. In fact, we usually assume the worst-case scenario, and that's why it's standard practice to generate a fresh session ID when the user logs in.


my bruteforce prevention has major downsides - any ideas? I'm currently searching for the best way to prevent my software's webportal from bruteforce attacks and came up with the following idea:

3 login attempts without any visual challenge
after 3 failed attempts show Google reCaptcha
allow another 3 attempts but now you have to click the captcha every time
if the last 3 attempts failed again lock the account

My idea just has major downsides and I hope you could give some advice:

what happens if the username changes at every login attempt? which
account do I lock after 6 attempts?
how shall I log the 3 failed attempts (not dependent if those are 3 attempts to one account or one attempt for 3 different accounts) before showing the captcha?

IP? But what if lot's of people from a company network use the
software at once?
Browser user agent? What if someone who tries the bruteforce attack
simply changes the user agent at every login attempt?
Cookies?

Detecting brute force by user client behaviour alone is notoriously difficult. Due to distributed attacks, attacks against multiple usernames etc. means traffic patterns are hard to detect.

My recommendation, and the solution I use on almost all of my own systems, is to insert a simple delay into the process at the point of failure so if a user authenticates successfully it simply functions normally but for every failure insert a 2 or 3 second delay before declaring the failure.

For both humans and scripted clients (such as legitimate access to APIs etc.) this does not cause any issue, but for brute force attacks this slows the process down to an infeasibly slow speed even for every one of any likely number of parallel brute force threads (as long as passwords are complex of course.)

In addition, most server side languages release the CPU for 'sleep' commands and so this avoids this particular solution causing a DOS based on CPU time (though connection socket pools may still be an issue).


PHP type juggling with MAC I am trying to solve a challenge, and I suspect it has to do with PHP juggling, because I get this base64 encoded json cooke as a response {"User":"foo","MAC":"bar"}

  BUG #2

  The calculated MAC (i.e. the result of hash_hmac()) is a string
  containing hexadecimal characters

  The use of a loose comparison means that if an integer was
  provided in the JSON payload, the HMAC string will be juggled to
  a number

I think that with a MAC, for instance "ff6d0...5885d", the PHP juggling will be compared to int(6) since it is the first numerical. My idea wat to POST with the base64 encoded json: {"User":"Admin","MAC":6}

But this didn't work... does the juggling only work with MAC's that start with a numerical?

The algorithm PHP uses for coercing strings to integers is documented here. In particular:

  The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).

Your supposition was that:

  I think that with a MAC, for instance "ff6d0...5885d", the PHP juggling will be compared to int(6) since it is the first numerical

But the 6 does not appear at the beginning of that string, it appears only after the non-numeric sequence ff. So the value will be coerced to int(0).

If, however, we have a different hash, say "6ffd0...5885d", the 6 appears at the beginning of the string, so that string would be coerced to int(6).

As you surmised, this coercion can happen during comparison in certain circumstances, as described in the notes on comparison operators in the manual.


Two Factor Authentication with PIN - Does where/how you enter a PIN matter? Say I have two websites with 2FA mechanisms that are otherwise identical.

Mechanism 1

You have to enter a PIN into your Token Generator in order to retrieve your One Time Password. On the website, you then use your password and the OTP by itself to login.

Mechanism 2

On the other, the OTP is accessible just by physically having the device. On the website you enter your password and then [PIN] + OTP.

I wondered if there was a provable difference in the security provided by these two methods? Are they equal and is it purely a design choice, or are there further considerations to make?

For example, it's clear to me that in Mechanism 2 it's at least possible to have the PIN intercepted electronically. After which, an attacker would just need temporary access to your Token Generator to login. But then, if the attacker is physically local they could probably gain your PIN some other way (CCTV, shoulder surfing etc)

In the process of authentication the user enters a password (something he knows) and an OTP value, which was generated by "somehting he owns" - the token generator.

I think you can change the first compoment "something je knows" in this way, that is provides the same security level in mechanism 1 and mechanism 2.

In my opinion it is important to take a look at the possession, "something he owns".
So the question is, what kind of OTP generator are you using here? What are the attack vectors for this token generator?

Image you have a hardware token generator, then an attacker needs really physical access to the device. (Let us assume, that the secret key was not compromised during delivery of the hardware).

On the other hand, if you are using a software OTP generator like a smartphone app, the possession might be prone to additional attack vectors. I.e. Imagine the storage of the users smartphone being copied by an attackers rogue program.
Then it might be a good idea to use mechanism 1, and use the local smartphone PIN to encrypt the secret in the smartphone storage. This would protect against remote attacks on the smartphone storage - remote attacks on pyhsical hardware or "not possible".

So in my opinion: If you have a real possession factor, one that is not online attackable, you do not need a local PIN.

And: When logging in to the website you do not need Password + PIN + OTP. Two "knowledges" are as good as one knowledge. So simply use Password + OTP.


Is there a point to using user certificates instead of only using machine certificates? I've seen that user certificates can be stored on the user's computer just like machine certificates would.

I understand it would be very secure if the user had placed his private key on a smart card or USB, cause then it would always be with him, like on his key-ring alongside his house and car keys. So user certificates give him the benefit of being able to log in to the network from any device by using his security token. Perhaps that's the sole point of a user certificate? Idk.

But if you're not using tokens then the user certificate will be installed on the user's computer. That's far less secure than him just using a password to get authorized to the network. He can keep the password as a memorized secret inside his head. But with certificates, he has to store it on the computer. So if someone gets access to his computer he can export the private key. Then voila, that someone can now authenticate to the network with his own device using the certificate and private key he got off someone else's device.

tl;dr: Should you deploy user certificates if you're not planning on using security tokens?

TL; DR - Deploy user certificates and uncheck the allow private key to be exported option when deploying them. For added security, require users add a password to the private key.

Discussion

  I've seen that user certificates can be stored on the user's computer just like machine certificates would. I understand it would be very secure if the user had placed his private key on a smart card or USB, cause then it would always be with him, like on his key-ring alongside his house and car keys

If a user loses their smart card or USB stick, the certificate is compromised. It is much more likely that a user loses physical control of either of these keys, thereby compromising the key.

A USB drive has zero protection against exporting a private key. At least a smart card does not allow the private key to be exported once it has been written to the card.

  But if you're not using tokens then the user certificate will be installed on the user's computer. That's far less secure than him just using a password to get authorized to the network.

Depends on the password. A 47 character randomly generated password with upper, lower, symbols and numbers is going to be pretty strong. "Monkey" on the other hand...

From a math standpoint, user certificates are orders of magnitude more secure than passwords the average user will generally use. However, this depends on your password policy and user base, I suppose.

  But with certificates, he has to store it on the computer. So if someone gets access to his computer he can export the private key. Then voila, that someone can now authenticate to the network with his own device using the certificate and private key he got off someone else's device.

User certificates can be deployed in a manner that the private key is not exportable. Ensure that allow private key to be exported is unchecked.

For additional security, you can also add a password to the private key, but this lacks the convenience of automatic deploy via GPO. And, in all likelihood, you'll need to go around to each user and do this for them with domain admin and local admin privs.


Web sites executing local port scans: Is this coming from a library? Can it be blocked? I recently read a piece by an infosec analyst who observed ebay.com doing a local port scan.

I could not believe my eyes, but it was quickly reproduced by me (see below for my observation).

I surfed around to several sites, and found one more that does this (the citibank site, see below for my observation)

I further see, at least across ebay.com and citibank.com the same ports, in the same sequence getting scanned. That implies there may be a library in use across both sites that is doing this. (I have not debugged into the matter so far.)

The questions:

Is this port scanning "a thing" built into some standard
fingerprinting or security library? (if so, which?)
Is there a plugin for firefox that can block such behavior? (or can
such blocking be added to an existing plugin)?

Thanks!

ebay.com as seen by me:

citibank as seen by me:

Other sites I checked that did NOT seem to be doing this:

paypal.com: no
ups.com: no
fedex.com: no
https://www.bankofamerica.com/: no
twitter.com: no
facebook.com: no
duckduckgo: no
authorize.net: no
wellsfargo.com: no

Blocking WS requests

While looking for a way to disable websockets, I found two native Firefox solutions that do not work any more, then stumbled upon https://github.com/jawz101/TrackersVsFirefox, which mentions that one can block websockets with the uBlock Origin rule:

*$websocket

You can restrict this further to localhost only, but you have to come up with a pattern that matches all possible localhost references (for example, all IP addresses between 127.0.0.0 and 127.255.255.255 refer to localhost as well). I won't try to come up with such a pattern as I am afraid that there may be some exotic aliases that I am not aware of.

Testing the result

In any case, once you have the filter set up, you can try it by visiting https://www.websocket.org/echo.html and clicking the Connect button. To test blocking localhost connections specifically, you can run a dummy server that listens for incoming connections and try to connect it.

For example, on linux you can run netcat -l 4444 to listen on port 4444 and connect to it by specifying wss://localhost:4444 as the location on the WS echo page.

Without the uBlock Origin rule, you will see some gibberish showing up in the netcat output and the WS echo page won't show any output (because netcat is not replying to it, just displaying the request).
With the rule enabled, you won't see any output in netcat but the WS echo page will display the error "DISCONNECTED, ERROR: undefined".


Exposure of /etc/ssh, risks? I accidentally exposed the keys in /etc/ssh

What is the risk?

I think it will allow someone to impersonate the server and conduct MITM.

Will it let someone SSH into the server? I think not because they're not the private keys of the users

You are correct in your assumptions. The keys in /etc/ssh are the keys used to identify the server to the clients, so they cant be used to connect. They can however, as you also correctly states, be used to by someone to identify as your server.

You can generate new keys for the server and notify any users that there is a new key and they should trust it. Users typically store your servers public key in their ~/.ssh/known_hosts file, so this needs to be updated. This can be more or less of a hassle depending on how many users you have.


A standard way to manually add a digital signature to a pdf file? I've created a few certificates to use myself, but I find myself stumped when it comes to creating a certificate which contains a digital signature.  First, how would I go about creating a standard certificate which no longer contains only common fields, but ones containing a digital signature as well.  And second, how could I manually append this certificate as data to the corresponding pdf file?

Thanks!

According to your comments to other answers, you actually want to

  sign a pdf file with [your] certificate, then have this signature saved and appended to the pdf [you]'ve just signed.

(BTW, you sign with the private key associated with the public key in your certificate, not with the certificate itself, but that's a detail.)

I assume you want to "append" the signature to the PDF in a way that a standard conform PDF viewer (e.g. Adobe Reader) will recognize, display, and validate as an integrated PDF signature.

In that case you already started wrong by signing the original PDF as is and expecting to now have to merely somehow append that signature to the file. Instead you have to build a new revision of the PDF document which includes a PDF AcroForm signature field whose value is a signature dictionary whose /Contents entry contains the signature of the whole new revision with the exception of the /Contents entry contents.

If multiple signatures are to be integrated into a PDF, this is done by means of incremental PDF updates (explicitly not by adding multiple SignerInfo structures to a single integrated CMS signature container!):

This is explained quite graphically and in more detail in the Adobe document Digital Signatures in a PDF. It furthermore is specified in the PDF specification ISO 32000-1:2008 made available here by Adobe in section 12.8 Digital Signatures.

Be aware, though! The specification says:

  A byte range digest shall be computed over a range of bytes in the file, that shall be indicated by the ByteRange entry in the signature dictionary. This range should be the entire file, including the signature dictionary but excluding the signature value itself (the Contents entry). Other ranges may be used but since they do not check for all changes to the document, their use is not recommended.

This seems to allow that you first create a signature for the original PDF and then append a new revision holding that signature indicating that range of signed bytes only contains that original revision, not the extended revision without only the signature.

In reality, though, PDF viewers (especially Adobe Reader) will only accept signatures which follow the recommendation that the signed range should be the entire file, including the signature dictionary but excluding the signature value itself.

Newer specifications, e.g. the ETSI PAdES specification ETSI TS 102 778 (cf. section 5.1 item b in part 2 and section 4.2 item c in part 3) even make this recommendation officially a requirements, and so will ISO 32000-2.

Depending on your programming context, there are many PDF libraries supporting the creation of integrated PDF signatures and also many products using these libraries. Some of them are even available for free subject e.g. to the AGPL.


Use another ssl certificate even if server has other certificates I deployed a laravel project to a server (in which I have root access). Then I was asked to install a ssl certificate to that project. But there are some projects that already have installed a ssl certificate in the server.

My question is if I install another ssl certificate (for example: Let's Encrypt's free ssl certificate) only to my new project, does it break other projects' ssl certificates ?

It is first time that I am installing a ssl certificate so I am reading and watching videos, how to install ssl. I am afraid of breaking other working projects.

It will be good if you provide a safe procedure how to install.

  Server's OS: Debian,
  Webserver: nginx.

I can't communicate with server's administrator!

First, SSL / TLS is quite an advanced setup. you will need to research how it works and test it on another machine before even attempting to do it on a production machine.

If you have a modern setup, (e.a. you have an SNI aware webserver, and clients.)
you can setup multiple TLs certificates, see the NGINX documentations regarding virtual hosts and multiple SSL.

To test with Ceritficates you id not buy, but only use for Testing / Development (ea. NOT PRODUCTION) you can use mkcert or xca.

the last thing I would recommand after you tried your setup on the production server, is to use a service like ssllabs to validate your setup. (do it for ALL domains with TLS in your server)

as a footnote to get a good cipher suite list, try cipherli.st


Is it possible to hack a SSID without actually having to sniff or send deauth frames to a host? I'd like to know if there exists at least the possibility of a known/theoretical attack on a wireless SSID that does not involve a host within the network, what I mean by this is that some of the common ways of obtaining network access requires a host as a victim either for evil twin attack type or a handshake capture by deauthenticating said host, however, I'd like to know if any of you know ways around this.

Let me explain the scenario:

I've no physical way to reset the router and by this means, reconfigure it to service me only.
I've already discovered the router's SSID.
There are no hosts currently attached to the SSID's network.
I cannot do a bruteforce attack on the possible SSID's password because the router may "tag" my MAC address and just lock me out of trying to authenticate again.

So the scenario takes out any host that we can use as a leverage for the pentest; if someone has any experiences or knowledge of what to do in this type of scenarios I'd appreciate it.

If the network is WPA2 as you sais in comments, this is what you can do:

You didn't specify if there is WPS enabled or not. So check that using wash (included on reaver package) or using --wps on airodump-ng. Then if enable you can try Pixie Dust attack (very fast but only affecting some Access Points, maybe you could be lucky). Also you can try bruteforce on PIN or an attack based on a PIN database.
Another way to hack it is getting a Handshake and then cracking it offline. To do that, you must be "listening" with airodump-ng while a legitimate client connect to the network. It doesn't matter if the SSID is hidden. You'll get the handshake anyway and you'll crack it offline based on BSSID. To obtain it, the common method is using DoS deauthenticating client but your question said "without send deauth frames". So if you want the Handshake without DoS you only can wait, wait and wait... until a client connect to get it. You sais there is no clients connected to the network. Maybe you can only set the "listening" and wait for days... Once you have the Handshake captured file you can crack it without fear of being detected or whatever, is an offline proccess. You can use aircrack or hashcat tools (or maybe other).
Another possibility is to create a Rogue AP Evil Twin with a captive portal hoping the victim confuse the network and put his/her wireless password on your trap. This attack requires a little bit of "social engineering" and a victim without any knowledge about networking (but believe me sometimes it works!). Is usual again to perform DoS to the legitimate network to force them to investigate and maybe they can make click on your fake network. Again without sending "deauth frames" is very very difficult to be successful with this kind of attack.

Of couse you can perform all of these actions with your MAC spoofed to be pretty sure of you are not being detected.

I'll recommend to you a tool what can do ALL of these attacks: airgeddon

Hope it helps!


Is it dangerous not to verify the signature of an id token issued by an external authorization server? I need to retrieve some values from an id token issued by an external authorization server inside a private network.

I asked for the certificate used to sign the jwt in order to verify it but I've been told there is no need to do so. The main argument is that there is no threat of someone compromising the response of a request on a tcp/ip connexion, and thus the jwt can be trusted.

I am still not totally convinced given that the connexion is not using TLS/SSL.

What are the possible threats?

As general rule, you should validate the signature on JSON Web Tokens whenever they are used, as this is the model of security around which they are built. There is absolutely no doubt that verifying the token is a better implementation, and even if the risk is low now, having verification in place will be a better security posture to build on for the future. Another developer down the road may assume you were verifying the token and that could cause a vulnerability even if there is not one now.

Note: Some of my opinion will be controversial to people who feel security should be absolute. I'm personally of the opinion that security needs also to be practical in order to be effective. You shouldn't spend $1000 on a safe to protect a $1 chocolate bar. But conversely, if you are dealing with valuable assets like financial information or personally identifiable information, you should certainly take appropriate precautions.

Risk

It is up to you in your implementation to determine whether it is worth the risk to skip verification.

Are the fields you're retrieving for access control, or purely for informational purposes?
Do you have alternate mechanisms in place to verify the token before this system accesses it?
What are the risks involved if the token was forged? Information disclosure? Privilege escalation? Injury or loss of life? Inaccurate security log entries?

Transport Encryption

You mentioned that it is passing over the network without TLS. I presume that is on the internal network only. A lack of transport encryption on a private network is not ideal to say the least, but you'll again have to weight the risk factors of what the token is used for to decide if this is acceptable. It will also depend on whether you trust the other security controls applied on your network - which you probably shouldn't, but you could have very good network security engineers and still not being using TLS... I don't have that information.

If it is passing over the public internet without TLS you should not trust the token at all, as it may have been compromised.

Not having encryption in transit for security tokens does expose you to a whole range of threats related to spoofing, tampering, and information disclosure. IP networks route over multiple hops, and without encryption and digital signatures provided by TLS someone could - amongst other things:

intercept the request before it gets to your 3rd-party authorization service and return an entirely forged token with more privileges
intercept a valid token in transit and alter it to have more permission than it does
steal the token in transit and inject it in requests to authorize other requests

Signature Verification and Secrets

Note also that HMAC signature methods use a pre-shared key rather than a public key for verification.

In your scenario, if an attacker stole the token you are handling, it would authorize them to do whatever that token can do. But if they managed to steal the pre-shared key, they could generate an HMAC signature for a token with any identity or permission scope in your system.

That's a risk as well, so if it's not actually essential to verify the token in your given context, it may actually be a reasonable measure to keep the shared key out of play to avoid the risk of exposure for the more valuable secret. It's all a balance of risk.

Note also that this risk does not exist for public-key or certificate-based signature methods. The key needed for verification in these cases is intended to be shared publicly and there is no risk associated with storing that information.


Typed my password on Google search box by mistake. What happens now? By mistake, I copied and pasted a password into Google Chrome search box on my personal computer, a Mac computer. However, I did not press enter or click search button/magnifying glass. Is my password compromised, should I change it.
Thank you.

What happens now? You should change your password.

What happened when you entered it in the Google search bar without clicking "Google Search" or Enter? Each character of text was sent (over HTTPS via GET Request) to Google which may or may not have provided suggestions on additional characters or words to enter for your search query.

You can see this live in the Chrome DevTools (press F12) as you type. Go to the "Network" tab and begin typing characters. You'll see each new character append the last request and the GET Request send off to a Google-owned IP address. You can also see the returned suggested searches in the Response tab.

Ultimately it comes down to whether you trust Google with the password you entered. In all likelihood is anything going to happen as a result of this / is your account going to be compromised? Probably not. But it is good practice to reset it given that this behavior can happen on any website you visit anyway.


insecure HTTP session issue A java based application supports two user roles. Admin and nonAdmin.

Login as Admin ,browser gets JSESSION ID.

Login as nonAdmin user from another machine. Browser gets another JSESSION ID.
Now edit this JSESSIONID and replace with  Admin's JSESSION ID. This time a nonAdmin user get to see the options meant for admin user alone.

is this session fixation vulnerability? is it enough to bind other client side properties like IP address along with SESSION Ids? or setting new session id after successful login helps here?

As @Arminus said in a comment, this is not session fixation. Session fixation is actually relatively rare today, because it relies on one behavior now (thankfully) widely recognized as insecure/stupid: when you log in, the server preserves the old token (JSESSIONID, in this case) rather than generating a new one. An attacker can abuse that by knowing the old token value (for example, because they were the last user) and then logging out and waiting for a new user to come along; when the new user logs in, they keep the old token.

A security vulnerability requires that somebody do something that they are not authorized to do. In your scenario, how the heck does the nonAdmin user find the Admin's JSESSIONID? If they're the same person, then the user is (presumably) already authorized to log in as an Admin - they did so on the other machine, after all - so no security bypass has occurred. If they aren't the same person, either the nonAdmin stole the Admin's JSESSIONID (in which case the security vulnerability is in how they stole it, which might be your fault or might be because the Admin user's computer has spyware), or the Admin user shared the JSESSIONID with the nonAdmin (which means the Admin is, essentially, deputizing the nonAdmin as a temporary user of the Admin's account).

Authentication tokens (JSESSIONIDs, in your case) have a number of critical properties. The following list is in no particular order. The relevant ones here are highlighted:

They are securely generated (i.e. don't use java.util.Random, which has predictable output; use java.security.SecureRandom). Some implementations use encrypted user-info strings instead of random tokens; this has some pretty bad security risks.
They are long enough that they can't be brute-forced (64 bits is generally seen as borderline; 128 bits and up is good).
They are never re-used, so an attacker who sees an old one can't use it to get somebody else's session. Since keeping track of all the old session tokens is infeasible, the solution is again to use a long-enough (random) token that the odds of a collision are infinitesimal (and if you express the odds against it happening using words like "billion", it's not infinitesimal enough).
They must be checked in a constant-time manner (otherwise brute-forcing a valid token becomes linear in its length, rather than exponential).
They must not be shared across privilege levels, or sessions for a given user. Any time a user re-authenticates, the old token must be invalidated and a new one used instead.
Token invalidation must occur on the server. If a user logs out or their session expires (or otherwise ends), the server must no longer recognize the token as valid. Simply deleting the token off the client is not sufficient.
Tokens must never be sent in a URL, only in headers or if necessary in message bodies. Even over HTTPS, URLs tend to leak (they may be recorded by proxies, included in referrer headers, or saved in browser history, among other risks). If a secure value absolutely must be sent in a URL, it must be single-use only and invalidated after the first attempt to use it, whether or not the user completed their action, and should also time out very quickly.
Tokens must never be sent over insecure connections. If your site supports HTTPS, then the token must never be sent over a non-HTTPS connection (an easy way to ensure this is have the token in a cookie, and set the secure flag on that cookie). If your site doesn't support HTTPS, then treat sessions as convenience only; there is no real security there. (Yes, looking at you, SE default post-authentication behavior...)
I'm probably forgetting some, but a comprehensive list is not the core point here. Still, as you can see, there are a bunch of things (some related, some independent) required for a secure authentication token, which is just one component of a secure site. You have to do them all; one weak link is usually enough for an attacker to get in.


Why not crack a password a character at a time? Brute force can be used to crack passwords by trying a large number of passwords.
Why does no one try the brute force approach on every single character of the password instead?

Because most operating systems hash passwords once entered (and store them in a database).  This means that the entire password is converted into a collection of cryptographic hashes, random-looking strings of characters into which the passwords have been mathematically transformed to prevent them from being misused.

So, once a password is hashed for a well defined hash, there is no way to attack each character.  That is circular logic. To attack each character you must know each character.  To know each character you must attack each character.


Requiring hardware key at boot-up on normal laptop I am sure that a question like this already exists and has probably been answered. I just couldn't find any results (probably due to my inability to word my question correctly).

We use laptops at work which require a hardware key (a USB) to boot the computer along with a username/password. It then boots to Windows and a different USB/Username/Password combination is required.

I am already aware on how to implement the second security feature (the windows login requiring USB as well) but can't find any information on implementing a USB requirement to pass through the boot-up process. It's very similar to having a BIOS password, though requires a USB/Username/Password combination and therefore more secure as requiring a physical token.

I am trying to implement this to provide higher than usual BIOS level security. I don't want the machine to be able to be used WITHOUT the physical access token and am not concerned with HDD security (i.e, the OS itself) as I have already implemented significant security onto that already.

i.e if somebody connects an external HDD and tries to boot onto that instead of the build in HDD (which has OS-level security), I want them to require a physical token to do so along with a username and password

The startup process should therefore go like this:

    1. Power on
    2. Insert USB (this is my issue)
    3. Enter Username/Password
    4. Boot to Windows
    5. Insert seperate USB
    6. Enter Windows username/password
    7. Login

There are several FDE (Full-Disk-Encryption) solutions that implement a pre-boot authentication (PBE) layer.
I personally only have experience with Sophos SafeGuard Easy. They are used mainly in security aware environments like military or public security.

The replace the standard boot-loader whichs provided by Windows or Linux with their own bootloader. After sucessful authentication the PBA decrypts the volumes and starts the normal bootloader.

There are several authentication methods possible, either with a smart card, a username/password combination or a YubiKey.
In the Sophos SGE solution a sync with all domain accounts on the machine is done and you can authenticate with your domain password.

In the YubiKey solution a USB-Stick is used. YubiKey with FDE

The same or another yubikey can then be used for the Windows-Logon with One-Time-Passwords.

For your process a look at the mentioned EgoSecure Solution on the Link provided may be useful.

For preventing boot from an external hard drive, the standard solution would be deactivating boot from USB in the BIOS Settings.


Is there any recommended approach for "upgrading" MD5 hashes to something secure? I'm currently dealing with a couple of user accounts containing MD5 hashed passwords. These accounts got migrated from an old system into our current system which uses PBKDF2 for password hashing. I would like to lift the old accounts to PBKDF2 password hashing as well.

Cracking our own MD5 hashes and rehashing them with PBKDF2 is out of the question.

The first thing that came to mind was migrating the user passwords at login, as described here.

However, I would never be able to migrate all user passwords because some of the users might never return and thus never login again, leaving me forever with insecure hashes.

So two options are left:

Resetting all passwords and informing the users via email
Hash the MD5 hashes in the database again with PBKDF2 and use this double hashing when a "legacy user" logs in. Meaning PBKDF2(MD5(plaintext)).

First solution would be really unpleasent for the users, because they would have to set a new password, so I'm tending towards the second solution.
This seems to support this approach, although talking mainly about bcrypt and not PBDKF2

Is wrapping MD5 in PBKDF2 (or, for what it's worth, other secure hashing algorithms) something that safely can be done, or are there better approaches for dealing with old, insecure MD5 hashes?

Yes, double hashing can be safely done, to give the older MD5 hashes more protection immediately.

Just make sure you can distinguish such double hashes from regular hashes, and update them as soon as possible. The verification process should be done differently for the two kind of hashes, otherwise leaked md5 hashes could be used directly as password, tried to explain it in this answer.


Are there any instances where AES CBC + HMAC is preferred over the AES GCM mode? I am just curious as to what extent AES GCM can replace the standard CBC + HMAC option.

There are quite some advantages to GCM, for one it allows for parallel processing which makes it efficient and usable for simultaneous hardware operations. Since you compare GCM to CBC+HMAC, I will point you to the GCM GMAC extension. GMAC is the HMAC variant but is uses a Galois field instead.

A predefined Galois field, say GF(2128), can be computed independently over an polynomial, whereas CBC chains blocks based on previous results. This gives GCM a high throughput, and makes it very efficient.


What information should I provide to third party pen testers - (black box penetration) I am going to hire a third party security company for Penetration testing in our company network.  I have already selected a pen testing and black box testing company to do them, but they have requested details regarding our network including; network setup, intranet, What data should be provided to them? and what data should not provided?

Given that the penetration testers have a limited amount of time (since you provide them with a limited amount of money) they can do a better job in that time the more information they have from start. Thus, if you are interested that they actually help you to increase your security you better give them all the details they want.

If instead you want to have a result which says that they did not find much in the time they had, then make their job as hard as possible and provide no information at all. But while such result might look good in a management report it will likely not reflect the true (in)security of your network.


Are security keys with touch requirements more secure than those without? My friends and I have worked at various tech companies which required us to use a security key in order to login to our computers. Some of us had to physically "touch" the device to login, while some of us at other companies did not need to touch our key.
Does the addition of having to touch the security key add any additional security? If so, how? If not, what is the purpose of it?

Touch is the one thing
that cannot be forged
The idea with hardware security tokens is that secret crypto keys are stored on the token itself. Even if the computer/device it plugs into is compromised, the secret keys cannot be stolen.
Usually, PIN entry is required by the token in order to start performing cryptographic operations. For convenience/usability, the PIN is often cached for a period of time, not requiring re-entry during this time.
Imagine that you use your security token to sign code, decrypt secrets, or SSH into servers. Once the token is unlocked, any of these operations can take place without further user interaction.
Now imagine your computer is compromised. Once you've entered your PIN, the attacker may be able to perform the above cryptographic tasks using your token without your knowledge. Even if you require the PIN on every operation, the attacker could keylog or capture it, and possibly present it for unlock.
Here's where the touch feature comes in handy. By requiring a touch, the token won't perform any cryptographic operations without confirmation from the user physically sitting at the computer. Of course, it doesn't protect against a physical attack, but that's already game over.
Now, while this gives a layer of protection against inadvertent or malicious operations with your secret keys, a remote attacker is not necessarily foiled by it. They may still backdoor your tools to insert malicious code into signed commits, copy your decrypted secrets, and hijack your SSH client to gain access to your servers.
I'd guess that it provides little to no benefit if you are only using it to log in locally.


Can you prove to a 3rd party, that a HTTPS TLS session took place? Alice is a (potentially modified) browser/client.
Bob is a non-modified HTTPS web server running common security practices.

Eve is collecting data from Bob from many Alices, Eve needs this information to be accurate, and Alice is happy to supply the information as they get paid. Eve however needs to verify the information was sent by bob, and not a scam attempt by Alice to make quick money.

Alice however does not want Eve to know their cookies etc and gain control over their account.

Can Alice prove to Eve that the data in a https / tls exchange came from bob, and that they didn't fake the data. And if so, can they do so without Eve stealing their session/cookies.

While TLS identifies the server and protects data against sniffing and modification it does not contain some kind of proof that the server sent specific data which can be used outside the TLS connection. This means if Alice could capture the full TLS traffic, extract the encryption keys and hand all of this to Eve, then Eve could actually verify that the data was sent by Bob (or at least somebody in possession of Bobs private key) but, they could also get the rest of the traffic, i.e. all the cookies etc.

To achieve such proof Bob would actually need to sign the relevant data (and only this data) outside of TLS so that Alice could hand over the signed data to Eve which could then verify the signature using Bobs certificate.


cant a CSRF token be stolen using iframe? from what I understand a common approach to storing a CSRF token would be:

the client retrieves from the server a CSRF token
the token is stored in an input element inside the form like this:

<form>
<input type="hidden" name="token" value="abc123supersecrettoken">
</form>

my question is, would an attack like this be possible, and if so, how can a site be protected:

user logins into facebook.com
user goes to evil.com, the site has he following iframe:

<iframe src="https://www.facebook.com/changeUserPasswordForm"></iframe>

with some basic DOM manipulation on the iframe, the CSRF token could be accessed by the attacker

would an attack like this be possible

This would not be possible. The Same Origin Policy prevents cross-origin reading. This applies also to an iframe from a different domain which is embedded in the current page.


Can I safely re-use an old, possibly compromised, hard drive? I have a 1TB Seagate hard drive (old-style spinning disc :) ). I want to repurpose it if I can do so safely.

It was as originally the primary system drive on a Win7 laptop. It may well have been compromised by viruses, etc.

I wish to use it as the boot drive for a new Debian installation on an old laptop. I'll use encryption, strong passphrases, etc. The laptop will host a full Bitcoin Core client, amongst other things.

My initial plan is to simply remove the existing partitions then using dd to write over the entire /dev/sdx device. Then I would let the Debian installed build it back up.

Will this protect me from any evil stuff that may be on the drive?

Is there something more I should do to clear the MBR, etc?

It's unlikely that the hard drive itself was ever compromised, just the OS installed on the hard drive, which means it should be fine to format it and re-use it.

Simply doing a single pass with dd should be enough, no need to remove existing partitions as dd would overwrite the partition table anyway. Really, I don't see how there'd be much danger in just creating a new partition table without even wiping the data.

Note that it is possible for a hard drive's firmware to be compromised (a quick google will turn up plenty of stuff about the NSA), but as far as I know, if you're using full disk encryption (eg LUKS) the unencrypted data will never be sent to the drive, so data theft shouldn't be a big concern there (although that assumes you encrypt /boot as well, if malicious firmware can modify your kernel you're hosed).


Isolated safe anonymous OS I wonder about a setup where I can have a primary OS on my Laptop, but keep a second OS that is safe, anonymous, persistent and isolated (for sensivite data that may communicate with the outside world).

The idea is that I can use the second OS to use the internet anonymously and keep private data that I don't want linked with my person in case my primary OS becomes compromised.

A Virtual machine wouldn't do it because a compromised host would have access to it. So I am thinking a dual boot with something like Whonix as encrypted secondary OS would be the safest option.
In this scenario, there is still a risk of a compromised Whonix having access to the primary OS partition, but is mitigated by the inherent security (Inernet connection via VM).

Are there simpler solutions for maximum security to isolate sensitive private data from everyday computer use not involving dual boot? Is there any caveat in the use that could lead to cross-contamination?

There are already some projects developed that are targeting your goal of safety. You should look at my old post.

For Type-2 hypervisors, there is RoboLinux project which has an unique feature called Stealth VM. Stealth VM software installer that allows you to build a Windows 7 clone running in a secure Linux partition. The system is protected from malware, anything you download will be contained within the virtual machine and it is intended for people who must have a specific Windows program with the convenience of being able to restore the operating system as new in just two clicks.

There is Qubes OS which is developed on Linux and Xen as an example for Type-1 hypervisors. Qubes OS takes an approach called security by isolation, which in this context means keeping the things you do on your computer securely isolated in different VMs so that one VM getting compromised won’t affect the others. Unlike Type-2 hypervisors, it has a secure inter-VM file transfer system to handle sharing folders' risk. In theory, that organization is more secure than Type-2 virtualization according to developers.


is there any program that can tell me which files have been transferred from my computer thru the web Is there a program that can tell me which files have been transferred from my computer thru the web?

So if I have virus on my computer that transfer files I will know about it according to the files list that have been transferred.

Depending on what you want exactly, you can use an IDS, like Snort, to record and alert based on certain criteria. Wireshark or tcpdump can also be used with filters to log file transfers.


Security risk of encrypting the same data with many public keys I need to distribute a shared 256 bit key to 100's or 1000's of nodes (I have the public key of each node).

There's no networking involved - this will all be done by loading a single file on to each node.  That file is generated by a "master".

In some cases, the nodes use 2048-bit RSA keys, and others it is a p521 Elliptic Curve key.

The idea is to create a line for each node in the distributed file encrypting the shared key.

If the node uses EC, then the node's public EC and the master's private EC keys are used to generate a symmetric key which is used to encrypt the shared key .  The encrypted shared key and signature generated by the master are stored on a line in the file.
The node would then loop through each line in the file, use the master's public EC key and its own private EC key to generate the same symmetric key, decrypt the data, then check the signature.  If correct, then that is the shared key.

If the node uses RSA, then the shared key would be encrypted with the node's public RSA key, and a signature generated by the master and both stored on a line in the file.
The node would then loop through each line in the file, use its private RSA key to decrypt the data, then check the signature.  If correct, then that is the shared key.

My worry is that does knowing that a single piece of data being encrypted with 1000 different keys give an attacker a significant advantage for deriving a private key?

Depending on the used implementation, using RSA with the same input and different keys could be a problem. If all your keys have the same exponent e, a variant of the coppersmith attack (Håstad's broadcast attack) is applicable: https://en.wikipedia.org/wiki/Coppersmith%27s_attack


The Need for includeSubDomains in HSTS RFC I am trying to understand the includeSubDomains directive in the HTTP Strict Transport Security standard. In particular section 14.4 of RFC 6797 confuse me.

Point 2. says

  The HTTP request sent to uxdhbpahpdsf.example.com will include
         the Secure-flagged domain cookie.

This seems to imply that if a domain cookie has been set as secure, it may in fact be transmitted to a server before the certificate of that server has been validated. That would completely defeat the purpose of setting the cookie to be secure in the first place. If that's not the case, then what am I misunderstanding in that paragraph?

Point 3. says

  and the user "clicks through" any warning that
         might be presented

This seems to imply that the threat scenario would only apply in case the user ignores security warnings or a CA signed a forged certificate. But if either of those were the case, the attack could just as well have been targeted at the example.com domain.

What is the connection between includeSubDomains and that paragraph? Point 3. only deals with a scenario, where the communication is passed over HTTPS anyway, which means HSTS wouldn't make any difference.

I think the way to read those three points is as three parts of one vulnerability, and are best read in a different order. HSTS does make a difference on HTTPS connections, and in fact a very significant one: HSTS does not allow users to click through a warning from the browser. All certificate validation errors with HSTS are fatal; the browser will not allow the user to add an exception, which is the biggest issue with relying on certificate warnings alone to prevent MitMs. So, if the attacker registers that subdomain, the issue is (in different order from in the RFC):

The attacker's site serves up a TLS certificate. If it's considered a valid certificate by the browser then HSTS doesn't help (because HSTS doesn't include pinning), but it's likely going to be an invalid certificate.
The web browser warns of a certificate issue. Because the subdomain doesn't have HSTS set, the user can add an exception or otherwise override the certificate warning to go to the site.
The domain cookie is sent to the attacker's server over the TLS connection.

With includeSubDomains, the following happens:

The attacker's site serves up a TLS certificate; again, if it's valid, the user is hosed.
The browser warns of a certificate issue. Because HSTS is set, this is a fatal error. The connection is terminated before an HTTP request is sent.
There is no 3. The connection was terminated in step 2.

(As a side note: certificate validation always occurs during TLS connection establishment; no HTTP requests are sent until after TLS is established. So no cookies are ever sent over HTTPS before certificates are checked.)


Is it possible to protect the emails and calendar in an Exchange server against own Exchange administrators? We have our Exchange server in a remote site administered by an external provider. We would like to avoid the possibility of provider employees to access the email and calendar of critical accounts in this Exchange server.

The inmediate solution we see is using PGP in Outlook but the problem is that we would like to protect also emails that the sender does not send encrypted.

For example, there exist a module in Exchange that inmediately encrypt an email when is received, store it encrypted and only the receiver may access the email unencrypted?

Another possibility is not using an Exchange server but use some solution in the cloud but in that case it is neccessary to blindly believe the provider when he says that their employees are unable to access the emails...

You cannot truly protect mail from the Exchange admin if they have Exchange Domain Org/Enterprise access.  If their intent is malicious, they can bypass delivery methods, and impersonate users, bypassing transport encryption.

PGP would work for receipt only and in the case the sender is also honoring the PGP methods needed.  An admin could email the person back as the user and say "my PGP is screwed up, can you send that unenecrypted" and 9 out of 10 times, the sender would comply.

Any cloud method is going to fall into this category as well.  In order to effectively administer most systems like they, the admin will have keys to the kingdom.  You can have auditing in place that would at least monitor administrative abilities so you could see other people accessing mailboxes or impersonating users and then you can require access to these functions.  Exchange 2013's DLP (data loss prevention) has gone a long way since 2010.

https://technet.microsoft.com/en-us/library/jj150527(v=exchg.150).aspx

I would start there so IF someone was trying to be malicious, you could track it.  But again.... if they wanted to, they can turn this off and be on their way before the other admins find out.  You either have to have strict contracts in place that give you massive legal repercussions against the hosting provider, OR choose a provider that is complying with compliance requirements.  They have to have auditing and process control in place that would make it MUCH harder for admins to carry out malicious duties.

TLDR;

There's no perfect method to prevent a full admin from being malicious for most mail applications.


What to look for in baby monitor? There are, from time to time, stories in the media about baby monitors being hacked. The hacker can for example gain access to the video feed and be able to interact with the monitor.

While I understand that completely protecting yourself from any type of hack, my basic question is: What are some things that one can look for in a baby monitor (audio and video) that will help prevent a hacker from gaining access? (I am assuming that no one untrusted has physical access to the monitor.)

I understand that just because a monitor has a feature it is useless unless it is used.

As an example: some monitors use WEP, but from what I can guess, this actually isn't safe(?)

The most common things are default configuration and outdated software.

So, in order to be safe, first be sure that you are using the latest software provided by the vendor.

Then change the default configuration. This include users and passwords, ports and any other relevant option you see.

Finally, be smart. Don't allow external traffic to that device if you are not going to use it outside of your home.

Basically, "hacking" of these kind of devices follow the steps I just described:

Use Shodan to scan for the device (that is, the device is reachable from Internet)
Try to log in using well-known default users.
Look for the software version and check if there is any vulnerability reported for that version, and if that's the case, check if there is an exploit available for it.


How can i cause a redirect in browser? I'm able to edit a parameter which is then reflected inside a link. I'd like to know how and if it's possible to cause a redirect. In shorts when i edit the parameter example like this example=/test.com that value is reflected in generated link like: www.example.com/test.com but when i open the link the browser loads www.example.com- Is it possible to make it load test.com instead?

I tried using @test.com but that generates a 500 error message. It seems that there's a check in place that blocks everything if you don't use the slash symbol first. For example /@test.com is accepted but not @test.com - How can i inject in a way that once the link is clicked i get a redirect to test.com?

Breaking down the request/responses:

For /@test I receive a 500:

{
    "statusCode":500,
    "error":"Internal Server Error",
    "message":"An internal server error occurred"
}

And if I try with /@test.com I get this:

{
    "success":true,
    "link":"https://www.example.com/@test.com"
}

It looks like the have some basic input checking going on that is rejecting your response (although it is always possible that your @ is actually generating an error on their end for some strange reason).

Since it allows a request with an @, just not as the first character, I'd try a few things:

Try using a URL-encoded @ which is %40.  If their input checking logic has some flaws it make make it through and allow a valid payload.
Also, credentials can come with a username and password.  A colon is used to separate the password.  Therefore try this something like this: :user@newdomain.com.  If you're lucky that will result in https://www.example.com:user@newdomain.com which should accomplish what you want.
Like before, also try with an encoded colon, just in case: %3Auser%40newdomain.com

However, I'm just guessing at what their input validation rule is.  In cases like this it becomes a guess-and-check to try to figure out what they are checking for, and then some more guess-and-check to find a payload that circumvents their rules and also gives you something useful.

It's possible that the actual rule is that the URL must begin with a front-slash.  In that case you are probably left modifying the URL to only point to arbitrary URLs on the target domain, which is less fun.  I check this by attempting simple payloads like test (without any special characters or slashes).  If that also gives a 500 then they probably require starting with a front-slash, in which case I think you will be stuck.  It's also possible that they always concatenate your payload with a forward-slash, in which case (again), you are probably stuck.  That would be the case if you inject test and they return https://www.example.com/test.


CryptoAPI to CommonCrypto with RC4 I have cryptographic code used in the Windows platform, which uses the Crypto API functions and need to convert this to using Common Crypto on OS X.
Essentially the original code is this, with error checking removed for brevity: -
CryptAcquireContext(&m_hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT));
CryptCreateHash(m_hProv, CALG_MD5 ,0, 0, &hHash);
CryptHashData(hHash,(LPBYTE)pszInputData, lstrlen(pszInputData)*sizeof(TCHAR), 0);

CryptDeriveKey(m_hProv, CALG_RC4, hHash, CRYPT_EXPORTABLE | 0x00280000, &m_hKey);
CryptDecrypt(m_hKey, 0, bFinal, 0, pData, pdwDataSize);

As far as I understand, this is what's happening: -

CryptAcquireContext - Get an object to handle the cryptography
CryptCreateHash - Create an MD5 hashing object
CryptHashData - Hash the input data with MD5
CryptDeriveKey, CryptDecrypt - Decode pData with RC4, using the key m_hKey

The size of pszInputData is 12 bytes and the output array of the MD5 hashed object is the same on both platforms.
To decode with RC4, I'm doing the following with Common Crypto: -
CCCryptorRef cryptor = NULL;
CCCryptorCreate(kCCDecrypt, kCCAlgorithmRC4, 0,
                      (void*)m_hKey.data(), m_hKey.length(), NULL, &cryptor);

char outBuffer[12];
size_t outBytes;
CCCryptorUpdate(cryptor, (void*)pData, *pdwDataSize, outBuffer, 12, &outBytes);

Testing the output (outBuffer array) from Common Crypto with an online RC4 decoder matches, so this is decoding correctly.
However, the final output from the Windows code in pData doesn't match the RC4 decoded in Common Crypto.
Are there some steps I'm missing or not understanding with the Windows Crypto API calls here; why do the outputs differ?
(Please note, I'm not looking for comments on the security or flaws in using RC4)

According to CryptDeriveKey() documentation, upper WORD of dwFlags parameter specifies desired key size in bits. In your case it should generate 40-bit (0x28) keys, effectively discarding all but first five bytes of the MD5 output.

To achieve similar behavior with CommonCrypto you can try this:

CCCryptorCreate(kCCDecrypt, kCCAlgorithmRC4, 0,
                      (void*)m_hKey.data(), 5, NULL, &cryptor);

EDIT:

Actually, the above code is not compatible with CryptDeriveKey(). It turns out (from test vectors published in comments) that Windows still uses 16-byte key but last 11 bytes are set to zero (thus, effective key length is still 5 bytes or 40 bits). Python code that produces same result as Windows code:

from Crypto.Cipher import ARC4
import binascii

KEY = "cfba3dd2ed"
DATA = "eb b9 bd 6f 5d 46 8d 17 c1 88 db 78"

key = binascii.unhexlify(KEY) + "\x00" * 11
rc4 = ARC4.new(key)
print binascii.hexlify(rc4.encrypt(binascii.unhexlify(DATA.replace(" ", "").strip())))

Outputs for me:

04021f02730101000000ff9b

This CommonCrypto code should work:

if (m_hKey.length() > 5) {
    memset(m_hKey.data() + 5, 0, m_hKey.length() - 5);
}

CCCryptorCreate(kCCDecrypt, kCCAlgorithmRC4, 0,
                          (void*)m_hKey.data(), m_hKey.length(), NULL, &cryptor);


Can HTTPS request parameters be seen by the PC client? I've searched for it but couldn't find a direct answer to this relatively simple question. Most questions are about a 3rd party intersepting the HTTPS POST or GET parameters inbetween client and server.
But my question is: can a PC user somehow see the HTTPS POST or GET parameters?
My C++ application sends HTTPS POST and GET requests to a third party website. In these requests it sends a secret password, which shouldn't be known by anyone except my application and the website. So can user use some kind of software, like firewall app etc. and see this secret password?

HTTPS protects against man in the middle attackes. Machines between the client and the server can not see HTTP GET or POST parameters.
However, other applications on the client (e.g. a TLS intercepting proxy) could potentially read the entire request, parameters included, in clear text. Or an application with sufficient priveliges could read the secret key from memory. So whoever controls the client - your users, or malware on their machine - will be able to read the secret key.


How can wireless password cracking be detected? Our team was hired for a red team engagement for a client. A part of the engagement is attempting to crack the WiFi passwords of their office APs. However, we obviously want to stay undetected. What kind of thing should we watch out for? Apart from the obvious things like don't let anyone see you with your laptop running AirCrack.

In order to capture the handshake of the WPE/WPA2 network you generally need a client establishing a connection with the access point.
This can be forced by the attacker by using e.g. a deauthentication attack which then leads to the client sending the hashed password to the access point.
A deauthentication attack can be detected, however, if you wait until a network device get's disconnected, which eventually will happen, there's no way to detect you capturing the handshake.
Once you cracked the passphare, it is obvious that you need to be careful with MAC address, hostnames etc. But that is not a part of cracking a WPA network.


Browser custom protocol handlers The possibility of running a shell command from an extension (NPAPI) has been phased out, but custom protocol handlers are still supported.

What is the practical difference if an extension can still launch any executable via the protocol handler?

Onus and user experience
Extensions with NPAPI mean that the browser and it's extension ecosystem are the source of malware, and are then responsible for combating it. Did extensions using this feature even need to disclose it?
On the other hand, launching a protocol handler is a very straightforward UX... it requires a user gesture each execution unless the user explicitly chooses to permanently allow. Prompting "Open something.exe?... example.com wants to open this application" signals to the user that they're making a choice right at this very moment to allow the browser to launch a different program.
Additionally, the custom protocol handler had to be installed on the machine outside of the browser ecosystem, which means it had to gain user trust on its own accord, not thru the app store where people might be lulled into a false sense of trust (e.g. "...it's on the Chrome web store so it must be safe...").


Does each device of the same model have different SSL certificates for them? Lets say my company produces a device which can be connected to secure websites or it may act as some kind of server.

Lets say I produced 100 pieces of the same device. Should I get one SSL certificate for all of them or 100 unique certficates?

Or even better, Can I still communicate with a secure server without a certificate?

I need to know how it is done currently in the industry, for example in the case of mobile phones.

A certificate is used to make sure that you connect to the correct device, that is that no man-in-the-middle is intercepting the connection. If you employ the same certificate on lots of devices which are shipped to lots of different customers the goal of proper verification if your own device can not be reached. Apart from that each of these devices would probably contain the same private key, thus extracting the private key from a single of these devices would make an attacker to intercept communication of all of the others and depending on the ciphers used would also make it be able to decrypt also previously intercepted encrypted traffic.

Thus the usual way is to create a unique certificate for each device, with a unique public and private key. Even better is to let the user replace the certificate with their own, because this way in can be better integrated in their own infrastructure.


How to determine if someone is scanning my server? How is possible to determine if someone make requests with tools for pentesting?
Is there any linux command?

Is your system publicly accessible?

Yes: Someone is probably scanning it.
No: Are you scanning the server?

Yes: Well, you've just answered your own question now haven't you?
No: It's probably not getting scanned.
I don't know: Wait... what?

I don't know: You've got bigger problems. And yes, you're probably getting scanned.


How do you determine if an open source script contains malicious code? I am trying to analyze an open source auditing tool to determine if it makes unnecessary and potentially harmful changes to the system. I am interested in determining if the script calls any binaries or writes to any files other than its own log file. I have analyzed the strace output for exec and write syscalls but am concerned it may not include information about child processes or that it may miss potentially malicious changes to the system. If anyone could suggest other methodologies I would be grateful.

Based on the rather generic requirements, I must say that there really are oh so very many ways to do malicious stuff, and even more ways to hide or obscure those activities.
For example, perhaps it only gets triggered after 3 months of use?

On the other hand - if this is open source, I would suggest auditing the code.
You can definitively verify anything and everything the code does, even under a very specific set of circumstances. Code coverage, and all that...
(Well, assuming there is not a rootkit in your compiler...)


Detecting port scans in OSX kernel Is it possible to detect port scans on OSX at the kernel level? I would like to write a kext that detects the ip addresses of systems scanning my computers ports.

How exactly does a stealth scan work? Doesn't the kernel get notified when a port is accessed from outside?

A stealth scan as it is commonly called is a half open TCP connection. Rather than:

SYN ->

<- SYN/ACK

ACK ->

it goes

SYN ->

<- SYN/ACK

RST ->

It's only referred to as stealth because many applications log a connection on its listening port. As this scan never completes the TCP connection, no log entry is made. Its in no way undetectable. The network stack in the kernel will still receive notification on the connection just the application listening on the port does not.

A bit more information is available here


Is attacking a password manager on android with root access a plausible concern? There is a password manager app for Android that I'm considering using, that reads a database format for a popular desktop password manager. There is one part of this app that is giving me pause; I've approached the author about the issue but the author does not seem very concerned about it. I want to make sure I'm not just being paranoid.

To use this app, you give it the master password for your password database. The app creates a two-part key by combining a 4-digit PIN with a random 256-bit key stored in Google's cloud-based application data. This key is then used to encrypt the master password locally. When you use the app, you enter the PIN, the app retrieves the cloud-based key, and uses both to decrypt the master password and unlock the database. There are no other options for unlocking the database. The cloud-based key is never stored on the device, it is only ever used in memory. The encrypted master password is only stored on the device, it is never uploaded to the cloud.

I'm willing to give the author benefit of the doubt here and assume the key is generated securely, and for the sake of argument I will give Google the benefit of the doubt and assume that this one app is really the only party they'll ever give the data to. Yes, I know this may not be a realistic assumption, but an Evil Google is not high on my list of concerns. If these assumptions hold, then as long as my phone is secure, then only the app on my phone can get at the cloud key directly, and therefore only the app on my phone can decrypt my master password.

However, I thought up this scenario:

Attacker steals phone.
Oooh, look! A password database! Drat...it's locked!
Attacker roots phone.
Attacker launches the password manager app.
Attacker enters a single PIN at random.
App downloads cloud-based key.
Attacker uses root privileges gained above, to dump process memory for the app.
Attacker reads cloud-based key from memory dump.
Attacker brute-forces PIN/cloud-key combinations offline.
Password database is unlocked in milliseconds or less.

Am I right to worry about this attack, or is it implausible/preventable somehow? Right now it's the only thing keeping me from trying the app. I'm not an especially high-value target or anything.

A follow-up question: I'm trying to convince the author to add an option NOT to store the master password, and rather to just ask for it every time I open the app. Assuming the password is secure (I use a phrase of 7 words chosen at random, with dice, from an unabridged hard-copy dictionary), and assuming the password is never stored anywhere, would this likely keep my passwords secure from an attacker who obtains my phone?

I know that root access on a phone can attack any running and unlocked password manager, but in that case, I simply need to (a) not root my phone myself, (b) be careful not to install malware, and (c) carefully lock my database after use. However for this app, there does not seem to be anything I could do to prevent the attack unless I immediately notice my phone is missing, and immediately delete the cloud-based key.

There are a number of mitigations you aren't considering.  To directly answer your question: Yes, provided an attacker has full purview over all phone activity (some android phones are difficult/impossible to "root" so this is not a given even at that level) they could capture the cloud part of the key and brute force the combinations within a short time (probably more than milliseconds since they have to test-decrypt the password file with every pass, there is no magic indicator that it worked after computing the key).

But, most cloud password managers allow for remote privilege revocation (i.e. disallow device from fetching key from cloud until it fully authenticates again) which should be practical for you to execute before the attacker roots your device, since it is very simple to do.

Second, mobile device management allows you to permanently wipe the contents of your phone should you find it stolen, again only effective if you act quickly but still should be possible to log in and hit wipe device before the attacker has even had a chance to size up his options with attacking your device.

Third, full device encryption with a strong pin (available in all android versions for a few years) would negate all of the attack vectors in one go, since the attacker would be required to know your pin in order to do anything to the phone at all.


Chromium Malware (possible) on my Linux Machine Running Chromium 60.0.3112.11 on Linux Ubuntu 16.04

Chromium attempts to access my Linux machine's media upon autocompleting bankofamerica.com, wellsfargo.com, americanexpress.com, or discover.com.
Chromium also attempts to access my Linux machine's media upon searches in Google for the following bank-related strings:
'bank'; 'american'; 'bank of america'; 'wells fargo'; 'american express'; 'discover';
'american express card'; 'discover card'; 'discover card services';
but not for:
'bank of america customer service'; 'bank of america interest rates'; 'wells fargo customer service';
'wells fargo interest rates'; 'american express card services'; 'discover card bill pay';
'banks'; 'america'; and all other banking and non-banking related strings that I have checked.
Chromium accesses my navigation entry screenshot manager upon resubmission of any URL. This could be a remnant of having used Selenium in the past to control the chromium-browser but thought this should be mentioned given the nature of the previous two bugs.

Documentation is as follows:

    me@linuxmachine:~$ chromium-browser &
    [1] 2496

4a. The error:

    [1:13:0901/211311.279992:ERROR:adm_helpers.cc(62)] Failed to query stereo recording.

is prompted by autocompleting in the address bar: bankofamerica.com, americanexpress.com
or
searches in Google for: 'bank of america','american express','american express card'

4b. The error:

    [2496:2496:0901/211421.675100:ERROR:web_contents_delegate.cc(199)] WebContentsDelegate::CheckMediaAccessPermission: Not supported.
    [2496:2496:0901/211421.675126:ERROR:web_contents_delegate.cc(199)] WebContentsDelegate::CheckMediaAccessPermission: Not supported.

is prompted by autocompleting in the address bar: wellsfargo.com
or
searches in Google for: 'wells fargo','american'

4c. The error:

    [2496:2496:0901/211631.723037:ERROR:web_contents_delegate.cc(199)] WebContentsDelegate::CheckMediaAccessPermission: Not supported.
    [2496:2496:0901/211631.723065:ERROR:web_contents_delegate.cc(199)] WebContentsDelegate::CheckMediaAccessPermission: Not supported.
    [1:13:0901/211633.046282:ERROR:adm_helpers.cc(62)] Failed to query stereo recording.

is prompted by autocompleting in the address bar: discover.com
or
searches in Google for: 'discover', 'discover card', 'discover card services'

4d. The error:

[2496:2496:0901/212845.137648:ERROR:navigation_entry_screenshot_manager.cc(134)] Invalid entry with unique id: 55

is prompted by resubmission to the browser of any URL that Chromium has already navigated to.

5.. Questions:

Can any forum members please comment on these Chromium errors and the possibility that they are produced by malware that is targeting my financial data?
    Specifically:

Are they predicted responses to known malware, and if so, what is the name and origin of the malware, the files known to serve as hosts, and the proper method of remediation of an infected system?
How much of a concern should I harbor for my brower or system safety and the safety of my financial data given the nature of these errors?
How should I properly contain and address the threats to my browser or system and restore Chromium to proper function?

Because Chromium is open source, you can verify that these log messages are pretty much normal. The association of their timing with financial-related strings are not.

The CheckAccessPermission log is coming from here: chromium/src/content/public/browser/web_contents_delegate.cc. If we follow up the call chain, we find MediaDevicesManager in media_devices_permission_checker.cc, where we can see that these functions are called when web or extension content is attempting to access your microphone or camera.

Because it seems like this could possibly be the fault of a poorly implemented extension, and also because Chrome extensions are the most likely culprit of fishy behavior by the browser, I recommend performing an audit of your extension list at chrome://extensions . Try disabling extensions one-by-one until the behavior goes away. Verify that this does not happen in an incognito / private window, which extensions are by default not allowed access to. (If any extensions are marked as "allow in incognito windows", uncheck that box before testing.)


Business process based risk assessment methodology for iso 27001:2013 I am working on an isms implementation for iso 27001:2013. So far whatever risk assessment approaches i have used asset based in which methodology focuses on asset value evaluation, threats, vulnerability and control implementation status values to calculate the risk associated with underlying asset.
Lately i have came across a business process based risk assessment. i have searched on google and have found few helpful sites although couldn't manage to find anything concrete in terms of risk assessment methodology one can adopt or relevant templates.
looking for help to come up with a formula in process based approach for risk assessment or any sample templates will be greatly appreciated.Thanks in advance.

Normally, the risk analysis is process based: You go through the main business processes with the client and then for each process you should find relative assets. For each asset, the impact on the business processes should be clearly defined in case of asset disruption: no impact, low impact, medium impact, high impact and also highlighting the vulnerabilities for each asset. The importance of an asset should be defined according to the importance of the business processes and the impact of this asset.


Fell for phishing scam. Is my gmail account with 2-step verification vulnerable? I can't believe it happened to me but I entered Gmail account's user-name and password into a website as part of a phishing scam.  I use Gmail's 2-step verification and have changed my password.  Is my Gmail account safe?

I got an email from a friend suggesting I download a document.  We frequently exchange articles but I was suspicious so I emailed him back asking if he had sent me the first email.

He responded that he had and, dumb me, mentioning no specific details suggested I would think it was great.  "How could a phishing scam respond like that?" I thought. I clicked the link, entered my Gmail username and password on my phone but couldn't access the "article."

I then logged into my Gmail (using 2-step verification) on one of the computers at work (a hospital with old Netscape browsers behind hospital network firewall) and opened the email and clicked the link.  I typed in my Gmail username and password again (but no authenticator Google 2nd step access code because I wasn't prompted.)

Still unable to access the "document," I moved my friend's email into my Gmail account's "Follow-up with" folder thinking I would try later at home with a modern browser.

I hadn't yet followed up when this morning I got an email from my friend explaining that  his yahoo account had been hacked from Korea and that it was even generating automated responses.  He added, "Don't click on any links!"

I immediately changed my account's password (about 17 hours after entering my info into the scam's site) but even if I didn't, those baddies don't have access to my phone and it's authenticator app so couldn't access my email, right?

Anyone have any thoughts?

Since you didn't enter your second factor code from your phone, and since you didn't say that you received a text requesting the second factor, you should be safe.

However, if you want to be sure that all bases are covered (or if you hadn't enabled 2 factor authentication), there are a few things to check to be sure that you haven't been compromised and that there are no further back doors into your account.

The first thing you should do is click the Account Activity Details link at the bottom of the Gmail webpage. Then check the history list for any unidentified activity. It doesn't show a lot of history (I can only see 8 hours back on my page), so it may not show you all activity from the time you entered the bad credentials but if you see an unknown IP in the list, you'll know that someone is logging on to your account.

At the top of that Account Activity window, there's a link to "Sign out all other web sessions", which you should click to make sure that no other web sessions are signed in.

Additionally, go to your account settings from the drop-down near the top of the page, then go to Accounts and Import, then check your Account Recovery Options to ensure that no one has set up their account as a recovery account.

Then to to Other Google Account Settings and then go to Sign-in & Security. From here, verify that your 2-Step Verification options are set to only go to your phone number -- make sure no one added an alternate phone or generated backup codes. If you see that backup codes were generated and you didn't generate them, then generate a new list to invalidate the old ones. Also, check the App passwords to make sure that no one has generated an App specific password (which allows them to bypass 2 factor authentication), revoke any credentials that you did not create yourself.

Also in the account settings, verify that no one has set up email forwarding to another address. If they forward a copy of your emails to their own address, they can use your account for Phishing responses and/or to reset passwords for sites that use email for password recovery. While you're there, make sure they haven't turned on POP/IMAP access, though that shouldn't help them unless they have changed your authentication options.

If you found that someone had reset any of your authentication options above, then reset your password one more time, but if you've verified that all of the options are exactly as you set them youself, then you should be safe from someone breaking into your account.

If you have reason to believe that someone did access your account illicitly, then you have to worry that they gained access to any of your other accounts that use email to reset the password, for good measure, reset important passwords like for online banking, credit cards, shopping sites that have stored credit card numbers, etc.

Check all folders (including trash and spam) for any password reset emails that the attacker may have received. Also, check your sent folder to see if he used your account to send emails to others. This is not a foolproof check since the attacker may have permanently deleted any traces of his work.


Can gnupg sign multiple files in parallel? I want to sign every file in a directory. I can do so with the following shell command, but it's slow.
Serial Execution:
find . -type f -printf "Signing %p...\n" -exec gpg --quiet --batch --yes --detach-sig {} \;

I have 16 CPU threads and would like to take advantage of these (mostly idle) threads to speed up the signing process. GNU parallel and Python multiprocessing are behaving oddly, though; when they run gpg in parallel, I'm prompted for my PGP key's password multiple times. I'm running gpg-agent, so I'd expect to be prompted for my password only once. I also observe intermittent memory allocation errors. The --lock-once and --lock-multiple CLI options don't seem to change the behavior. Is there some implementation issue with running multiple gpg signing operations in parallel?

I asked this question on the GnuPG mailing list, and got this response from Werner Koch:

This is all serialized because the gpg-agent does the actual signing.
There is one gpg-agent per GNUPGHOME.  Thus the easiest solution for you
is to provide copies of the GNUPGHOME and either set this envvar for
each process or pass --homedir=decicated-homedir-copy.  You can't use
links to the same directory because we use lock files.  However, it
should be possible to sumlink the private-keys-v1.d sub directories.

Working from Werner's answer, I was able to create a Python script which properly signs things using temporary key copies and symlinks:
#!/usr/bin/env python3
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

This Python script signs all files in a directory in parallel, utilizing all available CPU threads.

Naive use of the multiprocessing module won't work; see https://lists.gnupg.org/pipermail/gnupg-users/2020-November/064346.html
"""

import os
import fnmatch
import subprocess
import multiprocessing
import distutils.dir_util
import shutil
import stat
import argparse

def get_fileset(path: str):
    for root, _, files in os.walk(os.path.expanduser(path)):
        for item in fnmatch.filter(files, "*"):
            path = os.path.join(root, item)
            yield path

def create_worker_dirs(working_dir: str, pool_size: int):
    for i in range(1, pool_size + 1):
        dest = os.path.join(working_dir, "ForkPoolWorker-" + str(i))
        print("Generating worker dir", dest)
        os.makedirs(dest, exist_ok=True)
        for f in ['pubring.gpg', 'trustdb.gpg', 'gpg.conf', 'gpa.conf']:
            shutil.copyfile(
                os.path.join(pg_src, f),
                os.path.join(dest, f)
            )
        os.symlink(
            os.path.join(pg_src, 'private-keys-v1.d'),
            os.path.join(dest, 'private-keys-v1.d')
        )

        # fix permissions
        for r, _, f in os.walk(dest):
            os.chmod(r, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)

def sign_file(path: str, working_dir: str):
    worker = multiprocessing.current_process().name
    print(worker, "signing", path)
    worker_working_dir = os.path.join(working_dir, worker)
    r = subprocess.run(['gpg', '--homedir', worker_working_dir,
                        '--quiet', '--batch', '--yes', '--detach-sig', path])
    if r.returncode != 0:
        print("Error signing file", path)
        print(r.stderr)
        return False

    return True

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("dir", help="The directory to sign.", type=str)
    parser.add_argument(
        "pool_size", nargs='?', help="The number of workers to launch. Defaults to the number of available CPU threads.", type=int, default=-1)
    return parser.parse_args()

if __name__ == '__main__':
    args = parse_args()
    files = get_fileset(args.dir)
    pool_size = args.pool_size if args.pool_size != -1 else multiprocessing.cpu_count()

    pg_src = os.path.expanduser('~/.gnupg')
    working_dir = os.path.join(os.path.dirname(
        os.path.realpath(__file__)), 'gnupg-tmp')
    os.makedirs(working_dir, exist_ok=True)
    create_worker_dirs(working_dir, pool_size)

    with multiprocessing.Pool(processes=pool_size) as pool:
        results = [pool.apply_async(
            sign_file, (file, working_dir)) for file in files]
        if all([result.get(timeout=10) for result in results]):
            print("Signing completed successfully.")
        else:
            print("Signing error!")

    shutil.rmtree(working_dir)


How is character encodings used to bypass XSS sanitizers? I read in different blogs that PHP htmlspecialchars() function has certain problems when one does not give the expected charset as an optional parameter.

Can someone explain some basic stuff about XSS exploits that arise from bad usage of sanitize functions with some examples related to character encoding?

Does this affect modern browsers as well?

The problem

Abusing character encodings is a popular trick to get XSS to work even when there are filters in place. There are a number of different situations when it works, but they all share common prerequesits:

The attacker sends a payload in character encoding A.
The server doing the filtering or sanitazion is working in character encoding B.
The victims browser is interpreting the page as if in character encoding A.

Let's look at two example of how this can happend.

Example #1: No encoding parameter in htmlspecialchars

This is a quite common sight in PHP:

echo htmlspecialchars($_GET["query"], ENT_COMPAT | ENT_HTML401);

The problem here is the default behaviour PHP falls back to when there is no encoding specified. From the manual:

  If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.

So what encoding PHP uses depends on your version and configuration. Great. So now all that stands between you and the abyss is someone making an innocent change in php.ini, or perhaps just something as simple as a server upgrade or reinstall. I too like to live dangerously... but not that dangerously.

Note that this example has nothing to do with the browser. Modern or old, it doesn't matter, because it's the server and not the browser that's the problem here.

The solution off course is to specify the correct encoding and making sure that the same is specified in the HTTP Content-Type header of the response:

echo htmlspecialchars($_GET["query"], ENT_COMPAT | ENT_HTML401, "UTF-8");

Example #2: Browser heuristics biting you

This is a problem if your server does not specify what encoding it is using in the response (or if it only does it in a meta tag that is to far down for the browser to care about it). If you do not tell the browser what encoding to use, it will have to guess. Unfortunately, all browsers aren't so good at that:

  If certain strings of user input -- say, +ADw-script+AD4-alert(1)+ADw-/script+AD4- -- are echoed back early enough in the HTML page, Internet Explorer may incorrectly guess that the page is encoded in UTF-7. Suddenly, the otherwise harmless user input becomes active HTML and will execute.

The payload in the quote is <script>alert(1)</script> encoded in UTF-7. A sanitizer working in UTF-8 would see nothing dangerous in that payload and let it through, but the browser that is tricked into working in UTF-7 would still run it.

My understanding is that it is mostly old versions of IE where this is a problem. But I am not sure, so I would be happy to see another answer where it is clarified.

EDIT: See Xavier59's answer for a situation where it works on modern browsers.

The solution

What you need to do on the server is simple in theory. You need to make sure that the following is always true:

The character encoding of the response is corectly set in the HTTP headers.
The XSS filter is working in the same encoding as specified above.

In practice, it is surprisingly easy to get that wrong.


Difference between ROP and ret2libc During the exploitation of a binary, I wish know what is the difference between the ROP (Return-oriented programming) and the ret2libc ?

I haven't found a resource which answer this question

Thank you

Essentially ret2libc is somewhat a ROP exploit, since you create a new stackframe to call the system function by returning to the libc library and circumventing a non-executable stack.

A ROP in general works similar, you jump to fragments of code (called gadgets) that return at some point and "build" yourself the code you want to execute by combining those fragments. You literally program the code you want to execute, creating new routines that were not in the code before. ret2libc utilizes the system function to get a shell.