Passing session id in query string to maintain state in third party iframe - good practice?

I am considering always passing ?PHPSESSID=x in the query string for
  each relevant url as a workaround.

This is not the best practice, but if you decide to choose this method (because it is easy), you can make something like this:

<?php

    define("COOKIE_NAME", "PHPSESSID");
    define("DOMAIN", "example.com");

    function is_valid_cookie($cookie){
        //Test if the cookie is valid and does not have any malicious chars (";", etc)

        //...
        return true;

        //...
        return false;
    }

    function is_logged_in(){
        //Test if the user is logged in

        //...
        return true;

        //...
        return false;
    }

    function sanitize_url($url){
        //Sanitize URL
        //If you have PHP >= 4.4.2 or PHP >= 5.1.2, I believe you have nothing to worry here

        //...
        return $url;
    }

    function remove_querystring_var($url, $toRemove){
        //Removes $toRemove from query string of the $url
        $parsed = array();
        parse_str(substr($url, strpos($url, '?')+1), $parsed);
        $url = substr($url, 0, strpos($url, '?'));
        unset($parsed[$toRemove]);
        if(!empty($parsed)){
            $url .= '?' . http_build_query($parsed);
        }
        return $url;
    }

    if(isset($_GET[COOKIE_NAME])){
        if(is_valid_cookie($_GET[COOKIE_NAME])){
            setcookie(COOKIE_NAME, $_GET[COOKIE_NAME], time()+24*3600, "/", ".".DOMAIN, true, true);
            header("Location: ".sanitize_url(remove_querystring_var("https://".DOMAIN.$_SERVER["REQUEST_URI"], COOKIE_NAME)));
            exit(0);
        }
        else{
            header("Location: ".sanitize_url(remove_querystring_var("https://".DOMAIN.$_SERVER["REQUEST_URI"], COOKIE_NAME)));
            exit(0);
        }
    }
    else if(!is_logged_in()){
        echo "Invalid session!";
        exit(0);
    }

    //...
    echo "Welcome!";

?>

Example:

https://mail.google.com/mail/u/0/?auth=xxxxx&anything=yyyyy

Google will use and exclude the &auth variable, but will keep the &anything, because &auth have sensitive data for Google.


How does memory-hard hashing passwords protect against brute force attacks?

Password hashing is concerned with brute-force attacks that take place offline using a dump of hashed passwords, not online against a running service. See this answer for how password hashes are usually obtained.
A running service does pay a cost when verifying passwords since it is not completely cheap. A strongly recommended step to take is to rate-limit the number of login attempts that can be performed, thus preventing the attacker from sending more than "a few" password guesses.
If there is no rate-limiting, the likely result would be the server CPU being fully consumed with password verification, slowing things down even more potentially to the point of crashing. This would be equivalent to a denial-of-service but would not result in a successful brute-force attack.
If the servers can handle it, it would still take entirely too long to brute-force due to time needed to verify each password (as well as the round-trip to the server).
Finally, there are password hashing techniques where the load is mostly on the client (eg: SCRAM), but this is more useful with heavier custom clients (eg: DB clients).


"ECC 163" is not an encryption scheme.

There are some algorithms that work with elliptic curves. One of them is Elliptic Curve Diffie-Hellman (ECDH) which is a key agreement scheme. ECDH can be used as the basis for an asymmetric encryption scheme by coupling it with a symmetric encryption algorithm: to encrypt a piece of data, you run an ECDH instance with the ECDH public key of the intended recipient, and use the resulting shared secret as key in some symmetric encryption system such as AES.

While the principle is clear enough, saying "ECC 163" is nowhere sufficient to actually specify what the dongle is doing in practice. It is more a declaration of intent than anything else.

ECDH works in some elliptic curve. While generating random elliptic curve for cryptography is doable, it is complex and expensive, so (almost) nobody does that. Instead, systems that use elliptic curve (for ECDH, ECDSA...) rely on a handful of standard curves that have been generated once and for all. NIST has defined 15 standard curves, two of which having "163" in their name: B-163 and K-163. It is conceivable that by using the terminology "ECC 163", the vendor for your dongle really means to say that his hardware supports some EC-related cryptographic algorithm using one of these two curves.

If you want to interoperate with that dongle, then you need much more detailed information about what it does. Such information is obtained through documentation from the vendor, and/or analysis and trials, a process known as "reverse engineering" (there can be legal subtleties with regards to reverse engineering, depending on context and jurisdiction, so using vendor documentation is normally preferred; also, reverse engineering can be very time consuming, and may fail, especially for a physically hardened dongle).


What are the security implications of SSH tunneling?

To be able to run SSH tunneling, you must have an account on the "edge" machine. It is difficult to permit tunneling without giving a complete shell access on that machine. That's a shell as a generic user. Theoretically, Unix-like systems enforce strict security rules with regards to local users, so that giving a shell access to a user is not a big deal. In practice, if your users are potential attackers, this increases the attack surface: you have to worry about what such attackers can do to the edge machine from a shell running on that machine, as opposed to accessing the machine "from the network".

Also, if people from the internal LAN can SSH-connect to the edge machine, they are bound to try it also from the outside (i.e. from their home machine). You may or may not wish to allow that.

The common theme here is that SSH has a kind of all-or-nothing security model: you give access, or not, but it is not easy to enforce a restricted access ("you may connect by SSH on this machine but only to do this or that task"). To make a restricted access, you must set the user shell (at the Unix level) to a specific executable which does the filtering job, such as rssh, but I do not find this to be a really robust solution.


Faking IP address without being aware of returning response

The attacker can still spoof the IP address and use bank's IP address, but the response from your website will go to the spoofed IP address (bank's IP address) and not to the attacker's actual IP address.

Usually a TCP handshake is required to initiate a TCP connection. HTTP uses TCP. The attacker will send a SYN packet with spoofed IP(bank's IP), your website will then get this packet and send a ACK to the spoofed IP(bank's IP). The machine at bank will see that it has received a ACK packet and as it didn't send any SYN packet before, so it will normally drop the packet. Due to this a TCP handshake can't complete. So, the connection between your site and the bank is not established completely.

This is why in DDOS a spoofed IP is used. Because in DDOS the attacker's motive is to bring the target machine down, so that the legitimate users are not able to get the resources from the target machine. Hence the name Denial of Service (DoS) or Distributed Denial of Service (DDoS) attack.

Spoofing an IP address: One method is that an attacker will use some packet crafting tools and create a packet that will contain a spoofed IP address. The link above shows most commonly used tools.


Can display a GIF in  tag causing Client-side DOS

Possibly, though not so dramatically. The real trick of billion laughs attacks is that they're exponential: increasing the number of layers of recursion increases the total size (for the classic example) by a factor of 10. That's much more impressive than usual expansion relationships, such as linear (doubling input doubles the size) or quadratic (doubling input quadruples the size). As far as I know, no image format - definitely not GIF - allows the recursive expansion necessary for such exponential growth.
With that said, GIF is a compressed format, and thus you can attempt decompression bombs with it. Formats that allow more dramatic compression will do better, but GIF might still do something interesting. There exist sites around the Internet, such as this one, which store decompression bombs for testing purposes. They have what they claim is a 100Kx100K GIF - which would take 10GB even at only 256 colors, if you tried to expand it to a bitmap - that is only 7MB (after removing the BZ2 compression). That's not a small image but it's not enormous; some sites will let you host bigger than that. Similarly, 10GB isn't an enormous amount of memory - many PCs and I think some phones have at least that much RAM these days - but it could certainly choke a lower-resource machine.


Is installing an old version of OpenBSD on an internet-facing server a security risk?

I have one specific package (moodle) which is not available on newer versions of aforementioned OS (last version of moodle was available on OpenBSD 5.3) which is more than 4 years old.

In my opinion you ask the wrong question. The problem is less the old version of OpenBSD but more the old version of Moodle you want to run on this OpenBSD version. Although you don't specify details my guess is that you want to use this package (or here) which contains Moodle 1.9.16 on PHP 5.4 - both being very old.

OpenBSD releases are supported essentially for one year. Running a version of OpenBSD which is more than 3 years out of support can maybe done  if you really know what you are doing to keep the attack surface minimal enough - for example by only having SSH access with only key based authentication and if you have no untrusted users on your system.

But, running a large web application like Moodle definitely does not count as minimal attack surface. Web applications are usually complex and often have security vulnerabilities, sometimes even critical ones which allow remote code execution. And such vulnerabilities also exist with older versions of Moodle as a simple search shows. And while sometimes critical fixes get backported to older versions you can see from the commit history that the last change on this package was done 2012-01-21. I guess that this non-maintenance of the package was also the reason that it got removed from ports on 2013-09-20.

In other words: Running an old version of a large and complex application like Moodle with known critical security vulnerabilities is a very bad idea. And the security of OpenBSD will not help to protect you much in this case. It will not help much if you use a current version and it will help even less if use use an old and unmaintained version of OpenBSD.


android automatically accepts self signed certs on wifi

While it is frustrating, keep in mind that ultimately a user is being asked to make a security decision. When most users are prompted in Windows, iOS and macOS, they're usually blindly accepting the certificate. Even if the user were to examine the certificate, there is nothing to compare against (unless IT has explicitly told all users what to look for).

If security is top of mind, tunneled EAP methods with password exchange should not be used. In environments where some devices are unmanaged, EAP-TLS is the only safe bet.

Note that Android 7.1 and higher has greatly improved EAP server certificate validation.


Is this codes usage of document.location.toString() a DOM based XSS vulnerability?

This code snippet is vulnerable to XSS in jQuery prior to 1.9 (and in conjunction with the jQuery Migrate plugin). Even now, it remains at least a bad practice.

The string argument to $() (shortcut for jQuery()) can be parsed either as a CSS selector or HTML code. Parsing the string as HTML implies an XSS vulnerability, just as document.write() would. On the other hand, injecting into a CSS selector is not directly exploitable in current browsers.

The changelog for v1.9 explains how they changed the parsing behavior:

  Prior to 1.9, a string would be considered to be an HTML string if it
  had HTML tags anywhere within the string. This has the potential to
  cause inadvertent execution of code and reject valid selector strings.
  As of 1.9, a string is only considered to be HTML if it starts with a
  less-than ("<") character. The Migrate plugin can be used to restore
  the pre-1.9 behavior.

Since the string from your snippet ('.nav-tabs a[href="#' + <payload> + '"]') does not start with a <, you will not be able to inject your own code, when the page is running a current version of jQuery.

However, you should still sanitize the output. Sometimes, different modules (e.g. Wordpress plugins) come with their own jQuery library that might inadvertently override the newer version and reintroduce the legacy behavior. A simple fix would be to reject the string if location.hash is not alphanumeric or not contained in a list of predefined links.


What's the difference between privacy and anonymity?

Say you use a proxy to visit a site.

Privacy: security of content

With the proxy, you will be anonymous to the site you're visiting.
That is, it will look like the proxy is requesting the page, not you.
The site will still know your content, just not who it's delivered to.

Anonimity: security of identity

Assume you use HTTPS and the proxy or ISP is not maliciously stripping encryption.
Then the content of you connection will be private. But the proxy or ISP knows your IP address and that of the site you're visiting.
To the proxy or ISP, your connection is private but not anonymous.

For TOR and VPN, the ISP can still match the time and size of packets to make good guesses about the site you're visiting.

So about the technologies you mention;

Proxy:

private to proxy  (if trusted and site uses HTTPS)
website cant see you (if not sending identifiable info)
ISP monitors you

VPN:

same as proxy but more private (HTTPS built in)
website cant see you (if not sending identifiable info)
ISP cant see your browsing/data (just knows that you use VPN)

Tor:

same as VPN, semi-anonymous to everyone except the entry node.
private to everyone except you and the site
assuming your PC is not leaking info (it probably is)
ISP cant see your browsing/data (just knows that you use TOR)


How does dnsleaktest.com find my DNS provider

From the source of https://www.dnsleaktest.com/:

That site generates a random host name and arranges for your browser to request content from that host name. Since the host name has never been served to anyone else before, your browser's request to resolve it is sure to make its way to the primary server for the dnsleaktest.com domain. Since they run their own DNS, whoever they receive the DNS requests from is your DNS provider.

Whether forcing your DNS traffic to go through a tunnel instead of via your ISP depends on who you want privacy from. If you don't want the sites you visit to know where you're from, it's a mild leak: most sites don't bother to track where your DNS requests come from, and anyway they'd have a hard time figuring out which ones are yours, and your requests are likely to be served by some cache anyway. However any site could use the same trick as dnsleaktest if they cared. If you're using a tunnel because you don't want your ISP to know which sites you're visiting, making sure that no DNS request ever reaches your ISP is crucial.


Exploitation of Reflected XSS on Android App

A lot of the comments above are irrelevant. None of that stuff really matters. In the app, did the developer create a feature where external links are automatically redirected to the app? If not, the threat is very low.

Somebody would have to decompile the app and add that feature in and redistribute it order to successfully exploit that vulnerability. I would fix it regardless but the threat is low.

Stored XSS would be a different story.


When you sign code, it means that you vouch for that code. When people decide to trust your signature, it means that they trust you to only sign code after you verified that it is trustworthy.

When you abuse that trust and someone finds malware with your signature on it, you can expect them to never trust your signature again. When your certificate has a special trust status by any operating systems or distribution platforms, you can expect that this trust will likely be revoked if it comes to the attention of the maintainers that you signed malware with it.

So if you decide to sign 3rd party device drivers, you should only do so when you feel you can wholeheartedly take responsibility for whatever that driver does. If you can not do that with a clear conscience, it's better to leave it unsigned and let the user decide if they trust it. Or better, find a more trustworthy alternative.


Using Apple NSKeyedArchiver class without encryption to save score data locally

Any NSKeyedArchiver object can be unarchived by anyone if it is not encrypted, since it does not encrypt anything by itself. All NSKeyedArchiver does is, from the Documentation:

  NSKeyedArchiver, a concrete subclass of NSCoder, provides a way to encode objects (and scalar values) into an architecture-independent format that can be stored in a file. When you archive a set of objects, the class information and instance variables for each object are written to the archive. NSKeyedArchiver’s companion class, NSKeyedUnarchiver, decodes the data in an archive and creates a set of objects equivalent to the original set.

So, in other words, it creates a structure where each object's content is stored with an identification of its original Class, so the original object can be decoded later. Think of it as a kind of binary XML.

What I recommend you to do is take the NSData created by [NSKeyedArchiver archivedDataWithRootObject:(id)rootObject] and encrypt it using any method you prefer. If data is really secret I recommend using AES256 or Blowfish. When you need to use it, decrypt the data first and then put it in [NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)data].


How does the EAP-TLS handshake work, exactly?

In EAP-TLS, the peer (supplicant) and the authenticator do a TLS handshake. In practice, the authenticator usually relays the EAP mesages to an authentication (RADIUS) server which means that the TLS handshake is actually done between the supplicant and the authorization server.
[ TLS   ]<--------------------->[ TLS    ]
[ EAP   ]<--------------------->[ EAP    ]
[ EAPOL ]<->[ EAPOL | RADIUS]<->[ RADIUS ]
[ Wifi  ]<->[ Wifi  | ...   ]<->[  ...   ]
Supplicant    Authenticator      Authentication Server
(Wifi Client)  (Wifi AP)          (RADIUS server)

The TLS communication between the supplicant and the authorization server works as expected but usually mutual authentication is used:

server sends its certificate chain
client validate certificate chain against server name
client sends its certificate chain
server validate certificate chain
further crypto magic happens

Once the TLS handhsake is finished, the TLS session is not used anymore: it is not used to transport encrypted data.
If the handshake succeeds, the RADIUS server send a "RADIUS Access-Accept/EAP-Message/EAP-Success" message to the authenticator.
At the end of the TLS handshake, both the supplicant and the authentication server derive a "TLS master secret". This TLS master secret is used to derive a Master Session Key (MSK), see RFC5216:

In EAP-TLS, the MSK, EMSK, and Initialization Vector (IV) are derived
from the TLS master secret via a one-way function.

This MSK is sent by the authentication server to the authenticator as part of the "RADIUS Access-Accept/EAP-Message/EAP-Success" RADIUS message. As far as I know (?), the MSK is in practice sent using the following RADIUS Attributes, RFC2548:

MS-MPPE-Send-Key
MS-MPPE-Recv-Key

See the StrongSwan wiki on this topic:

For EAP methods providing an MSK, the RADIUS server must include the key within the MPPE-Send/Receive Keys [...]

See this Security StackExchange answer on this topic.
See RFC5216:
Enc-RECV-Key = MSK(0,31) = Peer to Authenticator Encryption Key
               (MS-MPPE-Recv-Key in [RFC2548]).  Also known as the
               PMK in [IEEE-802.11].
Enc-SEND-Key = MSK(32,63) = Authenticator to Peer Encryption Key
               (MS-MPPE-Send-Key in [RFC2548])

Once the authenticator has the MSK, both supplicant and authenticator can use the MSK has a PSK to secure the communication. In practice, the Wifi Pairwwise Master Key (MPK) is derived from the EAP MSK.


How to use Windows User Certificate (S/MIME) to sign data

You may look at this question

In C# you will need to use the Windows Store:

using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);

            foreach (var cert in store.Certificates)
            {
                string desc = cert.GetNameInfo(X509NameType.SimpleName, true);
                if (desc.Contains("WISeKey"))
                {
                    RSA pk = cert.GetRSAPrivateKey();
                    byte[] buffer = Encoding.Default.GetBytes("Hello World ... !");
                    byte[] signature = pk.SignData(buffer, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                    System.Console.WriteLine(BitConverter.ToString(signature));

                    break;
                }
            }
            Console.ReadLine();
        }
    }
}


Is SSH secure against MiTM if server fingerprint is not checked, public key authentication is used and confidentiality is not needed for that service?

In short:  it is not a design flaw. You've just had a misunderstanding of the design.

  The authentication protocol is that the client signs the challenge provided by the server, the server verifies it and then allows access.

The client does not sign a challenge provided by the server. Instead the client signs a structure defined in RFC 4252 section 7 which includes as a major component the session identifier.  This session identifier itself is a result of the key exchange as described in RFC 4253 section 7.2.

  ... a malicious server can impersonate a user to a legitimate server by doing MiTM and proxying user's responses to the original server.

Since the MITM does not have access to the clients private key it cannot create a new signature with this key. Thus it needs to find a way to make the server accept the original signature by the client. And since the signature depends on the session identifier the MITM would need to establish a SSH connection between client and MITM and another  between MITM and server which both have the same session identifier.

But in the Diffie Hellman key exchange the result of the key exchange depends both on client data unknown to the server and server data unknown to the client.  Since the MITM has only control over one side of each connection it cannot control the result of the key exchange and thus cannot control the session identifier.

Therefore the attack you describe will not work. The MITM cannot simply impersonate the client as long as the server properly authenticates the client. Either the authentication will fail because the signature is broken (does not match the session identifier) or it will fail because the public key is not the one expected by the server (in case MITM made up its own client key).


Does it Matter That Universal Windows Platform (UWP) is Open to Phishing Attacks?

Speaking of new-found powers. :)

It is now clear to me from the (great!) feedback here that I could have expressed this in a more fact-oriented manner, and that this issue does not seem to be as big of a deal as I am thinking it is.  I tried to keep it as objective as possible, but in dealing with an issue that is over three-years-old, I probably let it get to me more than I should have (see: not handled new-found powers appropriately!).

I realize this site isn't meant to be a sounding board, but it took getting this question out to see it for what it was.  I appreciate your patience as I learn here.

I have taken the MSFT CSG's advice from the referring thread and have started a UserVoice vote around this item.  If you like, you may view and vote for this item here:

Consider Displaying URL/Location/Context to User in UWP Application During Authentication

I am almost tempted to delete this question, but I will let it stand as a reminding lesson in my quest to be a good citizen both here and in general within the broader community.  Thanks again to all involved!


Why do I need to install the startcom intermediate certificate?

Short version:

Firefox is using its own CA database which includes the necessary Startcom intermediate certificate; OpenSSL uses /etc/ssl instead which does not have that intermediate certificate.  But you should fix this at the server side, not the client side.

Long version:

SSL certificate validation requires each certificate in the chain be validated.  The chain starts at the root, ends at the node certificate, and may include zero or more intermediate certificates.

The client software must have a list of trusted roots.  A root is signed by itself, and is trusted by virtue of the software vendor including that certificate in its trusted roots store.  In the case of Firefox, that's (I believe) cert8.db.  In the case of OpenSSL, it uses the /etc/ssl hierarchy.

The client software may include intermediate certs in its store, as well.  However, it's not required to.  It appears that Firefox has done so for Startcom, but that Ubuntu's /etc/ssl configuration tree does not.

For this reason, it is best practices for servers using node certificates signed with an intermediate cert to include all intermediate certs when sending their certificate to any client that connects.

To directly answer your question, putting the intermediate into /etc/ssl will fix the problem - for you.  Not for anyone else browsing your site.  In order to properly fix it, you should add the intermediate certificate to the chain that the server hands out.  For example, with Apache, see the SSLCertificateChainFile directive - DigiCert has a good walkthrough, and StartCom also has instructions.

@DanFromGermany asks, in the comments, if I can give a reference for:

  best practices for servers using node certificates signed with an
  intermediate cert to include all intermediate certs

In fact, to call that "best practices" is not strictly true - it's a requirement.  According to RFC 5246 (TLS 1.2):

  [The certificate_list] is a sequence (chain) of certificates.  The
  sender's certificate MUST come first in the list.  Each following
  certificate MUST directly certify the one preceding it.  Because
  certificate validation requires that root keys be distributed
  independently, the self-signed certificate that specifies the root
  certificate authority MAY be omitted from the chain, under the
  assumption that the remote end must already possess it in order to
  validate it in any case.

By inference - each certificate in the chain must directly certify the one preceding it, and only the root certificate authority is optional ("MAY be omitted"), then all intermediate certs are required.

So it's not strictly true to say that including all intermediates is best practices - it would be fairer to say that not including all intermediates is worst practices, but happens, because people are lazy, and because it works out enough of the time.


The supported hashes can be obtained by running the command with the --version flag.

From the GnuPG setpref documentation (bold emphasis mine):

setpref string

    Set the list of user ID preferences to string for all (or just the
    selected) user IDs. Calling setpref with no arguments sets the preference
    list to the default (either built-in or set via --default-preference-
    list), and calling setpref with "none" as the argument sets an empty
    preference list. Use gpg --version to get a list of available algorithms.


How do 2FA (and other account verification) systems identify true mobile numbers vs VoIP numbers?

In a manner similar to how some online services detect VPNs based on known VPN IP address databases, VoIP numbers come in batches that have known prefixes within each area code. Certain providers choose not to allow VoIP numbers for verification because they can be obtained and accessed from anywhere in the world, and are harder to tie to real people, locations or accounts, and are easier to change or dispose of. Some service providers also do not want to be liable for fraud committed by intercepting SMS messages while they are in the IP domain. Intercepting a text message on a cellular network is much more difficult than on a hijacked VoIP account. An attacker does not have to physically obtain the device (like stealing a mobile phone) on a VoIP account, just obtain login credentials.


Chrome requires SAN names in Certificate. When will other browsers (IE) follow?

IE probably never
IE is a dead product, it'll probably stay doing what it's currently doing unless there's some major security issue forcing Microsoft to issue a special security update to disable CN validation.
Firefox already there
Firefox already no longer recognize CN for new certificates signed by public PKIs, (deadline was anything issued on/after 2016-08-23) but still allow fallback to CN for non-built in CAs. Since Firefox is an open source product, for items like these, removing CN support likely will require a volunteer that actually goes forward to provide a patch to implement the removal, and such patch likely will only get merged if retaining any CN support is preventing some other major improvements to Firefox or the web/PKI infrastructure as a whole. There's really no big hurry for this removal, as keeping it around doesn't seem to prevent anyone from doing what they need to do at the moment, and the current solution of differentiating built in and imported certificate seems to satisfy Firefox's users for the moment.
Edge/Safari: unknown
Edge and Safari are a Microsoft's and Apple's products, keeping or removing support likely will depend in their respective commercial influences.
Further reading/tracking: ChromeStatus
So far, according to ChromeStatus: Support for commonName matching in Certificates, there doesn't seem to be any public communication from Microsoft and Apple for this topic.


About SSD secure disposal for conforming to iso27001

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

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

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


inetsim installation perlipq/libipq error

Kali Linux has inbuilt inetsim you can try that..!
or else check it out https://techanarchy.net/2013/08/installing-and-configuring-inetsim/ it has step by step process


What is the impact of controling the content of a webview in Android?

it depends on who the attacker & who the victim is in the whole equation. If we're talking about the attacker being an external party, who can potentially get some javascript executed in a vulnerable page inside the webview, then yes, to some extent your assumption is right. Without javascript interface enabled, there is not much that the attacker would be able to do to abuse the underlying app (the victim in this case).

However, if it's the other way round, where the victim is the page getting loaded inside the webview of the app (attacker controlled / malicious), then there's a lot that can be done to harm the victim, of course depending on how sensitive the victim page is.

I recently wrote a blogpost explaining this exact exploit scenario in (too much) details. You may want to check it out.


I was thinking to check the user in the database on each request so I
  can invalidate the account instantly. Are there any problems with this
  flow?

I don't see anything glaringly wrong, but....

There are some downsides. Doing this, requires that every user-interaction lookup your database table. For a small-ish application with not many users, this shouldn't prove a problem. If you've got thousands of users, with thousands of interactions per hour, that's millions of user lookups. Can you database handle this?

The alternative, would be to do this check only when the token is refreshed instead -- that way, you look up the database only once per refresh interval (let's say 15 minutes). Then 1,000 concurrent users will only result in a maximum of 4,000 lookups of the user table per hour (something any db can handle). This also means that only one service in your app (the refresh end point) needs access to the user table, which gives you better control and granularity for protecting your sensitive user data.

Of course, this means that if you need to disable a user, the worst-case scenario you can do this in is 15 minutes. For some applications that might not be acceptable -- so falling back to your check per request might prove a better solution if indeed this is a requirement.

In short, I don't think there's anything wrong with this approach, but I wouldn't recommend it. Do the user check on refresh instead of every request, tokens were built so that every end-point/micro-service could authenticate the user token without having to go back to a singular database table or end-point.


How are VLANS logically separating a switch?

Some attacks are prevented by VLANs regardless of what the router allows.  Arp poisoning, for example, or broadcast-based attacks like DHCP hijacking.  Two hosts segregated by a VLAN cannot attack each other in those manners.
However, for security the presumption is that the router will not allow everything, but will apply some access controls or NAT hiding between the two VLANs.  In that event the router should be able to provide all the security that it could between two physical VLANs.


One-Way Command Verification Using 2 Private Keys

If I may rephrase your idea

The sender would:

Create a message
Create a payload that includes the message, plus a digital signature created by encrypting the message (or a hash of the message, if it is large) with the sender's private key.
Include the payload plus the sender's public key in an envelope
Encrypt the envelope with the receiver's public key

To read the message, the receiver must:

Decrypt the envelope using the receivers private key
Decrypt the digital signature using the provided public key
Confirm the message (or its hash) and the signature match

The idea being that you get both privacy (because the sender encrypted the message with the receiver's public key) and integrity (because the sender signed the message with a signature that can only be created using the sender's private key).

I am thinking this would mostly work, with one small problem.  Your system lacks any notion of trust. How does the receiver know the public key belongs to the sender? A malicious actor could create a totally different message with a different asymmetric key, right? If you don't know where the message is coming from, all notions of privacy or integrity are completely moot.

Normally, the way you verify a public key belongs to an entity is to leverage the PKI and check the chain of authority. This requires the CA and everything that comes with it.

A different way to deal with this (if you don't want to deal with PKI) is with shared secrets.  You would generate a secret key and provide it to the receiver out of band (e.g. mail them a USB drive). That way you don't have to play all these games, you just straight out encrypt the thing, and assume nobody else can decrypt it.  That sort of approach is very common.


How to avoid writing .pem while signing a csr?

Sorry, per the sourcecode you can't prevent the writing of $outdir/$serial.pem and still get your (desired) -out. You could put $outdir someplace like /tmp that gets discarded frequently; or on an OS that allows you to add new filesystem types (Linux at least) you could create a filesystem type that implements a directory such that anything created in it is discarded -- but that seems a lot of work to avoid creating a few files that don't hurt anything.


Recent hack appends to all javascript files

There is a canonical question entitled "How do I deal with a compromised server?". Since you are on a shared host, there are some limitations to what you can do. I still strongly recommend you to read the full accepted answer.

Below I will discuss how this applies to your situation (i.e. on a shared hosting). Quotes are from the mentioned answer.

1. Take your site down.

  Whatever other problems you have, leaving the system connected to the web will only allow the attack to continue.

You can not know for sure that you have removed all infections. At this very moment you might unkowingly be spreading malware to your users!

2. Damage control.

  Change all your passwords for all accounts on all computers that are on the same network as the compromised systems.

  Check your other systems. Pay special attention to other Internet facing services, and to those that hold financial or other commercially sensitive data.

  If the system holds anyone's personal data, immediately inform the person responsible for data protection (if that's not you) and URGE a full disclosure.

3. Try to figure out what happend.

If you just put your site back up as it were, the same thing will just happend again. You need to try to understand what went wrong.

With shared hosting this can be hard, since it is possible that the hackers used an exploit in the server software itself or in some other persons account. You will need to contact your hosting provider and get them to help you with this. It can not be taken for granted that they will cooperate. If they do not, I recommend you to read your contract and possibly contact a lawyer to find out what rights you have.

However, you can examine some things on your own - namely your own site. Go through all the software you run (WordPress, Magento etc). Are you running the latest versions? Are you running any plugins? Are there any known security holes in the versions or plugins you are running? Especially WordPress plugins are frequent offenders when it comes to security.

There is some limited forensics you can do on your own. If you have backups, compare them to see what files have been changed at what time. The injected JavaScript you discovered might not be the only thing the attackers changed. There might have been multiple changes at multiple times (possibly by multiple attackers), so you can not know for sure that the date when the JavaScript files were changed was the date of the initial breach.

Especially if you run a lot of your own code, you might want to do a more detailed pentest to find any vulnerabilities.

4. Consider new hosting.

Especially if the breach was "their fault" or they did not help you to determine the cause of the breach, it might be time to move to new hosting. As others have mentioned, a VPS is more secure but can also require more effort on your part to run.

5. Get your site back up again.

Restore static files from a backup before the breach. Reinstall all software, and only use the latest versions. So dont just copy paste the files from your old vulnerable WordPress installation back up to the server from a backup.

And obviously, fix any problems discovered during step #3.


Is email encryption, as claimed by ProtonMail, possible?

Strictly speaking it is not possible, for the following reason: if the Web service encrypts the message, then the Web service gets to see the unencrypted message at some point (note: I write service, not server). At best, the service may be honest and do its best not to have a look at the messages at they flow.

Now let's see the claims of that "ProtonMail" service:

Swiss Based. Well, I see no reason to find this implausible. Switzerland is a real country and there are people who live there. However, they suggest that by being a "Swiss service", the data immediately come under the cover of Swiss law, which is a rather bold statement. Electrons don't have a nationality, and, contrary to a piece of paper, an electronic message does not have a well defined geographic position at all times.
Zero Access to User Data. That one is not completely true. When you write your message, you do it in their Web site. Even if all encryption technically occurs in your browser, that would still be done using the Javascript code that they send to you every time you connect to their service. If they want to read your messages without you noticing it, they can.
End-to-End Encryption. This is possible, if encryption is Javascript-based on the sender's browser, and decryption is again Javascript-based on the recipient's browser. Taking into account the pitfalls of doing crypto in Javascript.
Anonymous. I don't believe that one, at least not in the long term. They claim not to log anything; however, experience of past anonymous remailers shows that the logs are the only thing that stands between the remailer operators and jail, in some extreme cases (e.g. if the service is used to coordinate some terrorist actions). Almost invariably, the claim of not logging turns out to be fake after a while. On a similar note, even if the site operators are idealist enough not to log anything, eavesdropping on the network provider side is enough to get a lot of metadata and, e.g., work out who talks to who. This is called traffic analysis. It works well and no Web service can protect against that (only network-wide systems like Tor stand a theoretical chance to defeat traffic analysis).
Securely communicate with other email providers. That one makes me cringe a bit. They mean that when the recipient is not a ProtonMail registered user, they send a normal email with an embedded link to their site, so that the user may download the encrypted email and the piece of Javascript that decrypts it. As they say it, this requires that you previously shared a password with the recipient by some unspecified mean. The bad part here is that it trains people to click on links received by email, and then enter their passwords on the resulting Web page.
Self Destructing Messages. This one works just as well as, or as bad as, copy protections on movies. The raw fact is that if the recipient could read the message at some point, then he can get a copy indefinitely (if only by taking a photo of the screen with his smartphone). The "self destruction" is more a declaration of intent (pleeease don't save this email) than a security measure that can be really enforced. (However, automatic destruction of messages after a time will sure help the ProtonMail administrators, since they store the encrypted emails on their systems and don't want to do that indefinitely, because disk space, though cheap, is not free.)
Open Source Cryptography. That one is believable, and good news. At least they don't reinvent their crypto, but use time-honoured standards (in this case, OpenPGP). (I don't recognize any name in their list of security experts, but I don't know everybody. Effort at transparency is good.)
Hardware Level Security. They don't mean a HSM; they mean that they lock the doors of their server rooms, and use disk encryption. That last bit is weird: weren't the emails supposed to be already encrypted ? What private data remains, that they feel that it should be encrypted again ? This looks like security theatre to me.
SSL Secured Connections. This is very plausible, and very much needed in order to avoid third-parties tampering with their Javascript. Not using SSL would be a killing flaw in their system. Unfortunately, they spoil the effect by adding: "To allow extremely security conscious users to further verify that they are in fact connecting to our server, we will also release the SHA3 hash for our SSL public key". Publishing the hash of your public key makes sense only if people can obtain the hash in an untamperable way; if that hash is simply pushed on your own SSL Web site then you are running in circles. Invoking the magic of "SHA3" reveals the extent of the seriousness of that claim: this really is just some more security theatre (not the least since SHA-3 does not exist yet: right now, FIPS 202 is still a draft). (In fact they published the SHA-1 hash, not SHA-3.)
Easy to Use. For that one, you will have to judge for yourself. "Ease of use" depends on who uses it.

Summary: ProtonMail appears to be roughly the equivalent of using PGP, except that it is Web based, thus centralized. It brings back a lot of issues that PGP was supposed to solve, namely that there is a central server that gets to see who talks to who, and that serves the actual code repeatedly. That central server is thus a juicy target for whoever is intent on spying on people. The decentralized nature of PGP is its biggest asset against attackers; by making it Web-based, they increase the ease of use but abandon that decentralization.

While ProtonMail is certainly better than plain, unencrypted email, it would be wrong to believe it to be the ultimate answer to email security. At least, they made some efforts:

They use existing standards.
They have an explicit threat model. Even if it is not very detailed, at least they know the expression "threat model", which puts them in the top 5% of vendors of security systems.
They try to be transparent.

On a less bright note, I did not see anything related to opensourceness. That is, they say that they use "open source libraries" for cryptography, but they don't actually say which libraries these are; and they don't show their own source code, either. Users are back to having a look at the Javascript code and do their own reverse-engineering, and that does not look very opensource to me.

They also don't actually given any details on their protocol. Since they don't know (or so they say) the "mailbox password" of the recipient, then this begs the question of how they can push an email into that mailbox. We can infer that the mailbox includes a public/private key pair, and the mailbox password is really used to encrypt the private key, not the mailbox itself; this is what would make sense with the information they give (in particular reliance on OpenPGP). But it would be better if they said it. If the protocol is fine then it should be published; there is no reason not to do so. No source and no protocol are very bad points and they really should fix that.

Summary of the summary: ProtonMail's security can be summed up as: their system is secure because they say that they are good guys, honest and all, and they claim to be competent. So that's all fine, eh ?


Domain redirecting to my site without permission

Contact the registrar that the domain is registered with.

You can use any WHOIS search engine to gain the abuse contact details for the registrar, as well as (providing that they haven't made the WHOIS data private) the owner's contact details. I often use the who.is search for WHOIS information (I find that there are a few 'WHOIS search' providers out there who are actually registrars).

The section you'll be interested in is this:

Domain Name: EXAMPLE.COM
Registry Domain ID: 000000_DOMAIN_COM-VRSN
Registrar WHOIS Server: whois.register.it
Registrar URL: http://we.register.it
Updated Date: 2015-08-20T00:00:00Z
Creation Date: 2015-05-20T00:00:00Z
Registrar Registration Expiration Date: 2016-05-20T00:00:00Z
Registrar: REGISTER.IT S.P.A.
Registrar IANA ID: 168
Registrar Abuse Contact Email: abuse[at]register.it
Registrar Abuse Contact Phone: +39.0353230310

Obviously the registrar's information will vary from domain to domain, but you'll still be wanting to know this info:

Registrar Registration Expiration Date - If the domain is expiring inside a month, I personally wouldn't bother reporting it unless you feel it is doing you serious harm or that the domain's expiration date is extended (the owner will probably get notifications that it's expiring a couple of weeks prior)
Registrar Abuse Contact Email/Phone- Here's where to contact to have the domain investigated for abuse (this includes purporting to be another website, which is the case here). If successful, the domain will be suspended.

You will also be interested in the Registry Tech ID: section of the WHOIS record, which lists additional details for the registrar. Depending on whether the registrar is a reseller, this information could be different to the information mentioned above.

If you still can't get hold of the registrar, contact ICANN directly (if it's a domain regulated by them), or the appropriate regulator for the TLD or SLD of the offending website. If the registrar won't do anything about it/can't contact they the regulator will.


Potential risks of publicly uploading a Wireshark trace with TLS-related information?

If the wireshark trace was made from the perspective of a passive eavesdropper, then there is nothing in the trace that could be used to tamper with future SSL/TLS connections.

Keep in mind that there are many entities that are in a position to make the same trace that you made, including wireless hotspot operators, ISPs, backbone carriers, data centers, etc.  If it were possible to tamper with future SSL/TLS connections using the trace that you made, then any of these entities could do the same thing.  SSL/TLS was designed specifically to be resistant to this type of tampering.

Even if you run the trace at the client, and log session information to the SSLKEYLOGFILE, the information in this file will not be useful for tampering with future SSL/TLS connections, as this file contains only ephemeral keys and session keys used only for the session when the trace was made.


From a local file inclusion to a shell when file is downloaded?

LFI, will not get you a shell by itself. You need to download config files and the web application's sources, these can point you to either passwords you can use in the web app, ssh, database or help you find an exploit on a stored web app. (whiteboxing is easier)


I would advise against implementing this yourself. If you disagree, have a look at the current existing AES implementations; many libraries are available and it's likely that these will suit your needs.

Have a look at Turning a cipher into a hashing function and Description of the AES cipher on Wikipedia if you're interested how the algorithm works.


Nobody uses RSA to directly encrypt data transmitted over http (web) or SMTP (email). 2048 bit RSA would only allow you to encrypt 245 bytes at a time, and each such operation is expensive.

Protocols get one of the parties or both parties together to generate a new random number that is long enough to be unguessable and unique. 128 bits are enough, though TLS uses more. Then they use this number as a symmetric encryption key (technically, seed for KDF), which allows them to quickly encrypt a lot of data.

If the CSPRNG is backdoor-ed, adversary can predict the shared secret key. If the shared key is not secret, you completely break the security.

If one of the parties generated the shared secret key, they must transmit it to the other party, in a way that is immune to eavesdropping. A simple way is to encrypt the shared secret key using the recipient's public key. PGP does this, and older SSL/TLS did this.

A problem with transmitting the shared random secret key encrypted with the recipient's public key is that if you get your hands on the recipient's private key, maybe years later when they no longer use this keypair, you can decrypt previously recorded ciphertexts. So a junked hard drive with the private key for a long ago expired TLS server certificate would allow e.g. the NSA to decrypt years of old traffic.

Newer protocols demand use of better scheme: Diffie Hellman to establish an anonymous shared secret, and digital signatures to prove other party is who they say they are.

In modern protocols, RSA is only used for signing and verifying signatures.

Note: You may have read an explanation of RSA signatures as a kind of encryption. It is a very bad explanation, don't use it.

Note that textbook RSA is insecure and must not be used. You must use secure padding schemes for RSA encryption and for RSA signatures. The padding schemes for the two use cases have different goals and are different. Mixing them up is insecure.

Note that old TLS used pkcs#1v1.5, it's now considered insecure, use RSASSA-PSS instead.

As you've noticed implementing RSA securely is difficult, modern recommendation is to use better cryptographic primitives, like those in libsodium (or better yet, libsodium itself).


What kind of attack is a request like this?

This could be an initial control test for blind AW injection.

Typically those start with a true/false test.

So perhaps they are testing 1>1, which is always false.

Then they will also test 1=1, which is always true.

And look for a difference in the response

https://en.m.wikipedia.org/wiki/SQL_injection#Blind_SQL_injection


If a USB stick/device is inserted into a PC running Windows,
currently in "lock screen" mode (that is, somebody has pressed
WinKey + L), it will auto-mount it behind the scenes?

Yes it does! I had originally said "No" but it dawned on me that I had not actually verified that so I tested it this morning. It turns out that it does indeed mount even though the screen is locked. I also tried it on a screen locked Linux machine and found that the physical device can be accessed but the partition is not actually mounted.

This is how I tested:

I took an absolutely clean (verified via Linux) thumb drive formatted in Fat32 and plugged it into a screen locked Windows 10 machine and waited several seconds before unplugging it. Then I examined the thumb drive on my Linux machine.

Windows (and Macs) default write hidden identifiers to thumb drives when plugged in if they don't already have one. Sure enough, the previously clean thumb drive now had the hidden Windows identifiers on it. This showed that Windows not only mounted it but performed both a read and write to the thumb drive.

If a USB stick/device is inserted into a PC running Windows,
currently NOT in "lock screen" mode, it will auto-mount it by
default?

Yes! It will also enable USB devices that are not block storage devices.

In both cases above, will it ever run any kind of executable found
on it by default? (Like which I believe used to be the case for
setup.exe on CD-ROMs back in the day.)

No, under normal configuration now days it will not auto run a file from a block storage device or a USB connected CD. However Human Interface Devices (HID) such as a keyboard are enabled.

Previous versions of Windows did auto run files from CD's but never thumb drives, however manufacturers produced U3 thumb drives that were actually two devices in one, mass storage and a faux CD device that would auto-run files, so it looked like the thumb drive was auto running.

There are USB devices that look like thumb drives but are not. The classic example is a Rubber Ducky. It looks like a thumb drive but is actually a pre-programmed keyboard that can auto type any command that you could from a keyboard, and it auto runs upon being plugged in. There are similar devices, such as a Bash Bunny, that can act as multiple devices at once, becoming both a mass storage thumb drive and a programmed keyboard, allowing it to store the results of the commands issued as a keyboard.

All of the similar devices I'm familiar with are designed to function under USB-2, which does not support DMA bus mastering. Firewire supported bus mastering which made it possible for a master device to directly access computer memory on some machines that failed to securely initialize their their DMA control maps. USB-3 supports DMA, but I have no idea if something similar to Firewire is possible.


If I understand this correctly, normally, the Bamboo server is the one sending code and instructions to the EC2 instances.

This means that assuming that there is no remote code exploits in Bamboo that allows the EC2 to command the Bamboo server, then these are the possible things that the attacker can do:

Steal source code
Return fake test results, corrupting your results
If you used passing tests on CI to trigger continuous deployment, then it can trigger deployment
If your CI builds a package or image as a build artefact, which can later be deployed to production, then the compromised EC2 can inject malicious code into the build.

The SSL tunnel is the least of your worry; all it does is provide a secure tunnel between your Bamboo server and EC2.


Is there a online filter to check email attachments?

Virus Total and malwr and both good sites to submit suspicious files. Virus total will tell you if the file is flagged by any antivirus. Malwr will give you more detailed analysis (this may/may not be of interest to you).

Note that you're submitting files to an online community, so don't submit anything that is potentially proprietary/secret.


Why one time passwords using nested hash chain are not used?

The method you describe is indeed a classic algorithm for one-time passwords, but it has some drawbacks:

It is good only for N passwords, where N must be chosen at initialization time.
The client must invoke the hash function R times, where R is the number of remaining passwords in the chain, i.e. initially R = N. This limits the size of N, otherwise the cost becomes unbearable for the client system.
The server must retain some state, which is either the last successful password, or a counter. The counter has the problem that the cost on the server becomes proportional to the number of used password: if the user has used 1000 passwords, then the server must invoke the hash function 1000 times to validate the next password. On the other hand, saving the last password works only if the last password is the complete hash output, not a derived subset -- which makes for very bulky one-time passwords, hard to type (think 20+ random characters...).

For one-time passwords, common practice is to use HOTP, which uses a counter on both sides (client and server) and a single HMAC invocation. It also relies on the underlying hash function being secure, but it does so in a much easier to use way, avoiding the problems described above.

Summary: the method you describe is not used because much better methods are known -- not that they are more secure, but they induce much lower overhead on the client, the server and the human user.


Here is what finally used as a bash file.

#/bin/bash
chown -R root:root /var/www/html
cd /var/www/html
PLACES='
administrator/components
administrator/modules
administrator/templates
cache
components
images
images/banners
images/articles
language
media
modules
templates
'
for i in $PLACES; do chown -R apache:apache $i; done

find /var/www/html -type f -exec chmod 0644 {} \;
find /var/www/html -type d -exec chmod 0755 {} \;


Is hashing a DLL useful to protect from DLL hijacking?

It all boils down to how compromised your system is.
If attacker is able to only put/replace your dlls with malicious ones -
probably some sort of digital signature will help to filter our untrusted dlls.

If attacker controls system enough to replace not only dlls, but also your executable -
he can modify code which verifies signature, defeating your protection.

As for .net assemblies strong names - strong name is not for security and must not be
considered as a protection. It can only help to ensure that assembly was issued by a specific
vendor, and not modified since then. Assembly can be modified and re-signed at any point
with different private key (of course, vendor will change in this case). But assembly
will remain valid and signed.

As for hashing algorithm - it is probably fine to use SHA256, it is used by microsoft when computing
hash for digital signature of assemblies.


Using Fido U2F or similar as primary authentication method?

Indeed! I use/build/deploy both standard smart card PKI solutions (SSL client certificate, applets, browser plugin, middleware...) and FIDO U2F simplified PKI solutions and FIDO U2F works great even as a primary authentication method.

It can be used as a primary authentication through a shared login url page with username and FIDO U2F or through a by-user-unique login url (to identify username without even asking) with FIDO U2F. Another non-standard use case but easy solution if you only have to deal with a very few users: you can even skip the "asking for a username part" (server only need to send every known key handles to the device to find the right one).

About adding PIN protection, we are starting to see products with local PIN entry protection like the onlykey (https://crp.to/p/)

You can even develop your own FIDO U2F API compatible solution with enhanced features to add PIN protection, shared identity, simplified encryption... I am one of the few "mad dogs" working on such solutions.

Note/reminder : FIDO U2F works on Chrome on Windows, Linux, OSX, Android. Firefox built-in support should be available in a few weeks. There are already FIDO U2F USB security keys, NFC Cards/keys and soon there will be Bluetooth Low Energy (BLE) devices.


How can I publish text and video without revealing my identity?

This is an extremely broad question and it depends on many factors. You'll need to adopt a pen name. This name must have no relationship to your name or your interests. If you like video games, you must not use a Mario reference, for example. Do not interact with your pen name either. That is, do not even mention that you (the real and public you) know that the book exists. This is called OPSEC.
You might want to manage the videos and publish the book while using the Tails live DVD.
Anonymously publishing a book
Avoiding attribution with the book requires you pend special attention to resist stylometric attacks. There are dozens of research papers on how to do this, as well as tools to assist with it. The general idea behind stylometry is that everyone has a unique writeprint, and with sufficient text, it's possible to uniquely identify individuals. It's a very powerful technique using multiple methods and can accurately identify if two texts are from the same individual in a set of nearly a million. Avoiding it requires adhering to strict writing rules. Stylometry is a bigger deal if your adversaries are sophisticated.
If your neighbors, co-workers, etc. have access to a large number of "sample" texts from you, they will be able to use simple and public tools to determine how likely it is that this book was written by you. I do not know how sophisticated they are or how dedicated they are into proving authorship.
Anonymously publishing a video
It's more difficult to hide your identity when creating a video. If you expect any level of sophistication behind those who want to identify you, you need to use a throwaway camera. The reason for this is that every camera lens and CCD sensors have unique artifacts that may not be visible to the naked eye. These artifacts can prove with absolute certainty that two videos come from the same camera. Other than that, it really depends on what the video will be of. You'll need to avoid having anything that can identify you in the background, for example. It's also vital to strip EXIF data, if present.
Protecting the identities of your readers
Unless someone is purposefully trying to remain anonymous, they are going to be identified. You can perform the most basic privacy measures like hosting the video on a site which does not keep or publish logs and using a distributor who does not require personal information. Even then, you must expect some of your readers will talk about your book with their real name on social media.
At the extreme end, you can publish the material through a Tor hidden service. This is a special domain which can only be accessed over the Tor anonymity network. Naturally this will alienate some readers, as not everyone will be willing to download a new browser just to read your book, but it will guarantee that, by default, everyone who views the material will leave no trace of doing so on their computer or in their ISP logs. Obviously, this doesn't prevent someone from disclosing that they read your book...


Is there a rule-of-thumb for the minimum time for a password hashing function?

Minimum time? You want the hash function to take as long as you find tolerable for your application.

You suggested 50ms and 500ms. While 50ms is just too fast, 500ms is just a little to slow. In 2015, @Thomas Pornin recommended a minimal speed of 241ms. That was the recommendation 2 years ago so you might want to go just a little higher, for example 270ms.

By all means you can use your 500ms, but only if that's not too slow for your application.


For the broadest coverage with the fewest arguments, use your credentials as input into Nmap's credential brute-forcing scripts. Any of the scripts that use the unpwdb library will read usernames and passwords from a common source, which you can specify on the command-line:

nmap --script brute --script-args "userdb=userfile,passdb=passfile"

If the userfile contains the username and the passfile contains the password, then the brute-forcing will just use the one combination and then end.

Use caution in selecting scripts, though; not all of the brute-category scripts use unpwdb library, so some of them may perform bruteforcing with other lists of usernames and passwords: Here's a list of them.


How compromised should I assume my computer is?

Whether or not you should leave SSH exposed is subject to debate. I'll avoid that.

When you attempt to login to an SSH server, you complete the handshake prior to entering credentials. This means that even without a username or password, an SSH connection can show up as established. If someone was trying to brute force you, you would see some connections as being established.

You should check your server log files. If they have root access, it's easy to hide any wrong doing, so this is not a guarantee.

I would start with your lastlog to see your most recent successful logins.
I would then check for failed SSH login attempts, and see if there is any relation to that IP

grep sshd.\*Failed /var/log/auth.log | less

There is more you can and should be doing if you feel like you have been compromised. I am not going to cover everything, but wanted to suggest that there is the possibility that you were not compromised based solely on the data you have provided.


Does the strength of password matter in bcrypt?

The "strength" of a password is exactly how much it is unknown to the attacker. It always matters. That strength equates to the number of tries (on average) that the attacker will have to perform in order to guess it.

What bcrypt does is that it makes each try more expensive. With its configurable number of iteration, set sufficiently high, bcrypt can make it so that the attacker cannot try more than one password per second on his machine. This is much better (for you) than a billion tries per second, with a less suitable hash function: it makes cracking your password a billion times harder. However, if your password consists of only one character, the attacker will still find it in less than a minute.

So while bcrypt makes weak passwords more tolerable, it cannot save your skin absolutely.

(Output length of bcrypt is irrelevant for this. It is normal that hash functions have a fixed output size; in fact, if the output size depended on the input size then it would be a weakness, since it would leak information on the password.)


Is it possible for IMSI-Catchers to block emergency calls?

Is there anything that makes a regular call different from an emergency call?

Not physically, the signal works pretty much the same way as any other call. Phone manufacturers just add the ability to dial emergency numbers with locked phone (my Samsung allows me to add my own emergency numbers, eg. parents, so they can also be called from locked phone). Operators allow emergency calls without SIM (read without payment).

  Is is possible for an IMSI-catcher/cell-site simulator to block emergency calls?

An active simulator can block them. Some were even accused of doing so by accident. It works very similarly to a jamming device. Passive devices will not prevent any types of calls.


I cannot find any official statement from Adobe about the problem. But, Flash seems to have bytearrays shared between workers which are similar to SharedArrayBuffer in Javascript and probably can be used for high precision timing. Therefore I think that running Flash content can actually increase the risk of a Meltdown/Spectre attack. Still, given the security track record of Flash I think that there is already a large risk when using Flash in the first place and that Meltdown/Spectre attacks only add a little bit on top of that.


From the homepage:

  A potent cocktail of AES-256 encryption and PBKDF2 key derivation ensures that no one but you can see into your data. Everything from your passwords to the addresses of your saved websites are fully encrypted whenever you aren't using 1Password.

So it sounds like they derive an encryption key from you password using PBKDF2 and then use it to encrypt your passwords with 256 bit AES. (Or perhaps they just use the password derived key to encrypt another key they encrypt your passwords with, to make it simpler to change password, but the security should be the same.)

In other words, it is like your firsst option (but off course I have only read their homepage, not their source code). A password manager that worked like your second option would be a security catastrophe, and I do hope there are none on the market.


ISP provider does not giving permission to change my router password

No.

It means that your ISP provider can basically control your network. Change DHCP ranges, control port forwarding etc.

In a business situation, with sufficient contractual assurances, this might be possible. After all, some companies even outsource their complete IT.

In a personal situation, I would take a small SoHo router and connect only the WAN port to the ISP provider's router.


why don't we measure the strength of crypto against the cost it would take to crack it?

There can never be a straightforward calculation for this.

For example if you look at the LogJam attack and rainbow tables it is quite clear that there is a clear trade-off and breakdown in the resources that can be invested to crack 'every' encryption event and the resources required to crack one encryption event.

Obviously each cypher and protocol (and implementation too) will be critically examined to push both the initial investment and per encryption cost higher and higher. Logjam will push for better choices in coming years.

Candidate list of different components

Pre-Compute requirements for the specific use-case to be attacked.
On the Fly or after the fact requirements for the specific use-case to be attacked.
Number of Candidate Events for the use-case that might be attacked (by a nation state for example) The pre-compute requirement costs can be spread over these use-cases.

And these components will change quickly and the applicable use-cases will be many and varied.


Is brute force a probable threat even if you enable CAPTCHA and rate limit logins?

The protections you describe are good ones that you should consider, but there can still be weaknesses:

Many CAPTCHAS can be solved by robots, or you can easily pay people to solve them en masse for you (there are companies selling that service).
Account lock out is a good idea, but if you do it based on IP someone with access to a botnet could retry login on a single account from different IP:s until they get in.
Offline brute force is still a problem if your database gets leaked. If the attacker has access to the password hash, they can try all they want on their own system. That's why you should use good hashing.


Web Application Authentication Using Computer Properties

The browser fingerprint is public information for any site the user visits, so this information should be treated simply as a 'username' and nothing more.

The problem here is if the user changes computers, browsers, or settings they may be locked out of their account. There may be ways around this, but then you veer from your path of simplicity.

The other problem is with a PIN for a password. When using a PIN for a password, the entropy is significantly reduced and would be easily brute forced. Unless you are requiring your users to have a 20+ character PIN, this is highly insecure.

These are major flaws with your idea, though it is novel to say the least. Whether or not you implement this would really depend on the nature of your game, the users, and the required security. It is not a system that I would put ANY trust in, but whether or not trust is required is up to you.


This isn't a great answer, but right now I think it's probably the only one possible, because this is a remarkably challenging problem. I'll go over a little of why for the others playing along a home.

Humans generate passwords in a variety of idiosyncratic ways:

Some are so naive that there's no machine learning necessary ("password", "dragon", etc.)
Some of them are not straight single words, but very familiar to just about anyone who has had to pick a password that follows complexity requirements ("Spring2019!")
Others are difficult to parse until you understand the underlying method (keyboard walks like "qazwsxedc", initialisms from song lyrics, etc.)
Others are ambiguous (is "hearthandhome" derived from the base words "heart" and "hand", or "hearth" and "and"?)
And if a password is 100% randomly generated, there's no underlying 'algorithm' for a computer to figure out at all!

For human-generated password "algorithms" like the ones above, some are more difficult to emulate - starting from the same principles and generating similar passwords - than others. And going the other direction - taking an existing string and figuring out how the original creator of that password constructed it from its atomic components - is even more difficult. (This is probably why ML-based approaches seem so attractive.)

This is a hot area of research. Unsupervised learning may indeed be the only approach, but the tricky part is figuring out how to get decent training data at sufficient volume - if for no other reason that we can't usually ask the original password creator to explain their reasoning. (It's quite common to crack passwords by throwing the "kitchen sink" at a corpus of hashes, with a subset of the resulting passwords cracked even though we don't understand how the original password was created in the first place!)

Some breadcrumbs:

You're already familiar with the PassGAN effort
Matt Weir's PCFG Cracker (and its associated C-based rework) are probably some of the best places to start
Dmitri Fousekis' rurasort is a Python approach that might also be of interest.


What private information is stored in a cache db wal file from android mobile device

.db-wal file is a sql database write ahead log (wal) file. You can view more information on it here.
db-wal files

The sql database for whatever application it is made it, it is a normal file. you can use a file explorer such as x-plore on android and view contents, some of content may be encrypted some not.


Is it possible to spoof the mac address of a wireless adapter so that windows sees the spoofed mac as the physical?

Partially, yes. Windows OS (eg. using ipconfig command) sees the spoofed MAC address as the permanent MAC address.

However you can NOT say all of the applications running on Windows will see the spoofed one as the permanent one. Applications might be using some ways to acquire the permanent (burned-in) MAC address of the adapter. (For instance they might be using DeviceIoControl with OID_802_3_PERMANENT_ADDRESS option.) So some applications are harder to be fooled.


Resetting LUKS password from CLI with the recovery key

For the partition which is encrypted with LUKS, you will need to get the offset for the partition as well as the logical sector size of the device. Using sfdisk together with a regex expression is useful for this. Assuming the partition number with LUKS is partition 2, and the image file is backup.img:

# set the partition number for LUKS and the image file
partdev=./backup.img
partnum=2

# get offset of partition, sector size, and the next free loop device
partoff=$(sfdisk -d $partdev | grep -oP "$partnum : start= .*\K[0-9]*"
secsize=$(stat -c %B $partdev)
loopdev=$(losetup -f)

# using these values, create a loop device, decrypt, and mount LUKS
losetup $loopdev -o $((partoff * secsize)) $partdev
cryptsetup luksOpen $loopdev backup_crypt
mount /dev/mapper/backup_crypt /mnt

You now have the decrypted filesystem available at /mnt. Do what you want with it. When you're finished, you need to unmount, close the LUKS device, and remove the loop device:

umount /mnt
cryptsetup luksClose backup_crypt
losetup -d $loopdev


What I'm going to write here is not best practice, because if anything usable security research has shown, it's that the best practice (e.g. NIST guidelines) is seriously lagging behind on research. This is a condensate of research done on the topic, my own discussions with usable security experts at UCL, and my own approach as an interaction designer.

Take the question in reverse: what are the security requirements for your website, and what are the authentication requirements?

Security

For most websites, this boils down to one simple question: what irreversible externalities will the users (the users first, please. Then you as a provider) suffer if their account is stolen?

If users suffer serious consequences (e.g. financial losses, significant loss of reputation, identity usurpation with potential legal repercussions), then you care about them having a non-reused, strong password. Otherwise, you can let them reuse a password of their choice.

This determines whether you control the authentication factor, or they do. The intrinsic truth behind this rule is that users will reuse passwords simply because they have to cope with too many passwords to make a unique one for every website (see research on managing password portfolios).

Usability

Now it's time to talk about interaction modalities. What we're looking at here is to proportionalize the amount of user effort to the perceived benefit of using your website's services. Do users need to log in once a year to do some tax return or renew a subscription? Then, don't make them remember a strong password.

Do they need to log in on a regular basis to your service, and is automatic login not advisable (e.g. online banking or email)? Then, users might be more tolerant of learning a generated password. The key here is that users themselves must be convinced the perceived benefit of the service outweighs its perceived security cost, or they will disengage (see the Compliance Budget theory).

Low-effort strong authentication

What do we do when users cannot tolerate the effort requirement of a strong password? Let's now look at your own authentication requirements. The most glaring option here is to delegate authentication to a third party. This could be Facebook or Google, or a government-backed federated identity scheme for services with legal obligations to authenticate users in the real world.

You could also switch to authentication tokens, or add authentication factors to compensate for a potentially weak password. You could also go the route of one-time passwords sent via email. The solutions available depend on what restrictions you have with regard to alternate forms of authentication.

High-effort strong authentication

Remember to keep the perceived cost-to-benefit ratio of your authentication scheme balanced over time.

Don't be the kind of moron who imposes a unique, super-complex password onto their users only to force them to change it every 3 months, unless your threat model really justifies it. This is a sure way of getting users to store their passwords. And with users logging in onto services via their computer, mobile, office computer, etc., not all of them will use a reputable password manager (notwithstanding clipboard API attacks that threaten a wide variety of use cases for password manager users both on mobile and desktop).

You can also act on the perceived benefit and cost by communicating to your users what they gain from using a unique password and why it's important to do so specifically for your service. You should, in return, commit to good security practice and to respecting your users' time by not forcing additional security theater onto them. If they respect your decision, they will be less prone to bypassing your security measure or switching to competitor services.

Low-security authentication

Just email them a password reset link, let them do what they want, sit back and relax! Or switch to Google/Facebook authentication anyway because it's still more secure and usable than password authentication.


Risk of getting MySQL database compromised with a client application

Yes and no.

First the no: As you have realized, if any data you put in an app that you send to a client can be extracted from it. You can take steps to make it harder to find the password (obfuscation, encryption, etc) but as a general rule of thumb, never put anything in the app that isn't supposed to be public.

So how do you protect your database password? Simple: don't store it in the app. Make a small web application that the app sends the registration details to, and then have the web application store things in the database. This way credentials never leave your control.


For Windows operating systems, Microsoft has multiple KB Articles and other references to address SSL/TLS configuration.

Microsoft KB Article 245030, How to restrict the use of certain cryptographic algorithms and protocols in Schannel.dll has practically everything you'll need to know. Currently, the KB Article covers operating systems ranging from NT 4 up to Server 2012. The specific operating systems and editions covered within that range appear unusually inconsistent, but this should probably be effective for all Microsoft operating systems within that timeline.

There is also a TechNet article, TLS/SSL Settings which is currently scoped to broadly apply for all editions of Windows from Vista to 8.1, and from Server 2008 to Server 2012. This largely duplicates the details from KB Article, but also includes some Group Policy information and other useful details.

The main thing to be aware of, from the above references, is that there are a number of Registry keys and values within HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL which govern what SSL/TLS cipher suites and protocols will be allowed. Usage and effects of each are generally pretty obvious, assuming that the keys and values actually exist (default installations may omit some). Refer to the KB and TechNet articles for more detail, or Google for information about "SCHANNEL" Registry entries.

However, the above is only effective for applications and services which rely on SCHANNEL for SSL/TLS security. Non-Microsoft programs very often come with their own SSL/TLS implementation which must be configured separately. This is especially true for any applications which provide a web interface that is not served via IIS. In some cases, you will not be able to configure these options yourself, or you may have to "hack" them in without vendor support, for a non-Microsoft program. You'll have to investigate the support options for each application on a case-by-case basis.

Also bear in mind that SSL/TLS is not only used for websites. E-mail, remote access protocols, directory services, and many other applications and services also rely on SSL/TLS for connection security.

For testing the configuration, you will need tools like Wireshark or Fiddler to inspect the SSL/TLS handshake. The handshake will contain information about what cipher suites and protocols are supported by the server and client. Automated vulnerability scanning tools like Nessus, and penetration testing toolkits like Kali Linux, also commonly have utilities to test this. However, they may not be configured out-of-the-box to target all of your specific SSL/TLS-dependant applications or services. Google for usage guides, or post separate questions on an appropriate StackExchange site, as needed.


Can a file that has been opened and read still contain a virus?

There are numerous bypasses to the methods used to check if a file is Malware.

Some advanced malware detects hosting environments like sandboxes or virtual machines and will not trigger until the file is open directly on your machine. Malware can be set to activate after a certain period of time that such as day so running in a sandbox will not detect it.

Malware and anti-malware is an arms race so what can protect you today may not tomorrow due to bypasses or creative thinking.

So yes there is a possibility this could happen.


what an attacker can do if he/she got access my router admin panel?

Yes she/he have to simply change your router default DNS settings and forward any lookup to a DNS server that is under her/his control. With that she/he can start various attacks.

Some ideas:

Proxify your traffic so she/he can inject malicious code on every
HTTP resource you are visiting.
Push back-doored updates to some
programs.


Is this VM-sandbox idea a good idea for testing viruses?

These are good ideas but ensuring the system in Step One is not writeable may be a challenge.

Other things you may want to consider is the potential risk of a BIOS infection to the hypervisor host on the off-chance you are dealing with something advanced.

Similarly all connected devices may be vectors for infection think about BAD USB infecting all shared USB devices. I would have a concern about this in your setup more than anything.

https://srlabs.de/badusb/

An alternative might be to dedicate a computer to this task and leverage bootable CD/DVD's for your base OS and have no hard-drive at all. Then use a second dedicated CD/DVD drive to import data to be analyzed via CD/DVD-rw disks. Optionally you may need to treat these as dirty unless you can forensically wipe them.

Again, I think you have a good idea but I would seriously consider the long-term risks of a BIOS infection as well as potential data bus infections to things like USB devices, Firewire, Thunderbolt, etc...

Obviously you want no network connection here either and if possible no wireless connections including things like bluetooth. You want to think of this more as a forensically-sound workstation if possible.

Finally you may also want to have a fake virtual network connection so the machine doesn't appear to look like a forensic workstation to the malware.

Note: I think you can do all this very inexpensively so you may be able to try a few different methods until you find what works best for you but that said I do think you have a good idea for basic stuff I would just take into consideration the issues I mentioned above.


when defining constants, is #define more secure than static const?

static const is more secure, but not for the reasons you're thinking of.  It permits the compiler to perform type checking, which will catch a class of bugs that #define won't permit it to catch.
In regards to your specific concerns:

"#define" is embedded in compiled code, while static int leaves a variable in memory, which a user can change the value of TimeLimit in memory content easily
If using static const, it is easier for user to know the value of TimeLimit because extracting the value from memory is easier than extracting from compiled code.

In theory, this is true.  In practice, every compiler in current widespread use will compile the two cases identically (give or take type-inference rules).  In my testing with GCC, both a #define and a static const turned into the following assembly:
movl    $30, %eax

ie. move the literal value 30 into register EAX in preparation for performing an operation on it.
Now, there is one exception to this: if you're compiling with debug information, a static const value may be present in the debugging information where a #define will not.  But you shouldn't be shipping debugging versions of software to anyone you don't trust -- or most people you do trust, for that matter.


How to ensure my API requests are sent using SSL

As in any SSL connection, the system is secure if you use TLS 1.2 with only secure ciphers allowed (that is, good SSL configuration).

Other than that, SSL is MITM protected if the systems involved only trust the legitimate certificates used on the SSL connection. If one may inject on your truted certificate list or convince your system to accept a fake certificate, it will be able to do a MITM attack by presenting you the client the fake certificate, deciphering the data and reciphering it to your server, acting like a proxy.

So you may want to make sure you have trusted certificates correclty and restrictively set, and maybe also want to use public key pinning (explicitly deciding to trust specific public keys instead of fully trusting certificates or certificate authorities). You may want to check what are the trusted anchors that PHP is using, and it looks like depending on the version it may not even check the certificate at all, and that would make a MITM trivial. More info on that here: https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432

  Note that the protocol in the url is https and that the data and api
  key are simply included in the url as segments.

I´m supposing you are worried that the API token would leak here because it is visible on the URL. Actually the api/apikey/somedata part is protected by SSL, what happens behind the scenes is that you stablish a SSL connection to myapp.com (without saying what you want from it on clear text) and then, just after sucessfully connected,  using the protected and ciphered connection, you request to "get api/apikey/somedata". So the api key will not be visible for anyone listening. However, the full URL may leak by other channels, like a browser history, logs and so on. Thats why usually authentication tokens are added to HTTP headers instead of path or query params. They are as protected as in the path from the SSL point of view, but it less likely that it leaks by mistake.


Suspicious SMS getting received on selected browsing

Its very possible that your operator inserts a header in outgoing HTTP traffic containing your mobile number, just to allow remote billing, ad targeting, and remote subscription.
http://www.htxt.co.za/2014/10/29/vodacom-admits-to-leaking-phone-numbers-to-websites/

Those sites you visit, are those "trusted" sites or are they "random"? If they are random, it might be that those sites are using your phone number to bill you just to gain Money.
Its not possible to turn off such auto billing.

To protect yourself against large phone bills, I would suggest switching to prepaid. If some subscription service initiates on your phone then the prepaid card will exhaust quickly and then the subscription service will stop to work, preventing any high charges to you.

Its might be very possible that you in the TOS of your operator, did accept that says that by visiting a site over mobile data, you accept that the site might bill you for its usage.
To prevent such things from happening, you could in addition to getting a prepaid, also get some sort of VPN tunnel, either to your home, or to a VPN operator, then preventing the operator from injecting your number in your HTTP traffic.


How too use R0b0tPirates 500 error bypass

The "Custom Injection Payload" section of the SQLMap Documentation
explains how to add a bypass like this.  It seems to me you would use --suffix followed by the AND clause you pasted above.

Here is the text from the docs:

  Custom injection payload

  Options: --prefix and --suffix

  In some circumstances the vulnerable parameter is exploitable only if
  the user provides a specific suffix to be appended to the injection
  payload. Another scenario where these options come handy presents
  itself when the user already knows that query syntax and want to
  detect and exploit the SQL injection by directly providing a injection
  payload prefix and suffix.

  Example of vulnerable source code:

$query = "SELECT * FROM users WHERE id=('" . $_GET['id'] . "') LIMIT 0, 1";

  To detect and exploit this SQL injection, you can either let sqlmap
  detect the boundaries (as in combination of SQL payload prefix and
  suffix) for you during the detection phase, or provide them on your
  own.

  For example:

$ python sqlmap.py -u "http://192.168.136.131/sqlmap/mysql/get_str_brackets.php?id=1" \
-p id --prefix "')" --suffix "AND ('abc'='abc"
[...]

  This will result in all sqlmap requests to end up in a query as
  follows:

$query = "SELECT * FROM users WHERE id=('1') <PAYLOAD> AND ('abc'='abc') LIMIT 0, 1";

  Which makes the query syntactically correct.

  In this simple example, sqlmap could detect the SQL injection and
  exploit it without need to provide custom boundaries, but sometimes in
  real world application it is necessary to provide it when the
  injection point is within nested JOIN queries for instance.


What to do about email threats containing leaked passwords?

This is a known scam. The scammers look up emails and cracked passwords in public leaks of site databases and then send an extortion email to people. The password is already out in the open, sorry. You should change the passwords on all sites using that password. On the up-side, this does mean that the person who is emailing you is not actually a hacker and does not have any malware on your system.

You should use a password manager to prevent this from being an issue in the future.


Encryption algorithm keySize restriction in JSSE 7

Rather old question, but just happened to come aross the same issue. Didn't have luck trying to avoid 128 bit AES ciphers by specifying "keySize < 256". What finally seemed to work was:

jdk.tls.disabledAlgorithms=..., AES_128_CBC, AES_128_GCM

This should force Java to only allow 256 bit AES ciphers - provided that the JRE allows using strong cryptography in the first place (which most recent JREs do out of the box, otherwise you still have to download and install the "Unlimited Strength Jurisdiction Policy").


Is there an anti virus that protects processes from being injected code to?

Most antivirus will try to protect processes from code injection. However, this is ultimately heuristic: the only clear distinction between malicious code injection, and normal process behaviour, is at the human level: did the human user actually wanted that to happen, or not. Software in general, AV in particular, cannot fathom the intricate psychological processes in the soul of the human user.

So AV software commonly relies on recognizing known "hostile payload" and tries to catch variants thereof. It is a delicate compromise between security and functionality: the AV should let the normal data flow, but still reliably locate and destroy maliciously crafted data. So AV vendors must tap-dance between false positives (blocking normal data, thus breaking functionality) and false negatives (failing to block malicious data). Furthermore, AV ought to be efficient: they cannot afford to use all the CPU resources of the machine in order to come to a block/pass decision.

Common AV surveys all network communications to apply their automatic filters on all data flows. Some also try to be especially careful and strict for data which flows to specific, "sensitive" process like, indeed, lsass.exe.

Summary: yeah, AV do that. But don't expect miracles.


/dev/urandom isn't truly random, but once it has been properly seeded it's good enough for security critical use. For true randomness, you need /dev/random, but I'd stay with urandom.

Your implementation produces slightly biased output for two reasons:

The number characters (31) doesn't evenly divide 2^31. This bias is small enough to have a negligible effect on security. It's possible to fix this, but I wouldn't bother.
The rounding technique is flawed. The first and last character are only half as likely as the rest.

I'd change the following:

$diff = $max - $min + 1;

...

$fp = (float) $val / 2147483648.0;// 0x80000000, choosing this value ensures that $fp is truly smaller than 1, and not equal
return floor($fp * $diff) + $min;// now all values 0 <= x <= diff are almost equally likely

With 12 characters the total entropy is around 60 bits. With one million codes guessing even one of them should take around 2^40, or a thousand billion attempts. This is infeasible for online attacks, where the attacker needs to send one request to your server, but cheap with offline attacks. It looks like offline attacks don't apply to your system, so the codes seem large enough.

Assuming your php code has no subtle flaws this should be fine. I'm no php programmer, so I might have missed something.

In PHP 7 you can use random_int which is secure and easy to use.

$randomIndex = random_int(0, $count - 1);

In earlier versions you could use the random_compat
 library.


Asuming that this injection basicly works:

localhost/phptest.php?lang=(){:;}; /bin/ping http://localhost

Your problem is related to the command you try to inject. Ping accepts a hostname as a parameter. But you injected http://localhost as a parameter which is a url and cant be accepted by the ping command. It must be ping localhost instead of ping http://localhost.