The PSK passphrase is (by design) stored in a retrievable format by the Modem vendor, in this case Arris, but the same standard is supported by many other modem vendors.  In DOCSIS cable modems this is most commonly done via SNMP against this specific OID:

clabWIFIAccessPointSecurityKeyPassphrase    OBJECT-TYPE
    SYNTAX      SnmpAdminString (SIZE(0..63))
    MAX-ACCESS  read-create
    STATUS      current
    DESCRIPTION
        "This object is defined in TR-181 Device.WiFi.AccessPoint{i}.Security.KeyPassphrase."
    REFERENCE
        "TR-181 Device Data Model for TR-069."
    ::= {clabWIFIAccessPointSecurityEntry 5

This is part of the CableLabs WiFi MIB, which is is in turn based on the TR-069 sub-standard of TR-181.

Not only does this apply to cable modems, but many DSL and FTTH endpoints will also allow the service provider to retrieve your PSK passphrases and a litany of other settings.

This allows for end users to have their settings backed up in case of a device having to be replaced or much more commonly for call centers to be able to retrieve some of the settings, like the pass phrase, when a customer calls in because they can't remember it.


Is a company decrypting all SSL traffic through a Root CA GDPR compliant?

The problem with the GDPR lies in the remark: "without even notifying this software is being installed". In that case: no it is not compliant.

If you dig a little deeper, you will find that in almost all cases there has been some form of communication about this, either in the contract or via the work council and publication to all employees.

In general, employees do not have the same liberties in the context of their work as they have in the free world. Some form of monitoring and/or command is allowed.

To be a bit more complete: of course, the grounds for the data processing in this case will not be consent. It may be 'necessary for the performance of the contract' (doubtful), but more likely 'necessary for compliance with a legal obligation' (in heavily regulated industries) or 'necessary for the purposes of the legitimate
interests'.

    In order to rely on [legitimate interest] as the legal ground for processing it is essential that specific mitigating measures are present to ensure a proper balance between the legitimate interest of the employer and the fundamental rights and freedoms of the employees. Such measures, depending on the form of monitoring, should include limitations on monitoring so as to guarantee that the employee’s privacy is not violated.

(last part is a quote from "Opinion 2/2017 on data processing at work", art 29 working group)

I work in a place where such a MITM-attack monitoring is deployed. I have not been directly involved in the implementation. But it was clear that:

some sites (e.g. banking sites, government sites etc.) needed to be white-listed, so no monitoring was done for these sites)
Contact with the work council, publication to all employees and making it part of contracts with contractors was necessary.
Not all employees will understand the implications of this monitoring.

If you want to have real fun in such an environment, exercise your art.13-15 rights. Make sure art. 15.3

    The controller
    shall provide a copy of the personal
    data undergoing
    processing.

is respected.


Can MitM spoof a signed certificate by imitating the Certificate Authority?

How does the client get the public key of the certificate authority?

The certificate store is created at (OS/Application) install time, and updated as part of normal secured (OS/Application) updates.  Firefox is notable as an application that uses it's own cert store.  Because root certificates are pulled from a local store rather than over the network, they are immune to MITM attacks.

  what happens if that store is ever updated or compromised

If a bogus root certificate is added to the cert store, then its owner can forge certificates for arbitrary destinations (e.g., your-bank.com) and intercept your communication.  In a corporate environment, that's called SSL Interception and it may be performed legitimately, with your administrator installing the necessary certificate.  Yes, (an attacker | your employer) can use this to view and modify your web sessions.

If an attacker manages to do that, you're in trouble, but then, if they have the access and privileges to do that, you're in pretty big trouble already - your PC is already compromised enough to be keylogged.

It's possible to detect this sort of MITM by reviewing the certificate used in a session; in Chrome, this can be done by right-clicking on the lock icon and selecting "Certificate".  However, that's a manual process, and hard to do at scale.


I crafted an answer using Javascript, because it's what I am used to and no language is specified. I am confident that you can find/create an analog in whatever other language you please.

First off, I stole a function from This answer to create a cartesian product. The explanation of cartesian products is not really in the scope of this question, but suffice to say it combines arrays of possible characters into arrays of possible strings (very oversimplified).

OK, so ckozl's function is :

function cartProd(paramArray) {

  function addTo(curr, args) {

    var i, copy,
        rest = args.slice(1),
        last = !rest.length,
        result = [];

    for (i = 0; i < args[0].length; i++) {

      copy = curr.slice();
      copy.push(args[0][i]);

      if (last) {
        result.push(copy);

      } else {
        result = result.concat(addTo(copy, rest));
      }
    }

    return result;
  }

  return addTo([], Array.prototype.slice.call(paramArray));
}

and mine is :

function findSubs(string) {
        //create a linked list of sub characters
        //expect lower case input
        subs={
                "p":["p","P"],
                "a":["a","A","4","@"],
                "s":["s","S","$","5"]
        }
        //create an (initially empty) array to store possible characters in each position
        result=[]
        for (var i=0;i<string.length;i++) {
                result[i]=subs[string.charAt(i)]; //Would be more robust if you added logic here to handle it not being a key in the subs object.
        }
        /*
        so result might look like:
        [
                ["p","P"],
                ["a","A","4","@"],
                ["s","S","$","5"],
                ["s","S","$","5"]
        ]
        for an input of "pass"
        */
        return cartProd(result)
}

Honestly, ckzol's function does all the heavy lifting here. You would need to flesh out the subs array before use, and this does not handle adding characters at the end of the string (because it seems kind of arbitrary).

Also note I have ever so slightly modified the cartProd function, such that we can hand it an array of arrays as input params rather than multiple arrays overloading the arguments.

Edit: also note that the returned value is an array of arrays, so you would want to iterate through it and for each element e do e.join("").

Edit again: also note that you could easily extend this to apply other mutations to the password. For instance, if you wanted to add a number between 0 and 99 to the end of the string you could push an extra array onto the end of result, containing ["0","1","2",...,"99"]. You could include an empty element ("") in this array to also output possibilities not including the number suffix. The same logic could be used to add a prefix. Essentially you are building an array of arrays of possible characters in the result array, so you can include any mutations you can think of.


Get senders location via IP in email Header

As you have asked the question, the only possible answer is do not hope to be able to relyably do that
The problem in SMTP headers, is that any header could be forged, even if all cannot be forged at the same time. And free VPNs are great at presenting an IP address which is not the original one. So here is a simple possibility:

I am currently in a country with poor security reputation but I know free VPNs in England, Germany or France, and use a mail account in the same country
I use one of those VPN to connect the Webmail host

Then all IP addresses that you will be able to find in the mail will say that the mail originates from England, Germany or France...
And I was not even speaking of the From: address...


How to make Squid Proxy undetectable by ip-check.net?

The URL you've used seems to determine if a client uses a proxy not (only) based on HTTP headers but also where the request comes from.
To check I've used ssh -Dport dst, which creates a SOCKS proxy listening locally on the given port and where the traffic then comes out of the proxy with the IP address of the SOCKS endpoint. I've tried this with an external system at some public hoster and with localhost as a target: in case of localhost the URL claimed that no proxy was used while in case of the external system it claimed that a proxy was used. But the difference here was only in the source IP of the traffic, not in the use of a proxy.
While no details are known it is possible that this specific detection algorithm distinguishes between IP addresses which are associated with public hosting sites and other IP addresses, and in the first case simply assumes the use of some proxy, VPN or similar.


You are using parameterised queries consistently for all variable values, so there is no SQL injection attack.

However, storing database values in HTML-encoded format is an antipattern. You'll make it difficult to process the data at an SQL level (since 1 db character no longer equals one on-page character), you'll produce inappropriately-encoded output for non-HTML formats (eg sending mail), and you'll fail to properly HTML-encode any data that comes into the database by other means (or which doesn't touch the database at all, eg a Parameter output straight onto the page).

The time to HTML-encode is when you are dropping some text into an HTML page. In ASP.NET templates you get the <%: ... %> tag to do this automatically, as well as attributes of WebForms doing the right thing (caution: not always). HTML-encoding should not be done as an input-processing or database-query-creation step because those places aren't anything to do with HTML.

Also you should of course be storing passwords using a salted hash (ideally a strong one like bcrypt) and not in the clear as implied by the Password=@Password comparison.


Duqu and other reference material for security people

For Duqu Symantic has a quite detailed explanation http://www.symantec.com/content/en/us/enterprise/media/security_response/whitepapers/w32_duqu_the_precursor_to_the_next_stuxnet.pdf

Most anti-virus companies have some reporting on threats of varing levels of details. As this is not my specialty it appears to be random as to who will have details of what, but with a little hunting I can usually find something technical.


Why might malware make a DNS request for an epoch time converter?

Let me put it like this,

Nowadays malware are often connected to a CNC ( Command and Conquer ) Domain, they often communicate with this domain to inform the hacker that the malware is now active and is pending for future commands to execute, this is part of the sophisticated approaches that is being used today.

The malware enters your environment.
Calls the CNC to make aware of his activation.
The CNC replies with more commands to execute.
Often the malware would use DNS Ex filtration to encrypt the data gathered and sending it to the CNC for decryption and is the hardest thing to catch without the correct tools.

The domain you have mentioned would look offline, however could be a dns server that would relocate any data posted from the pc to an XML storage space.

if the website is not accessible through a browser or through a ping test .. it could be accepting requests only from signed calls.


Best guess, they contain the hash so that it's possible to check the password for correctness before trying to decrypt the file contents (which might be very long). Hopefully the contents also have a MAC or other integrity / authentication tag of some sort, so you can verify the correctness of the password after decryption, but that could be a lot of work if the file is huge (as some PDFs are) just to tell the user "whoops, wrong password".

If the attacker knows part of the plaintext (or at least knows what it should look like, such as that an embedded image should have a recognizable image file header), that can be used as a "crib" to check the password without either resorting to the hash or trying to decrypt the whole file. However, that doesn't work very well for the general case.


Bypassing Directory Traversal Filter with separate Folder and File Inputs

None of them are vulnerable to SQL Injection

Why would they? Is there a reason you expect the download script to perform a query?

You shouldn't rely on tools such as sqlmap. They are meant to make things easier, but if you want to learn - or test an application in-depth -, you need to perform these things yourself.

  It is possible to delete the \public\ part of the path using comments with #

No, that doesn't make sense. The path is build like this:

\files\public\[INPUT_PATH]\[INPUT_FILE]

You can't really comment out something that exists before your input (most - if not all - APIs that allow file access also do not allow comments in file path).

  or another way so I can finally access to the private directory?

If this is for educational purposed, I'm assuming that it is meant to be vulnerable. You say that "it is not allowed to introduce ..".

Is this an assumption you made? or did you look at the source code and is this actually how it works? If this is a filter, you need to check how it actually works.

What if you input ....\\? Maybe the filter replaces ..\ with nothing, which would give you ..\.
Is it filtering the file name and the directory? Are the filters the same? Can you use one to travers, but not the other? Can you use / instead of \?
can you input . as directory, and .\private\passwords.txt as file? It would combine to \files\public\..\private\passwords.txt


Brotli compression algorithm and BREACH attack

I thought this was quite an interesting question and problem, so I had a go at implementing the attacks myself, but against something other than "true" or "false".

To make things simple I used a static page as a file and injected content into it at the end. The target secret looked like this:

<input type="hidden" name="secret" value="7253b8f45f322b411ce39b12c6e9a84c" />

I used the source of an MSDN page as an example to build around. The full target page source I used can be found here; the secret is on line 33. An important factor here is that the page content includes a lot of other hexadecimal strings, which imitates a potentially more difficult attack scenario.

To attack this, I used a fairly naive method:

Append <input type="hidden" name="secret" value=" to the end of the page, then append our previous guesses (if any), then append 0000 to ffff in sequence and look for the smallest result when compressed.
For the 4-character hex string that produced the smallest result, add the first three characters to our guess. Dropping the last character is important as there is quite a bit of uncertainty in the last character, and if it does get it wrong it tends to just repeatedly generate the last character for all remaining guesses (e.g. 7251 on the first would generate 1111 on all subsequent guesses).
Loop steps 1 and 2 until we have <4 characters left to guess. Run through the remaining possible combinations, in each case adding " /> to the appended string to complete the tag.

I wrote a complete implementation with parallelism in C#, which you can find here.

Here are the results for GZip:

................................
Guessed f45a
Secret: 7253b8f45
................................
Guessed f322
Secret: 7253b8f45f32
................................
Guessed 2b41
Secret: 7253b8f45f322b4
................................
Guessed 11ca
Secret: 7253b8f45f322b411c
................................
Guessed e39a
Secret: 7253b8f45f322b411ce39
................................
Guessed b12a
Secret: 7253b8f45f322b411ce39b12
................................
Guessed c6e9
Secret: 7253b8f45f322b411ce39b12c6e
................................
Guessed 9a84
Secret: 7253b8f45f322b411ce39b12c6e9a8
Reached last block.

Guessed 4c
Secret: 7253b8f45f322b411ce39b12c6e9a84c
Done!

This took only a couple of minutes to run and it correctly discovers the secret.

Now let's try again with Brotli, using the "fastest" compression mode, with the same configuration for the attack:

................................
Guessed 7253
Secret: 725
................................
Guessed 3b77
Secret: 7253b7
................................
Guessed 4aa7
Secret: 7253b74aa
................................
Guessed 47aa
Secret: 7253b74aa47a
................................
Guessed 0aaa
Secret: 7253b74aa47a0aa
................................
Guessed 0aaa
Secret: 7253b74aa47a0aa0aa
................................
Guessed 3a0a
Secret: 7253b74aa47a0aa0aa3a0
................................
Guessed 0aaa
Secret: 7253b74aa47a0aa0aa3a00aa
................................
Guessed 4aaa
Secret: 7253b74aa47a0aa0aa3a00aa4aa
................................
Guessed 2aaa
Secret: 7253b74aa47a0aa0aa3a00aa4aa2aa
Reached last block.

Guessed 7a
Secret: 7253b74aa47a0aa0aa3a00aa4aa2aa7a
Done!

Not so good. The second guess goes wrong and this throws off the whole algorithm. So maybe we need to be a bit more cautious, and only accept 2/4 characters per block instead of 3/4.

................................
Guessed 411c
Secret: 7253b8f45f322b41
................................
Guessed 1c77
Secret: 7253b8f45f322b411c
................................
Guessed e377
Secret: 7253b8f45f322b411ce3
................................
Guessed 9b12
Secret: 7253b8f45f322b411ce39b
................................
Guessed 1277
Secret: 7253b8f45f322b411ce39b12
................................
Guessed c677
Secret: 7253b8f45f322b411ce39b12c6
................................
Guessed e977
Secret: 7253b8f45f322b411ce39b12c6e9
................................
Guessed a84c
Secret: 7253b8f45f322b411ce39b12c6e9a8
Reached last block.

Guessed 4c
Secret: 7253b8f45f322b411ce39b12c6e9a84c
Done!

And there we can see it works again! So it turns out that it isn't impossible to attack Brotli in this way.

The key part that explains why your attack failed is the pre-defined dictionary:

  Unlike most general purpose compression algorithms, Brotli uses a pre-defined 120 kilobyte dictionary, in addition to the dynamically populated ("sliding window") dictionary. The pre-defined dictionary contains over 13000 common words, phrases and other substrings derived from a large corpus of text and HTML documents

(from Brotli - Wikipedia)

So do "true" and "false" appear in this dictionary? Yes! I found a textual copy of the dictionary here and you can find true and false on lines 6829 and 1204 respectively.

The reason my attack works and yours doesn't is that I'm looking for something that isn't in the dictionary. For a single token like "true" or "false", using the dictionary index is much more efficient than trying to fold the characters together with another instance in the stream using distance encoding.

But why was it harder for me to perform a successful compression oracle attack using Brotli than with GZip? There don't appear to be many hexadecimal strings in the dictionary. I believe this is simply because the Brotli compression system is more complex than GZip. GZip uses a combination of LZ77 and Huffman coding, which has a strong focus on duplicate elimination, which works great for a compression oracle attack. Brotli, on the other hand, has more tricks up its sleeve, leading to a higher likelihood of other compression mechanisms being used instead of duplicate elimination during the first few blocks when the duplicate isn't very long. One way to improve the attack for Brotli would be to brute-force a longer set of values in the first block (e.g. 6 or even 8 characters) to try to elicit a duplicate elimination. This is much slower but would likely force a reliable compression oracle out of the Brotli compressor.


Does SNI have any benefit when doing fingerprint validation instead of using the common name?

(Edited response since you are not confusing SAN and SNI):

With SNI the client sends the expected hostname within the ClientHello. This is necessary if you have multiple certificates behind the same IP address. It does not matter if you validate the certificates the usual way or if you verify it by fingerprint - the only question is if you have a single certificate on the IP (no SNI needed) or multiple certificates (SNI needed).

If the server is under your control and your application should only connect to your server, then a single certificate is enough, so no SNI is needed. But, if you use a CDN then you often have multiple certificates behind the same IP and the relation between the actual server/IP and the hosted certificates might change over time. In this case it is not enough to identify the server as owned by the CDN, but you have to make sure that your certificate is located on the server and you have to tell the server to use the configuration behind the certificate. In this case you need SNI.

And, while the Host header inside an HTTP request also specifies the requested hostname, this is only a property of HTTP (and it is not even required with HTTP/1.0). With protocols like SMTP you don't have such information but SNI is still used with these protocols on the client side (postfix, exim) and also the server side (exim).


Sweet 32: Which applications we consider vulnerable?

You need to take into account that there is a difference between disk/file encryption and network encryption. The paper talks primarily about streams of information thus networks. As you mentioned briefly, much of the transmitted data actually is HTTP related stuff, and that is an important part of the attack.

The 64bit ciphers are not actually broken (ignore crypto definition for the moment), but more weakened to a point they become vulnerable, and so leave a good to far chance they could be converted back to plaintext with modern hardware (or at least some pieces).

In order to do this, you need lots of information to detect specific patterns. Those patterns will only emerge in large volumes of repeated data, and luckily this is often the case with networks. HTTP is a great example, although keeping a connection alive long enough to capture all the data, without missing packets or encounter malformed frames is rather difficult over the internet. In a lab the circumstances are ideal, which makes this exploit work.

To answer your question, applications such as Vim use blowfish for file encryption, which stores data only once (or multiple times, but not repeatedly). This limits the chance of being broken significantly. Don't think file encryption that uses 64bit block ciphers is problem-free, which is why the advise is to omit 64bit ciphers all togehter. For OpenVPN, this does not leave much cipher suites to pick from, but change is coming..


How do you put your own CA into the trusted root CA store of users who are not members of your domain?

I would highly recommend against this. Adding your certificate to personal devices root stores is a bad security practice. It's a matter of trust. Should your corporate devices trust your authority? Yes. Should random peoples devices trust your authority? Not really. The worst that I've seen happen when I've connected to an 802.1x wifi network is it ask me if I want to continue with an unverifiable certificate.

In regards to your question though, you need to have a way of distributing the CA certificate before a user connects. For iOS you can create a provisioning profile that contains your CA cert. All you would need to do is have users go to the profile URL in safari and install it.

Android as far as I know is more complicated. Users would need to first download the CA cert, then go into their setting and manually add it.

Automatically allowing CA certificates to be installed is impossible. If it were allowed, attackers could force you to install their own CA certificate and hijack sites like Google or your bank.

Photo source: http://www.bu.edu/tech/services/infrastructure/networks/wireless/8021x/iphone/


exploiting Open redirection vulnerability in java

Open Redirect happens when the application takes user supplied URLs or paths as parameter value and redirect to them without warning the user.

Scenario:

Step 1: The following get request takes a URL as a parameter value.

GET /thengakola.asp?&returl=http://pappadam.com
Host: mangatholi.com

Step 2: So by sending the following link to anyone, I can fool a user who trust mangatholi.com to land on malicious website pappadam.com

http://mangatholi.com/thengakola.asp?&return=http://pappadam.com

Find out if you can device a scenario to redirect an unsuspecting user to land on another website from the link. The application is vulnerable to open redirect then.


Encrypting data before sending to SaaS tool and decrypting on browser view

Based on what you have outlined, your solution seems overly complex and I'm not sure why you wouldn't just encrypt the data rather than hashing it. There may be limitations in what you can store in the remote app that may require encoding the encrypted data (similar to what needs to be done when sending encrypted email). This would eliminate the need to maintain a local database mapping hashes to original text. Requiring that sort of mapping would require sharing of the database between all possible clients, which could be a problem - easier to share a secret key than a database in most cases.

However, fundamentally, I think the problem is trying to add security to something which was not designed for it. This is rarely a great path to take. The solution often ends up overly complex and frequently has holes which aren't easy to spot. The real solution is to use a SaaS which includes the level of security you require and avoid any solution which attempts to add security on as an afterthought.


Could I recover the content of file from its checksum/hash?

A simple answer, NO.

It is like asking, if I know, that x%4 = 3, is it possible to find the value of x? No. Surely, there would be infinite values of x satisfying this equation, but you wouldn't simply know which one is correct.

Similarly, many(or infinite) video clips could result in a given hash value(obviously, infinite video clips have to be mapped to a specific number of hash values, so collisions are bound to happen). You wouldn't know which clip is correct.

That too, in human time? No.

EDIT:
As pointed out in comments, since the file is chunked into pieces of 2 MB, there won't be infinite possibilities, but it would be pretty large(2 raised to power of 16.7 million, approximately). Brute-forcing such a large number of possibilities, in human time, is still close to impossible. But yeah, it's not infinite.


Kerberos replay attack within allowed range - authenticator won't prevent it?

In Kerberos V5 a replay cache was introduced which keeps track of all authenticators recently presented to a service (recently = the size of the clock skew). If a duplicate authentication request is detected in the replay cache, an error message is sent to the application program.


How to trace the owner of a computer by mac address

Nope. MAC addresses are extremely easy to modify, and there is no centralized registry of them anyways. There's really nothing you can do beyond setting a secure wifi password (that means using WPA2) to prevent them from connecting in the future.


Why does Windows 7 remove Authenticated Users from file permissions when a folder is shared?

If you use the Share... button Windows will push the share rights on to the file permissions. Period!

Use Advanced Sharing... button if you want to separate the share permissions from the file permissions.


How are short passwords not safe if you limit the number of attempts?

The main reason passwords need to be long and random (i.e. high entropy) is to protect against offline brute force attacks.

Passwords are usually not stored in plain text. Instead, they are hashed. If someone steals the database with the hashed passwords (this is surprisingly common), they can not directly read the passwords. Instead, they have to try loads and loads of passwords to find one that matches the hash. Since the password hashes have been stolen, this can be done on the attacker's machine and not via the website itself (hence offline attack). This means that any limits on retries on the webpage do not apply.

Long and random passwords takes more guesses, so they are harder to crack even if the database is ever stolen. That is why they are encouraged on the web.


How are symmetric cryptographic keys stored?

Secret keys (symmetric or asymmetric) are typically stored in an encrypted medium of some sort such as a keystore or encrypted database. Specific example of a keystore would be the JKS (Java Key Store), and a database would be SQLCipher. This encrypted medium is secured with a master password, which is needed in order to read/write to it. SQLCipher will first churn the password through with PBKDF2 in order to ensure it has enough entropy and computational cost.

The question of where that master password is stored will of course affect the security of your system. For the client side, expecting the user to remember it is the best option. For the server side, a Hardware Security Module (HSM) may be used to secure the keys like Amazon's Key Management Service.


I have been using Backtrack for 2 years and I have heard no news of any spyware or 'phoning home'.

Also, have you seen the photos of the NSA using Backtrack?

Metasploit and w3af actively work with the curators of Backtrack, which shows some level of confidence in the distribution.

Also, with the number of people running packet sniffers attached to Backtrack as part of their penetration testing, any anomaly would show up immediately.

Because everything in Backtrack is open source, every package added to the distribution is verified before release. You can even check things out yourself.

Does this help?


Stack Protection off but still cant overwrite EIP

Your second example dies due to 0xffffd8fe pointing to an illegal instruction. It seems a poor address for a blind ret or jump esp pivot into your shell code (should be in the binary 0x0804xxxx). It also seem like a poor address for your shellcode as it should be located somewhere closer to 0xbfff0000. Try putting a breakpoint on the address you are overwriting EIP with before running the payload. That way you can confirm execution (breakpoint hit) and inspect the instructions.


What web browsers support OCSP stapling? Are the privacy and performance features the same?

My impression is that OCSP stapling is not well supported on the client side, but it's possible my information might be out of date.
Firefox apparently supports OCSP stapling, as of Firefox 26.  (Thanks to Jan Schejbal for this information.)
Chrome supports OCSP stapling on Windows, Linux, and ChromeOS.   (Thanks to Kit Sunde for this information.)  (The Chrome team has decided that they plan to remove CRL and regular OCSP checks, but they haven't disabled OCSP stapling.)
I've read one report that most browsers support OCSP stapling on Windows.
Here is some more information on browser support for OCSP (but not OCSP stapling, unfortunately).


Any way to prove that two devices are in the same physical space, for authentication?

There are schemes (1 and 2) that use environmental sensors like accelerators to generate a shared secret.

Two devices are shaken while held together. The specific time, pattern and magnitude of shaking should be unique to these two devices.

This data can be used to calculate a secret value only these two devices should know.


Unless you need to be FIPS compliant I wouldn't disable rc4 md5. You can simply prefer it as a last resort. You can configure your webservers in such a way that they will only resort to rc4md5 if the client does not support any other ciphers you offer. This way you needn't worry about supporting legacy clients.

To my knowledge older phones sometimes only supported RC4 MD5 (from the pre smartphone era).


IPsec with PSK: Can PSK be used for passive eavesdroping?

In my understanding PSK is only used for authentication in IPSec. The key exchange itself is done with Diffie-Hellman and the PSK is not used as part of the key exchange.

An active attacker could impersonate the expected peer due to knowledge of the PSK. This way he could be part of the key exchange and thus have access to the key needed to decrypt the traffic.

But with purely passive sniffing the attacker is not involved in the key exchange. Since the exchanged key is independent of the PSK the passive attacker cannot determine the key and thus not decrypt the traffic.


I'll start by saying I'm not a lawyer, and its been a long time since I worked in Healthcare....

I am not aware of any legal constraints beyond the DPA and GDPR. However it is not unusual for health boards to have their own requirements independent of the legislation. Depending on the usage you may also be subject to the HSCIC rules - Amazon have a doc about this. A requirement of the latter is that you trained in the use and application of the policy.

  It works by querying two entire tables decrypting all of the contents and then putting the result in redis

This makes me think that someone has not understood the requirement nor the impact of applying encryption. Since you've written the cleartext outside the encryption, then there is no benefit to the encryption. I suspect that the reason for writing the cleartext outside the encryption is in order to query the data. I'm not surprised that this has an impact on the service as a whole. That is does have a detriment to the service and no benefit implies a net detriment and hence the encryption is actually worse than useless. Presumably someone just heard "encryption" and thought it was more secure. It doesn't matter all that much that Redis is "in memory".

If this was on a platform where you could guarantee the integrity of the memory, then it would be trivial to configure 2 instances of MySQL - one running off zram and one off disk, then replicating between them to make sure you always had an up to date, unencrypted copy which wasn't written to disk without having to rely on batch copying and the constraints of a noSQL database.

There's little effective difference between using transparent encryption implemented by the DBMS and encryption on the block device (e.g. dmcrypt, luks) or at the filesystem tier. There are operational differences about who controls the keys - which may be an important consideration). There is a difference with Mariadb encryption in that it can be specified at the table or tablespace level without having to split tables/tablespaces across different filesystems. MariaDB also supports the AWS key store.

As it stands, IMHO, using any of these transparent encryption methods and not copying the cleartext to redis would give you a faster and more secure solution.


Could "Windows Network and sharing center" constitue a security risk?

Devices will only show up there if they are configured to be discoverable - for Windows computers machines (7 onwards IIRC) you are asked when first joining a network whether you want to treat it as Private (the computer will be discoverable) or Public (it won't be). See here for more info:

https://www.howtogeek.com/245982/whats-the-difference-between-private-and-public-networks-in-windows/

While it has convenience value for legitimate users looking for devices and resources on the network it really doesn't offer much for a malicious user compared with more dedicated scanning tools. Turning it off to try and protect things is very much security via obscurity IMO - if you've got a discoverable machine called "SuperSecretServer" with an open share called "PlainTextCreditCardDetails" then the fact that it's discoverable is NOT your big problem!

Other devices that show up there are usually doing so because they are UPnP enabled (typically things like printers, media streamers, that kind of thing) where being easily discoverable is often something they aim for.


Website sent me my new password (after reset) in clear text

No, this does not indicate whether they are storing your password in plain text or with reversible encryption. They might be, but this still leaves other possibilities open. All you know for certain is that they created a new password and emailed that new password to you. That password may well be hashed appropriately for storage in their system.

However; this is a poor security practice and I would absolutely gripe to them about it, and point out that such a poor practice in one regard makes you suspicious of the quality of their security practices in other regards.

Email is not secure, and they shouldn't be doing password resets by sending you a new password in any form, anyway.

EDIT:

I just installed an open source file transfer application on one of our servers to check it out.

I confirmed that it is hashing passwords for storage in the database, which increased my comfort level. Then I created a couple of accounts and realized that the stoopid thing emails the passwords at the moment of account creation in plaintext to the new account holder.

I am beside myself. One of these was actually a fairly sensitive account, for which the account holder should absolutely not have to change the password (but will now be forced to do).

This utterly stupid, utterly non-secure nonsense has got to stop. A plaintext password should simply never, ever, under any circumstances EVER be emailed. Ever. End of discussion. That entire mode of thinking should be quashed instantly whenever it is encountered, and public websites that engage is such practices should be punished for it.

END EDIT:

They should be doing password resets by sending you something like a reset link with a (long, complex) embedded code/token, which permits you to choose your own new password, over a secure (HTTPS) connection. Ideally, upon clicking that link, you would still be required to answer another security question or two, in order to confirm your identity. Or some kind of 2FA should be implemented, where you click the link, then you have to punch in a code that was texted to your phone. And I still feel that you should have to answer at least one more security question on top of that, because 2FA is still utterly susceptible to having your phone stolen or cloned.

That reset link should have a very short valid lifetime. In my opinion, it shouldn't work for more than about 5 to 15 minutes. If you don't get around to changing your password in that time frame, you can always request a new link when you're ready.

If you ever encounter a site or service that sends you your existing password in plaintext, then you must assume they're storing it in plaintext or using reversible encryption.


PKI usage in a cluster; per application instance or per application?

Generally speaking, each private key should be unique, and private keys should not travel.

If you have several "applications" that expect HTTPS connections (on port 443, SSL/TLS handshake...) and that run on the same machine, then the application are not, actually, doing the SSL. The SSL is handled by the Web server frontend (say, an Apache or IIS): that frontend does the SSL, then (only then) receives the HTTP request, learns the target path, and thus knows to which application the request shall be dispatched. In that kind of setup, the private key and the certificate are not owned by the applications, but by the frontend. In that model, you would give one private key and certificate per machine.

The paragraph above assumes that your "micro services" really are all registered on a common HTTP+SSL engine, as is expected if they all use the default HTTPS port (443) and the same IP address. You could do otherwise, e.g. run the different services on distinct ports (the connection URL will then have to include the port name), or even on distinct IP addresses (if each machine owns several IP addresses). In that case, each micro service may run its own HTTP+SSL engine, and thus have its own certificate and private key.

There are two main reasons why you would want to make several private keys and certificates:

You want to give certificates to systems that are not equivalent to each other in terms of security, e.g. they belong to distinct customers who do not fully trust (or even know) each other. The idea is that knowing a private key used by a server allows (conceptually) impersonating that server. Similarly, having distinct certificates allows revoking one without revoking the others.
Private keys that travel around are "less private". It is best when private keys are generated on a machine and never leave that machine. Thus, if you have 10 servers, you would want to have (at least) 10 private keys. Moving private keys around safely is doable but requires care (copying over SSH connections should be OK).


How safe (for privacy/security) is ZIP for file encryption of backups on a flash drive

There's plenty of apps out there to [...] figure out the password.

Well, yeah, those are dictionary attacks. It doesn't matter if you're using AES-256 or FOOBAR-1024, if you choose a weak password it can be broken easily. The only thing that helps slightly against dictionary attacks is using an expensive key derivation function. From a comment on the question below, it appears that 7z uses 2^19 hashing operations to derive the key, probably giving some protection:

https://stackoverflow.com/questions/12470378/how-key-derivation-and-key-verification-functions-are-implemented-of-a-7-zip-arc

  Is encrypted 7z/zip safe? How safe is it?

I haven't reviewed their code myself, but I would hope they are as strong as the underlying cryptographic primitives (e.g., 256 bits of security for AES-256). If a tool is so broken that it is not clear from its interface or documentation which cipher is being used at which bit strength, then don't use it.

256 bits of security is plenty safe; in fact, your password will almost certainly have fewer bits of real entropy than 256 unless you are very hard core.

  Are there any alternatives for encryption that you don't have to install any new programs to use?

Depending on your definition of "install", you can use a custom LiveCD or virtual machine to run programs without "installing" them.

  Which is better to use? 7z or zip?

zip, assuming WinZip AE-1 or AE-2 format is used for actual encryption. It uses standard protocols like PBKDF for key derivation, and others have probably written compatible software, so any discrepancies would've been noticed by now. 7z is just not in the same league.

OTOH, if you're using a random zip tool's "password protect archive" feature that doesn't mention AES-256 or PBKDF, it could be god-knows-what.


Is privacy a part of security? (Bruce Schneier)

Yes, privacy is a vital part of security. Privacy is the result of a person having the ability to control information about themselves. That is in general granting to individuals the power to make choices about who they share their information with.

Allowing individuals to have the power to keep issues confidential is critical to their security, because it allows them to deny information to threats.

In security jargon a threat is a person capable to doing damage to a target by theft, destruction, or other means.

For example, if a person is the potential target of a theft or assault, they would be wise to keep their location confidential. They could reduce their risk by not disclosing their possession of items that would attract a thief, like jewelry or large amounts of cash.

A person who might be at risk of discrimination because of their nationality or religion may decide to keep that information private.

There are many good examples of how keeping information private provides reduction of risk (in turn greater security) and those questions are accepted here as long as they related to IT.


Is allowing users to sign out of all other sessions good or bad?

Having the ability to terminate all sessions that exist for a certain account is a good idea, just as it is a good idea to have 'forget me everywhere' functionality.

A user's account should be associated with a single user. If this user wants to sign in on multiple devices, they should be able to do so. Just the same, they should be able log themselves out on any and all devices they previously logged in, if they choose to do so.

The benefit is of this is that it would log out any sessions that still exist because the user forgot to log out (which is a real possibility, mainly with shared devices).

The idea that this functionality should not be implemented because it could be misused when an account is compromised, is a non-argument: if a person gains unauthorized access to an account, they can do a whole lot of bad things. Logging out any active sessions would be one of the least damaging ones, while at the same time having a fair chance of alerting the account owner of the fact that something is wrong (which is a good thing).

(The strength of the authentication scheme (1-factor vs multi-factor, as mentioned by some other answer to this question) has little to with this.)


School website exposes root FS, where to report?

Get in touch with the school by any means necessary. There will certainly be a 'contact us' form on the website; if not, pick up the phone and do them a favour and call them. Even if they are in a different country, VoIP calls are quite cheaper today and I'm sure you can afford the cost.

Explain the situation in good details, making clear that your intention is not to expose anyone's privacy nor to ask for a ransom but that you are doing your duty as a responsible citizen. This is because often non-techie tend to panic and call the police pointing you at the culprit.

If you are able to, offer your advice on how to protect the webserver or explain what should be done so they can independently verify your advice by going e.g. to OWASP or asking questions on Security Stack Exchange.

Offer some degree of personal information e.g. how to get in touch with you, what is your name, and make your e-mail as professional and polite as possible. It is very likely that it happened as a genuine mistake so there is no need to add fuel to the fire that will generate.

Imagine the person on the receiving end is e.g. your grandmother (or any non-techie -- no offense for grandmothers out there). How would you explain it to them? What details would you offer first?

Make sure you cc: other people e.g. the principal, vice-principal etc. so that there can be no "your word versus theirs" if it comes to litigation.

Lastly, if you think the data exposed is really dangerous, make it clear that you will report this to the police if you do not get an answer by XXX days (be reasonable and account for school holidays).


Is your communication in same subnet safe when an attacker initiates a ARP Poisoning attack?

With an attacker on the same broadcast domain (in this case subnet) it is relatively easy to perform an ARP spoofing attack.

Within a broadcast domain TCP sequence prediction style attacks become much more valid if the attacker can simply listen for the sequence number in promiscuous mode instead of actually guessing it.


Is Docker Desktop safe to use on a unsecured network?

Does this mean that a machine connected to the same network can access Docker on my machine?

Just like regular Docker, containers aren't directly exposed to the network unless you manually expose specific ports on them. host.docker.internal is a special value used to ensure the host is reachable from containers, even if its address changes.

Is Docker safe to use on a unsecured network?

In general, probably, but you'd need to be careful if you are exposing ports to the unsecured network, or if your containers are connecting to outside services using non-secure protocols.
See the docs for more details.


Authentication & Authorization via md5(userid + secret + endpoint + payload)?

The concept of calculating some form of hash over (url + request payload + ...) is not something uncommon. I wouldn't say it is flat out wrong.
There are a few problems with this specific implementation, though:

MD5 is not considered secure. SHA-2 would be a much better choice.
There doesn't seem to be any protection against replay attack. Adding e.g. unix timestamp in the header and including it in the input to hash calculation could help. Server-side timestamp validation necessary.
Including nonce in the payload could help. No two otherwise same requests would result in the same hash.
I find calculating a hash over an input including secret a bit unusual. Why would you like to do that? More common solution would be to calculate HMAC, e.g. HMAC-SHA256 instead, and exclude the secret from HMAC calculations. HMACs provide you with authenticity, as only the party with access to the key can generate correct authentication tag. I believe authentication was the reason why the secret was originally included. With key-based HMACs, the use of uuid-like secret could be abandoned.

I wouldn't be worried about the payload being case-sensitive, extra whitespaces etc. If you implement it right, it will work. And then obviously the server has to calculate the hash (or better HMAC) and compare it with the one it received, in case of differences I expect it would respond with 401.


Wireshark HTTP continuations (Hydra HTTP version)

Hydra's HTTP Form module only uses HTTP/1.0 as can be seen in the source.  You could probably modify the source to send HTTP/1.1, though I can't guarantee its implementation is otherwise conforming.  I've never seen a server which absolutely refuses to speak HTTP/1.0, and many tools use it by default, like wget.

The Continuation you see in Wireshark is because the full HTTP response is not contained in that packet.  There should be a previous packet (if you captured it) that has the beginning of the HTTP response.

If you need a tool to test an application for HTTP passwords and need to speak HTTP/1.1, I believe ncrack supports that.


Can public certificates be password-protected?

What would be the point ? A public certificate is public: if you need to password-protect it, it would mean your security model is flawed. Therefore, there is no standard way to store an X509 certificate in a password-protected form.

That being said, in practice, you can place a cert into any kind of container: a PGP protected file, a ZIP file, a password-protected PKCS#12 (basically, a PFX) or any type of container.


How does client-side cookie encryption enhance browser security?

After your edit, the question is about something entirely different.

That commit is about encrypting the cookie database with an user-specific key, for Windows' users. On a multi-user Windows environment, it's common for a user to have access to other users' files. Encrypting the cookie database with a key held on the user registry and derived from user password, other users cannot access that data.

This increases cookie security, because any attacker getting the database file will not be able to read the cookies. To read the data, the attacker must get the computer while the user is still logged in, or compromise the password.

But the cookie database is not as valuable as the saved password storage.


Finding ecc private key from plaintext and public key

A good first step would be to introduce something similar to a session key, and then using a block cipher to encrypt the actual payload.

Encryption would work like this:

Generate a random passphrase which should more or less be globally unique and should never be reused. If you need to edit the encrypted file and reencrypt, generate a new key.
Encrypt that generated passphrase using ED 25519, and store the output at the head of the file along with other metadata (ie: the IV for your block cipher, etc.).
Sign your encrypted passphrase using ED 25519, so you'll never decrypt something that wasn't generated by you. Store this next to the encrypted AES key in the previous step.
Using your random passphrase for your block cipher, encrypt the payload using something with authentication like AES in GCM mode, or AES in CBC mode with an HMAC.
At the end of the file, generate a signature of the encrypted ciphertext, proving that you, the holder of the private key, vouch for its integrity.

This gives you a lot of benefits. First, you're now using a standard block cipher for your payload, and AES (in the right modes of operation) isn't vulnerable to known plaintext attacks. Second, now that you're using a standard block cipher, encryption and decryption will be much faster operations in CPU time. Third, using a block cipher mode which has authentication gives you integrity, and by signing the ciphertext, you assert that not only has the message not been tampered with, it was you who created it.

Step 5 above may not be necessary, as your signature in step 3 should be good enough combined with an authenticated block cipher like AES in GCM mode or CBC with HMAC.

Decryption looks like this:

Decrypt your random passphrase using ED 25519 and check its signature. If everything looks good, proceed, otherwise fail.
Use your decrypted passphrase to decrypt the ciphertext using your block cipher. Your block cipher should be providing integrity support (GCM or CBC+HMAC) and should fail if anything was tweaked.
At the same time that your decrypting each block, pipe the original ciphertext through the ED 25519 signature verification method so you're not having to rescan the entire payload once you're done.
After you've finished decrypting the ciphertext, validate that the signature (generated in step 5 above) is valid.

This should provide a pretty robust encryption system.

Since I see now that you're mainly looking for message authentication, I've devised another solution which just does that.

Generating message authentication codes:

Generate a random key to use with your HMAC.
Encrypt and sign that key and stick it at the front of each message.
Run your HMAC over the entire plaintext.
Append output of the HMAC at the end.

Validating message authentication codes:

Decrypt and validate the HMAC key at the head of the message.
Generate an HMAC over the plaintext as above.
Compare your HMAC's output to the stored HMAC at the end of the message.

Provided that you use a good hash function for your HMAC (ie: SHA-256), this should be a pretty good solution. It effectively removes your concern of known-plaintext attacks for ED 25519 (not that they exist, necessarily), and will generally be a much faster solution in performance than doing signatures natively in ED 25519.


Set up a WEP network as safely as possible

Consider a WEP-network as a room with public access. Think of it as a dark room and people communicating by calling each other's names audible to everyone.

All means to identify persons eligible to enter are rendered futile due to the nature of that room. After cracking the WEP-key any MAC-address can be spoofed. You cannot increase security for any device within that network, because there are no means to cut off communication effectively or in other words to throw someone out of the room, as you can't see that person.

If you consider your WEP-unprotected network public, you can limit further access to a more secure network segment by enabling access via VPN. This can reduce harm to devices and services located behind the VPN-gateway.

The only faint possibility to keep attackers slowed down eavesdropping within your WEP-protected network is to use heuristics to throw them out of your network as soon as they do „unusual“ things in comparison to the devices normally connected to your network. But keep in mind, that this will lead to a false sense of security as it relies on obscurity of some behaviour of your common network devices. And there is no security by obscurity. Also honeypots used to detect attackers might work only once. Every measure you can use to identify attackers can be analysed by the attackers themselves to circumvent it.

Summarised you can:

protect network devices within that segment, if they can protect themselves i.e. up to date operating systems tuned to a security level that you might use to log into a public WIFI-network
protect attached network segments by enforcing usage of VPN for access

you cannot:

protect credentials used in that segment
protect obsolete devices within that network from being attacked
protect communication which doesn't use an encryption totally unrelated to the authentication mechanisms of WEP.


Where are certificates used to prove identity and why aren't DNS responsible for the job?

do sites you log into such as Facebook (or this one) use asymmetric encryption?

Yes. Both actually. Regular TLS uses both asymmetric encryption (for the certificate part and to negotiate a bulk-encryption-key) and symmetric crypto (for the bulk encryption part). This combination is for speed, because the usual symmetric crypto here is about 100 times faster than the asymmetric part.

This combination is known as a Hybrid cryptosystem.

  Isn't this more of the roll of the DNS server?

Yes and no. While you could do it that way, and while there are attempts to store (or at least mark) valid crypto keys directly in DNS, this is not (at least right now) the usual way of doing this.

What does that mean? One of several ways that a CA may check the validity of your claim to a particular domain-name is by sending you e-mail to the admin@-account of your domain.

And if somebody manages to insert themselves between the CA and their DNS server at that precise moment, they can fool the CA. So if someone has hijacked those wires (e.g. bribed employee, e.g. NSA's QUANTUM router exploitation program), then the CA may be fooled into issuing a certificate to them.

If that malicious actor then later uses the same man-in-the-middle-trick when a regular person visits the site with the stolen/misissued certificate they will get the green-lock and won't notice. (Unless extra care has been taken by the site operators against that. E.g. by pre-loading certain browsers with known-good site certificates.)

  are the public keys usually not provided by the owner them self and actually the certificate authority (since [according to here][1] the public key is extracted from the certificate)? For example when I connect to Facebook is its public key given to me by DigiCert Inc, not actually Facebook?

No. While some CAs offer this as a convenience/service it's not required technically that they know both public-part AND private-part of the pubkey/privkey pair. (And I'd run screaming from a CA that made such an offer.)

Instead you send them the pubkey and have them sign (and know) just that.


Protection against DDoS when using proxies

I would suggest that the simplest defense is probably to buy access to a CDN that provides protection against DoS.  Take a look at Cloudflare and Cloudfront.  You could also look at MaxCDN, Akamai, EdgeCast, level3, Rackspace, VPS, Cotendo, Limelight, Cachefly, Highwinds, and many others.

Why use a CDN?  Three reasons.

First, it will benefit both performance and security.  It will make your site faster.  And, if you get a flash cloud or an unexpected spike of visitors, it'll help keep your site fast, responsible, and available.  And, of course, if you come under DOS attack, the CDN has the capacity to absorb the traffic and ensure your site stays available.  So, this is a win-win for both security and site performance.  (How often do you see that?)

Second, it is affordable.  A CDN is relatively inexpensive, and is almost certainly cheaper than the staff time it would take for you to futz around with defending yourself against DOS attacks and to keep up with the latest DOS techniques.

Third, the CDN can probably do a better job than you can.  Because of its scale, the CDN probably sees thousands of DOS attacks a year (on hundreds or thousands of web sites), so it has a chance to accumulate statistics on the common patterns, learn how to detect DOS attacks, and work out what defenses work best.  Also, because of its scale, the CDN may be able to afford for its employees to stay up-to-date on the latest attack techniques being used in the wild.  And, the CDN may be able to afford to develop custom automated defenses, since they'll be applicable to all its customers.

So, take a look at CDNs as a possible defense.  That may be simpler to deploy and more effective than the approach you are taking.


Why is TLS_FALLBACK_SCSV secure against a MITM attack?

At the end of the handshake, Finished messages are exchanged, under the protection of the newly negotiated algorithms and keys; in particular, the contents of these messages are protected by a MAC. The contents of the Finished messages are a hash of all preceding handshake messages. Any external manipulation of the ClientHello message as it transits from client to server will be detected at that point: the client and the server won't work over the exact same ClientHello contents, thus won't obtain the same hash value for the Finished messages.

This protects the handshake against alteration as long as whatever alterations the attacker performs don't allow him to immediately break the whole crypto layer. In the case of the Poodle, even if the attacker succeeds in forcing SSL 3.0 usage, he cannot destroy the crypto right away, and thus cannot "fix" the Finished messages.


Alice and Bob authentication and integrity problem

Yes, Mallory, a Man-In-The-Middle could intercept communications as follows, and pretend to be Bob to Alice, and Alice to Bob:

A → M → B: w{nA}

B → M → A: w{nA+1}

A → M → B: (F, H(F), w{H(F)})

Step three requires a hash collision in order to substitute a file - Mallory could have created an evil file, E, and can calculate H(E).

Mallory observes traffic and waits to see a file transfer happen where H(F) = H(E).

Once this happens, Mallory manipulates the traffic so instead of

(F, H(F), w{H(F)})

being sent to Bob,

(E, H(F), w{H(F)})

is sent instead. Note that as H(F) = H(E), w{H(F)} will also equal w{H(E)}.

The protocol can be fixed by the nonce and secret being part of the file transfer stage:

A → B: (nA, F, H(nA | w | F))

Steps one and two are no longer required. As Mallory cannot hash their own file with w, they have no way of detecting a collision.

Of course, Mallory could replace every file transfer F with E in the hope that a hash collision occurs, however Bob would notice that something was amiss.

In order to fix that in the protocol, HMAC(SHA-256) could be used rather than a weak 40 bit hash.


Why are there places that still advises to use complex-only passwords?

The same reason that people are still pushing for input sanitation in 2015: the security world moves very slowly; they adopt things at a snail's pace, and the end-users are orders of magnitude slower at changing their ways.

Once people have become accustomed to a way of doing something, anything that is contrary to that is going to be rejected for a long time, until enough people are crying about it. Even then, you're going to have a few holdouts like Dave. That's one of the core reasons why people are still proclaiming outdated practices.

Getting older people to use a password manager may be next to impossible.

  People will not remember complex passwords in every 90 days.

Most people write their passwords down and put them on their desk in the form of a sticky note, or they type it enough times to remember it, or they even store it in a text file on their desktop (groan), or they set it and forget it with a long-lasting cookie.

And if they forgot it, no problem! They'll just start the password reset process. This is normal behavior for most users.

  Is there some kind of old standard for the password rules? Or people don't know the math?

The vast majority of people, including developers, don't understand better password practices at all. Even less people understand the math or reasoning behind why something should be the way it is.

If people aren't knowledgeable, and you appear to be in the know, then people will blindly accept what you tell them... but even if they agree that password managers and pass phrases are better, old habits die hard.


No, she cannot remove the colored pen if she just takes a screenshot.

How Snapchat stores photos is a question for Snapchat themselves. Although they will most likely deny that they save them (they do), it all depends if they store the photos in layers or an all together, un-editable screenshot.


Is it safe to use the official Facebook apps in a public Wifi?

Short awnser: Yes and No

Explanation:

Facebook Claims they use TLS/SSL everywhere, but after a bit of poking around using Wireshark, i found out that logging in, visiting timeline etc. all go over HTTPS (no port 80 connections detected), when visiting certain elements though, like apps/games, photo's and such, i detected HTTP connections through port 80.

Also note that some optionsmay vary per OS, i think i heard there was an option with certain OS's to manually turn on/off the SSL/TLS function, but i cannot verify this nor find it on google.

Long story short, it seems that the login part is secured, but photo's and clearly 3rd party apps aren't, making it a partially encrypted service.


Should I hash my passwords even if I am only allowed to generate limited traffic?

Yes, you should hash your passwords. Storing passwords in plaintext is not acceptable.

No, it does not affect the amount of traffic your site require. The hashing should be done server side, so it does not affect what is transmitted from the client.

Hashing the passwords protect them from theft once they are stored in your database. To protect them from theft when they are transmitted from the client to the server, you need to use HTTPS.

Some related reading:

Why should I hash passwords?
How to securely hash passwords?


Is Stegosploit a real concern with modern browsers?

To answer the question: The website admin must be in on the exploit.

The encoding technique is there to obfuscate the actual exploit scripts, thus flying under the radar from current detection methods. It still requires HTML/Javascript to be on the webpage in order to decode and run the exploit.

That is to say, if I had encoded an exploit into pleasedontrunthis.jpg, I (the web admin), would still need to open the image like so:

<script src="pleasedontrunthis.jpg">

To answer the question in the title: Not really.

This is an encoding technique, not an exploit. It requires the would-be attacker to serve malicious Javascript in order to... server malicious Javascript. This technique could provide sufficient obfuscation to hide itself from both automated and human scanners for a potentially longer period of time than exploits which offer huge walls of text simply by hitting F12.

In practice this means that someone could hack a website (ie, through a Wordpress vulnerability), and deliver a silent exploit that would take longer to find.

In reality, if an exploit in the toolkit was capable of pwning your machine, it would have most likely pwned your machine either way. The reality being that not all malicious code is going to make itself glaringly obvious, so there's always an inherent risk when deciding to allow it.


Is it practicable to use font to visually decrypt ciphertext

It is not quite clear how you exactly imagine it. But given the description so far I assume that you just map for example the character "Z" to something shaped "A" and then replace every A in your page with Z which will be displayed as A on screen due to the special font.

Apart from being a nightmare for any user relying on screen reading it is probably easy to crack to: For one one could use OCR to find the real text, compare this with the HTML source code and thus build a mapping between source code character and displayed character. Even this might not be needed because one could do some statistical analysis of the HTML source code and some comparison again a dictionary to get the mapping between source code character and displayed character because this is essentially just a substitution cipher based on single letters.

  This font is create with some One Time Pad key.

I'm not sure what you really mean with this. But it might mean that every mapping between character in source code and displayed character is done only once instead of reusing the same mapping all the time as I've described above. While you don't have an easy to crack substitution cipher this way it means that you would need a lot of fonts for each HTML page. This would be even more be a usability nightmare than with a single font. But, OCR could still be used to extract the text. Essentially the protection is about the same as you would just make a photo of the page and just put this photo online.

Thus essentially: it makes it a bit harder for web crawlers but at the cost of making it harder for end users too.


With openssl, why does a decrypted & re-encrypted file differ from the original encrypted copy?

One of the basic goals of cryptography is that someone who intercepts encrypted messages shouldn't be able to learn anything about the unencrypted originals. If you can determine whether two encrypted messages have the same content without actually decrypting them, then you've found a weakness.

To prevent that, an encryption scheme must produce different results when encrypting the same message twice. The padding that is added when you do an RSA encryption is different every time.

If you want to study RSA without padding (a.k.a. "textbook RSA") you can use the -raw option to rsautl. The input must be exactly the size of the key modulus since there's no padding. Just make sure you don't use it for any serious application.


How does the padding scheme impact the security of encryption

Short answer: Don't sweat it.  In most cases, the choice of padding method doesn't matter.

Longer answer: why it doesn't matter.  As long as you use proper crypto design practices -- in particular, as long as ciphertexts are properly authenticated -- I'm not aware of any way that the choice of padding affects security (with one exception, see below).

It's true that if you fail to authenticate the ciphertexts, then there can be attacks, as @Thomas explains.  Then again, if ciphertexts are not properly authenticated, you've probably got a host of other problems, so you shouldn't blame this on the padding scheme.  Cryptographers know that if you encrypt something, you really should be authenticating the ciphertext; failure to do so is a classic rookie mistake that can open up serious security flaws.

In short, if you're following good crypto practices, the choice of padding shouldn't matter much for security (and if you're not following good crypto practices, you may have bigger problems).

The exception: a case where it does matter.  OK, now we're down to the fine print.  This is where I admit that the above is a bit of an oversimplification.  There is one situation where the choice of padding may be very important to security: resistance to traffic analysis.

Encryption does not conceal the length of the messages being encrypted: the encrypted message typically reveals the length (or approximate length) of the message that was encrypted.  In some contexts, this can be highly problematic.  For instance, there are contexts where revealing length information gives away the entire store: it reveals the stuff you were trying to keep confidential.  (See, e.g., Chen et al's astonishing side channel attacks on SSL-encrypted web applications.  Among other things, they showed that an eavesdropper who observes the lengths of network packets while the user is typing in a web search query can infer what the search query was.  I think Google fixed the problem, but it was a stunning, eye-opening example of a general risk that was previously known.)

If you are in a context where message lengths reveal sensitive information, then you have a problem.  The standard defense is to pad the messages before encryption, so that the ciphertext length does not reveal anything about the message lengths.  One way to do this is to pad all messages out to a fixed length, before encrypting.  Another (less secure) way to do it is to add padding of a random length, with enough random padding that the random noise obscures the signal and prevents an attacker from learning enough information about lengths to do any harm.  So, in a context where we need to prevent traffic analysis, the design of the padding scheme becomes critical, and standard padding schemes are probably not going to be enough: you may have to do something special.


Attribute Certificates and Access Management

In real real life, attribute certificates don't work. Nobody really supports them. One reason for that is that certificates are, by definition, an asynchronous distribution method for information: a certificate binds some values together (for a "normal" certificate, this is a name and a public key; for an attribute certificate, the holder name is bound to the attribute values) and the binding is verifiable without talking to a central online repository. This is what the cryptographic signature on the certificate is about: to allow for offline or at least semi-offline verification.

The flip side of offline verification is that there is no way to immediately cancel a certificate. There is revocation, but it is asynchronous in nature: when a certificate is revoked, this becomes effective within a few hours or days (depending on how often CRL are produced). Asynchronism is exactly what you do not want for authorization: if you want to block somebody because of suspected malicious activity, you want to do it now, not next week.

It is possible to make synchronous revocation by making all clients obtain fresh revocation information everytime, by talking to an OCSP server, but this voids the reason why you wanted a certificate in the first place. The whole point of using certificates is to avoid having to talk to an online server every time you need some authorization information.

So, basically, certificates and authorization do not mix well. This makes RFC 5755 attribute certificates for authorization quite useless. Correspondingly, they are not much used.


Using Diffie-Hellman to verify SSL Certificate?

I don't think you understand fully what you are doing so I try to explain your steps:

  ...start by establishing a secure connection between the App and the Web Server using Diffie-Hellman..

This would be an anonymous DH connection because you don't verify the identity of the peer. And you can't verify its identity because you have no trust anchor yet. Because you don't verify the identity you cannot be sure who you are talking with. This means also that MITM attacks are possible so you should not trust any data you get inside this connection.

  ... to transfer the certificate, so that when the SSL connection is being established, I can verify if the certificate is correct.

This means you transfer a trust anchor for future connections using an untrusted connection which is open to MITM attacks. There is no way to verify that the certificate you got is actually the certificate of the peer you liked to talk with and not the certificate of the attacker.

In summary: You replace "no verification because no trust anchor" with "verification against actually untrusted trust anchor".


In SQL, prepared statements often use the ? as a placeholder. If they used parameterised queries but did not sanitise the inputs, then starting the password with a ? could confuse their code and result in an error.

This does not mean that this requirement is justified. It means that they know that they have insecure/buggy code and are forcing the users to enter their passwords in a certain way instead of fixing their code.


DES-CBC: Two ciphertext blocks c2 and c5 are equal. Why would this leak information?

Lets think about this:

Ek = cipher "E" with key "k"

M# = Plaintext message block "M" number "#"

C# = Ciphertext block "C" number "#"

CBC mode is:

Cx = Ek(Mx XOR Cx-1),  or in english:  To get the cipher text for the current block number, you perform the keyed encryption of the value obtained by taking the plaintext message block of the same number, and xor'ing that against the previous numbered ciphertext block.   That's the definition of CBC.

So if you have a series of CBC encoded blocks, and you realize that C2 and C5 are the same cipher text  (ie, C2 = C5), you know:

C2 = Ek(M2 XOR C1)

C5 = Ek(M5 XOR C4)

And since C2 = C5, that means:

Ek(M2 XOR C1) = Ek(M5 XOR C4)

By the power of the maths, that means more importantly that you ALSO know:

AHA!:

(M2 XOR M5) = (C1 XOR C4)

Since you have been observing the ciphertexts, you not only know that C2 is equal to C5 but you've also captured C1 and C4 in your observations.

So you calculate (C1 XOR C4) and you have a value, which means you have a real number and not a variable on the right side of the equation marked "AHA!!".

That value is equal to (M2 XOR M5), as noted above.

So under your hypothetical, where your professor says you ALSO know plaintext M2, you are able to plug that in on the left side and solve.

You know that your known M2 XOR'd against your still unknown M5 equals the known value you calculated by taking the XOR of C1 and C4.

Back to basics.  The magic of XOR is this:

If A XOR B = C, then B XOR C = A,  AND A XOR C = B.

That's how RAID disk arrays with three disks work, by the way.

Result:  Duplicate ciphertexts in CBC combined with a known plaintext corresponding to one of the blocks permits to you calculate the plaintext of the other matching ciphertext block.


It is not possible to hide the SNI information if the server requires it to serve the proper certificate. There was discussion on encrypting this information in TLS 1.3. But this idea was abandoned since this would require establishing an additional encryption layer and thus adding additional overhead to the connection establishment. Apart from that this information might leak anyway due to DNS lookups and of course also through the certificate the server sends, which is in plain too. Thus if you want to better protect your privacy you need to use an additional encryption layer yourself, like a VPN.

For more details see also

Why do HTTPS requests include the host name in clear text?
How is HTTPS/SSL able to hide destination website that one is connecting to?


Suppose you do collect some evidence. What are you hoping to accomplish? You really want to keep working for someone who installed spyware on your computer and lied about it? Do you truly think this relationship will flourish as a result? And you think this will stop once you "lock him out"?

Your first step needs to be contacting an attorney trained in employment law. At the very least, you might have some damages owed to you. From him you will learn what burden of proof you need to bear in order to pursue a legal case if you can't shake your boss down for money.

Evidence collection is hairy. Attempts to collect your own may not be admissible in court or your methods discredited, as you are not trained in evidence collection. Furthermore you could open yourself up to being sued yourself-- depending on the contents, attempts to upload pcaps or logs offsite can yield claims of intellectual property theft against you.

So you really need to consult a local attorney who can guide you through what is less a technical issue and more a legal one.


Point several HTTPS domains to the same web server

There is no magic in there: the user will see what the web server sends, and the web server will send what you tell it to send.

You said that both URLs will share the same IP using a DNS CNAME entry, so you will encounter a different behavior depending on the browser supports SNI or not. SNI is supported by all decently recent browsers and allows them to indicate the server name during the early phases of the SSL handshake, thus allowing the web server to select the right certificate to show to the client.

With browsers supporting SNI you simply have to configure different virtual hosts (or equivalent depending on your web server) based upon the server name, each on referring to their own certificate but most probably sharing the same document root and other properties.
If you would like to support older browsers, when receiving a request from such a browser the web server, having received no server name, will always select the default virtual host and use the configuration contained therein.
If you would like to be perfectly clean and show the right certificate even for those clients, then you will need to use a different IP for each server name. Otherwise, it will be up to you (hem, your customer) to decide to what extent you tolerate a graceful degradation of your services for clients using old browser (the website will remain reachable in any case for these clients: older - and therefore by definition insecure - browsers will have a security warning mentioning the certificate from the other domain or a specially generated default certificate, depending on your configuration and choice).


Is there a key length definition for DH or DHE?

Key sizes are traditional. By this I mean that there is no universal, mathematically accepted notion of "key size" which will match all algorithms. For symmetric algorithms, it is customary to have keys which are sequences of bits of a given length n, such that all possible sequences of length n (there are 2n of them) are acceptable keys; in which case cryptographers tend to speak of n as "the key size". There is already room for trouble here, with DES, which has 64-bit keys out of which only 56 bits are used, so DES can be said to use 56-bit keys. Similary, 3DES uses a 192-bit key which is in fact a 168-bit key; and, to further the confusion, there is a known algorithm which (theoretically) breaks 3DES in effort 2112 so 3DES is sometimes said to have security level "112 bits". Another troublesome algorithm is RC2, which has an extra "effective key size" parameter which lowers the resistance of RC2 against brute force down to a configurable value, even if the key is longer.

For asymmetric cryptography, things are more complex since public and private keys no longer are "just sequences of bits". For instance, a RSA public key consists of two integers, the modulus and the public exponent. It is traditional to use the size of the modulus as "RSA key size", even though it is not possible to fit an entire RSA public key into a sequence of bits of that size (because there would be no room for the public exponent).

For Diffie-Hellman, the standard is ANSI X9.42. This standard consistently avoids to speak of "the key size". Instead, it always talks of "the size of p" and "the size of q". Both sizes are important for security, but not within the same range. Namely, DH works with numbers modulo a big prime p, and with a generator g. The generator g "generates" a subgroup of integers modulo p: if you consider the successive values 1, g, g2, g3... modulo p, you will get back to 1 at some point. The order of g is the smallest integer k > > 0 such that gk = 1 mod p. Mathematics tell us that k necessarily divides p-1. With these notations:

DH can be broken if discrete logarithm modulo p, with base g, is broken. There are some algorithms whose cost depends on the size of p, so you want p to be big enough to make these algorithms too expensive. The best known algorithm of that type is a variant of the General Number Field Sieve and the current record, for a "random" modulus p is 530 bits (it is possible to craft a special-form modulus p which makes discrete logarithm easier, but a random prime will avoid that with overwhelming probability).
Discrete logarithm can also be broken in a time which depends on both the used exponent size, and the order of k. If, within Diffie-Hellman, a party selects its private exponent in a range of t successive values, and the largest prime factor of k (the order of g) is q, then the algorithms of that type will break DH in a time which depends on the smallest of q and t. These are the "generic" algorithms, whose running time is proportional to the square root of q (or t, if it is smaller).

So basically you have three sizes:

The size of t for DH private key generation: each involved party generates a random DH private key in the 1..t-1 range.
The size of q, which is the largest prime factor of the order k of the generator g.
The size of the modulus p.

In some protocols, q is generated explicitly, thus with a known size, and then p is generated so that p-1 is a multiple of q. Then g is selected to have order exactly q (gq = 1 mod p). In these protocols, we set t = q: q is known, and systems generate private keys in the 1..q-1 range.

In some other protocols, p is generated as a so-called "safe prime", i.e. such that (p-1)/2 is also prime. In that case, p = 2q+1. For these protocols, the DH private keys will be generated in a smaller range t, typically 160 to 256 bits.

In yet some other protocols, q is not known at all, and just assumed to be large enough. This is the case of SSL/TLS (for DHE cipher suites, the Server Key Exchange message contains p and g but not q, so the client does not know q). There again, a range t is used.

We want n-bit security for some n, meaning that breaking the algorithm should have average cost 2n operations. To achieve such a security level, the size of q and the size of t shall be at least 2n bits, but p must be much larger. To give figures, it is generally estimated that if you look for n = 112 (112-bit security, which is what you get for symmetric encryption with 3DES), then you need q and t to be at least 224 bits, but p should be at least 2048 bits.

Summary: when talking about DH, a "big" size like 1024 or 3072 normally means "the size of p", while a "small" size like 160 or 256 normally means "the size of q" or "the size of t". There is no standard for "the size", and indeed the standard does not define a unique one-size-fits-all size.

In your Wikipedia quote, the "3072 bits" is the size of p (the modulus). The value y, which is a DH public key, is in the 1..p-1 range, thus also a number of 3072 bits (or slightly smaller). The private exponent x is chosen in a range 1..t-1 which may be as big as 3072 bits as well (or even bigger) but a much smaller range, down to (say) 256 bits, is perfectly acceptable for security.

As @Polynomial says, see this site for comparisons between key sizes.


Does including the username in a password make it less secure?

In a word, no. But that's not what usually happens.

Anything added to a password either makes it more secure, or no change at all. But since appending/prepending your username is so common, it tends to fall in the no change category in many use cases, which makes password strength verification very difficult.

For example:
Username: JonathanParr27
Password: JonathanParr27!

Here, the password is simply the username with a ! appended. The password does contain a capital, lowercase, digit, and punctuation, plus it's 15 characters long. By typical metrics, it should be a good password. But an attacker will try appending numerals or punctuation to the username on brute-force attempts, so now this long, complex password can really just be reduced to username + !, which is quick and easy to guess.

As such, most places with secure password requirements will simply say, nope, if you use your name in your password, it's no good. This both simplifies password strength verification and also puts an end to the silly practice of using your username as the basis for your password.


In search of an answer to this question, I decided to do some research and see if I could find out myself.
Your thinking seems to be on the right track:

60 Minutes showed Karsten Nohl, a German computer scientist, remotely
attacking U.S. Congressman Ted Lieu’s cell phone and listening to his
cell phone calls... The spying was allowed by security bugs in the
global telecommunications network known as Signaling System No. 7
(a/k/a SS7), which allows carriers to connect so they can offer
roaming and texting. According to Nohl, SS7 will be used for the next
10 to 15 years until its replacement (Diameter) is implemented, and
Diameter is also vulnerable. — Landlines still a safe way to communicate but telephone companies want to drop them

Most of what I could find does not mention anything about landlines being affected. I can only find mentions of mobile phones being affected:

Who is affected by the vulnerability? Should a hacker gain entry to the SS7 system on any number of networks, or if they are used by a law enforcement agency as part of its surveillance, anyone with a mobile phone could be vulnerable. — SS7 hack explained: what can you do about it?

Another article detailing this issue mentions that SS7 is 43 years old but focuses exclusively on mobile technology that was hardly existent then.
President Trump recently made headlines as well because of the SS7 vulnerabilities.

Trump has been asked to give up his third iPhone but wants to keep it as “unlike his other two phones, he can store his contacts in it.” And while he’s encouraged to use the White House’s secure landline for conversations, he reportedly doesn’t want the calls going through the switchboard and logged for senior aides to see. US intelligence agencies believe spies from China and Russia are eavesdropping on Trump’s calls—even those using the secure iPhones—by intercepting them as they travel through national and international cellphone networks. — China and Russia are reportedly eavesdropping on Trump's phone calls: He's been advised to use the White House's secure landline

Note the mention of secure landline. The government uses encrypted landlines that ordinary consumers do not. It's possible ordinary landlines may also be somehow vulnerable. The article does not say whether an ordinary landline would be more vulnerable. Secure landlines have been mentioned in more than one article:

Mr. Trump’s aides have repeatedly warned him that his cellphone calls are not secure, and they have told him that Russian spies are routinely eavesdropping on the calls, as well. But aides say the voluble president, who has been pressured into using his secure White House landline more often these days, has still refused to give up his iPhones. — When Trump Phones Friends, the Chinese and the Russians Listen and Learn

The government currently uses Secure Terminal Equipment for its secure landline communications. This replaced STU-III, which was used from 1987 until 2008. To be clear, this is not technology that ordinary civilians would normally be using.
I do find this all a little ironic considering that Signaling System 7 was intended to replace in-band signaling, which allowed anyone with a tone generator to reroute calls on Ma Bell's analog long distance network. SS7 is still more phreak-proof in the sense that end-customers can no longer do that.

The SS7 system CCS-7, which dates to the 1970’s, is riddled with security vulnerabilities like the absence of encryption or service message validation. For a long time, it didn’t pose any risk to subscribers or operators, as the SS7 network was a closed system available only to landline operators — Primary Security Threats for SS7 Cellular Networks

Given that mobile phones were barely in use when Signaling System 7 replaced the multi-frequency based signaling system that had been in place since the 1940s, I don't think it's exactly fair either to say that SS7 was designed with vulnerabilities, because they weren't vulnerabilities at the time we transitioned to it.
To answer the question, the security risks seem to be mostly surrounding location and access to content on the device, and since none of that applies to landlines and I found references recommending using landlines to circumvent SS7 security issues (despite the fact they rely on SS7 for long-distance as well), I can say that landlines are certainly a much more secure choice and are likely not affected by it. If anyone else finds something, though, I'd like to hear it; there's very little circulating online about how landlines are affected.
Recent update:
According to NIST, landlines may not be immune after all:

The U.S. National Institute of Standards and Technology (NIST)
announced in July 2016 that organizations should no longer send one
time passwords to mobile phones. The reasoning? This approach is
simply not secure. NIST—which both corporations and U.S. regulatory
agencies look to for cybersecurity compliance—determined that thieves
can too easily steal one time passwords sent to phones via SMS text
message. (The same applies to voice codes sent over landlines,
according to the agency.)


No, that's not exploitable.

All variables in the string you're passing to eval() are \-escaped, so they don't get expanded. This means you're always literally evaluating...

$RequestVariables = $_REQUEST;

...which is just an ordinary assignment without any possibility to inject your own code.

  What if they were not \-escaped?

In that case you're still out of luck because $_REQUEST and $_SERVER are guaranteed to be arrays, and the string representation of an array is always just Array, not displaying any contained values.


Where is the version number in an x509 version 1 certificate?

Short answer: The RFC (1422) mentioned by Wikipedia is not correct. Not only is the format mentioned in an earlier RFC (1114), but that RFC correctly references the ITU document which does have the original description: the 11/1988 version of the X.509, available here. In section 8.7(c) of that document, it is stated that "if the value of a type is its default value, it shall be absent." Therefore, a version 1 cert is the default version, and should not be included in the cert that is signed.

Longer answer, with a bit of explanation:

The newer X.509 specification (which is not in an RFC, but the ITU document is not freely available) that relates to public key certificates is most recently documented in RFC 5280. Here's a part of section 4.1, which covers the ASN.1 encoding:

Certificate  ::=  SEQUENCE  {
    tbsCertificate       TBSCertificate,
    signatureAlgorithm   AlgorithmIdentifier,
    signatureValue       BIT STRING  }

TBSCertificate  ::=  SEQUENCE  {
    version         [0]  EXPLICIT Version DEFAULT v1,
    serialNumber         CertificateSerialNumber,
    signature            AlgorithmIdentifier,
    issuer               Name,
    validity             Validity,
    subject              Name,
    subjectPublicKeyInfo SubjectPublicKeyInfo,
    issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
                         -- If present, version MUST be v2 or v3
    subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
                         -- If present, version MUST be v2 or v3
    extensions      [3]  EXPLICIT Extensions OPTIONAL
                         -- If present, version MUST be v3
    }

Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }

Two parts of this notation that refer explicitly to versioning are the version tag itself, and the issuerUniqueID, subjectUniqueID, and extensions sections. The version tag says that the default is v1, and the original spec said that defaults should be absent. When the later revisions of X.509 added versions, those new versions were no longer default, and did appear in the signed cert.

Although you can use this newer specification to generate a version 1 pubkey cert, there's really no need. You can label a new cert with the version 3 tag (using the integer 2), and just choose not to use any of the new sections.

The new spec is backwards compatible with the original. ASN.1 is used for encoding in all of these cert revisions. ASN.1 is very compact, and mostly relies on the defined format of a structure to determine what any given field means. That is, what you see with all of the "::=" syntax is a definition that you follow when parsing the blob of data you get. The first field listed in the TBSCertificate sequence is the version, which is an integer. The next field is the serialNumber, which is also an integer. If the version field is missing, which it may be if the cert is a version 1, it could be really difficult to know that the serialNumber is not the version. (It is possible--and likely, with CA certs--that the serial number is a single digit number.) The way around this--which is used in the specification shown here--is to use DER tagging. If the version tag is present, it is tagged using DER tag "[0]." The serialNumber is not tagged, so if you encounter an integer without a DER tag, you know that it is probably a version 1 cert. (It's also possible that you just have an incorrectly formatted cert--look at enough certs, and you will find all sorts of ASN.1 formatting mistakes.)

Version 1 certs don't have any of the other sections marked with DER tags, but version 3 certs (the version you will encounter most often on the internet) don't have to include any or all of those sections either. To know which, if any, of the sections are present, you look at the DER tags. Most version 3 certs will have extensions, but not issuerUniqueID or subjectUniqueID. In those certs, you will see the [0] tag for version, 1 and [2] for subject and issuer uniqueIDs, and [3] tag for extensions. Many version 3 certs you encounter don't have uniqueID sections, so the [3] tag immediately following the subjectPublicKeyInfo is the indication that the extensions are next to be parsed.

You will not encounter many version 2 certificates. Because X.509 and ASN.1 isn't confusing enough, there is an X.509 specification for "attribute" certificates--a different kind of certificate which does not contain a public key and follows a different format (with similar fields in a different order)--which are always labeled as version 2 by definition. See RFC 5755 for more information, and the format, for attribute certs.