How browser detects Phishing Pages? I want to know how browsers detect phishing pages.And also what methodology browsers use to detect phishing pages?

I'm not aware of any plugins specifically that do this, but in the case of the Google search engine, or something like Norton DNS or google DNS it's all done on reputation.

For example if you report a page as a phishing page, then a hundred other people also report it, when that search result comes up in google it will say that the page is potentially unsafe. If you're using a service such as Norton DNS then it will direct you away from that page.

I would imagine any browser plugin or functionality would do something along the same lines, checking each URL against a reputational database before advising whether it is a safe link or not.


Is the perfect MITM attack possible? Let's imagine a data link layer level MITM attack. Is it possible to fulfill all of the following points?

you completely hide your identity by forging your own MAC address
you create malformed packets, so the router doesn't even know you are exist
you intercept every packet from the victim, and repeat it to the default gateway (and vice versa), replacing crucial informations such as SSL/TLS public key

Is there a way to accomplish this? How can I detect this kind of activity? I'm afraid the attacker can do basically anything without leaving any fingerprints, if it goes deep enough in the OSI model.

Shenanigans at layer 2 are fairly trivial. Many devices (especially mobile devices) are automatically spoofing their MAC addresses; it is simple to do so on most desktop platforms. By default, if you are sending any traffic on the network, the router may know you are there. By definition, if you are connecting to a wireless network that requires authentication, the access point will definitely know you are there. Whether it knows who or what you are is a different story. The only way to be truly undetectable from a network perspective would be to sniff wireless traffic passively.

replacing crucial informations such as SSL/TLS public key

There are several classic attacks that can be launched from a MitM standpoint; notably, SSLStrip. However, for any service that is already connected to using TLS, you're going to have a hard time. You cannot simply replace certificate information from the server without triggering a security warning on the client, unless it is a poorly written application (e.g. modern browsers are out). That is the nature of TLS; it authenticates the server and prevents an active MitM attacker from being able to do much besides DoS.
There are technologies to detect and prevent ARP spoofing attacks, and these functions are largely implemented in enterprise networking hardware (e.g. Cisco whitepaper). The general concept is that the device uses prior knowledge (previous addresses, DHCP snooping) and looks for suspicious changes in the proposed MAC address mappings or gratuitous ARP packets being sent. If this activity is detected, the packets are ignored and no changes are made to the ARP table. There are also endpoint tools that may be able to work similarly.
If you can't afford to risk ARP spoofing attacks, there's always the option of disabling ARP altogether and using static ARP entries. But in general, properly configured TLS will thwart most risks. Of course, any non-encrypted traffic is fair game to be viewed and modified by an attacker.


How does nmap determine if it's running HTTP service on a port? Fails here I'm running apache on 192.168.56.178, which listens on port 80, 8090 and 8095 (configured as <VirtualHost *>).

Now If I open my browser and point to any of those 3 ports, e.g 192.168.56.178:8095 I will get a It works page.

Then I try to determine which port runs HTTP service with nmap,

%> nmap -p 80,8090,8095 192.168.56.178

Starting Nmap 6.40 ( http://nmap.org ) at 2013-11-01 17:00 CST
Nmap scan report for 192.168.56.178
Host is up (0.00025s latency).
PORT     STATE SERVICE
80/tcp   open  http
8090/tcp open  unknown
8095/tcp open  unknown

From the result, nmap cannot determine ports other than 80. Why is that?

Can I fix it?

nmap defaults to the -sS option if a scan type is not specified. The -sS flag is a simple SYN scan to check the status of the port. No advanced fingerprinting is done to determine the service running on the port. In this mode, nmap merely looks up the most common service running on the particular port using the nmap-services file and displays it under the services header.

If you want more accurate fingerprinting to be done, try running nmap with the -sV or -A flag for version detection and aggressive mode respectively. The -sV version detection flag will instruct nmap to perform more intrusive scan types like making HTTP request to the port and reading the banner information for example. The -A flag goes a step further and attempts to scan the port with NSE scripts. Both the -sV and -A flag should identify Apache running on ports 8090 and 8095.


Is there an added benefit to authentication within a part of an application, after authenticated into the main application? Essentially I have a application that is 2 parts.

One part is on the user's machine, which will upload files to my server, and
the other part is a web application that works with those files.

Both of the Applications implement security protocols for Authentication/Authorization on their own using the same security framework, but I'm not sure if they actually share any Session data (not sure how I would find that out).

My question is.... if I added a WebView portion to the Main Application, would it be wise to make them log in again, since that's default functionality when going to the site?

Or, since they already logged in the main application, that there is no point in making them "log in again?"

To add further into the discussion, the Main Application is more of an admin control area, where you create your users, so that others can log in to those users on the web.

IF I were to have 1 login for both, would it be weird logging into the admin (main) and then wanting to view a user would log in itself through the main Application and forcing a login?

I figured I would post both scenarios, in case one would be different.

I assume that once you are in, it doesn't matter what happens.  The user accounts cannot be edited from the web, just the main application, so in reality once you are logged into the main, there isn't much you could do by auto-logging into the web part.

I also am curious if I were to implement a password recovery for users, if it would make sense to allow changes to passwords in the application (without remembering the user password), or do a recovery process as if they were the admin.  AS I said above, once you're logged into the Admin, all users are vulnerable to anything.

Thanks for any advice!

I'll propose a rule of thumb which may help you with your decision:

  When switching from a lower privilege level to higher, make them login again.
  When switching from higher to lower, do not require another login.

Here's an example of how bank ATMs implement this rule. Consider these 2 scenarios:

You put in your ATM card, enter your pin, select "Withdrawal", choose your amount, receive your money, view the balance of an account.
You put in your ATM card, enter your pin, view the balance of an account, select "Withdrawal", choose your amount, enter your pin again, and receive your money.

The only difference between these scenarios is whether the withdrawal happens before or after the balance inquiry. If you begin your session with a withdrawal you are assigned the highest permissions, and therefore you can do an item of lessor permission afterwards. If you begin your session with a balance inquiry, you are assigned lower permissions, and then in order to perform a withdrawal (which requires the highest permissions) you must enter in your pin again.

Perhaps you can use similar reasoning when determining if your user should have to login again.


OAuth2 for mobile apps with confidential backend client (Is PKCE required?) I'm wondering why neither rfc6749 nor rfc8252 seem to consider the case where the mobile app does not make protected resource requests (and is therefore not a client) but instead relies on a backend server (confidential client) that does.

*Note that I use the term mobile app instead of native app only because the spec defines a native app as being a public client:

From rfc6749

Section 2.1:

  A native application is a public client installed and executed on
        the device used by the resource owner.  Protocol data and
        credentials are accessible to the resource owner.  It is assumed
        that any client authentication credentials included in the
        application can be extracted.  On the other hand, dynamically
        issued credentials such as access tokens or refresh tokens can
        receive an acceptable level of protection.  At a minimum, these
        credentials are protected from hostile servers with which the
        application may interact.  On some platforms, these credentials
        might be protected from other applications residing on the same
        device.

section 1.1:

  client -
        An application making protected resource requests on behalf of the
        resource owner and with its authorization

The case that I'm inquiring about is similar to how rfc6749 section 2.1 defines a web application, but instead of an HTML user interface, the interface would be a mobile app:

  A web application is a confidential client running on a web
        server.  Resource owners access the client via an HTML user
        interface rendered in a user-agent on the device used by the
        resource owner.  The client credentials as well as any access
        token issued to the client are stored on the web server and are
        not exposed to or accessible by the resource owner.

rfc8252's definition of native app seems more reasonable as it doesn't restrict its use to apps that are public clients:

  "native app"  An app or application that is installed by the user to
        their device, as distinct from a web app that runs in the browser
        context only.  Apps implemented using web-based technology but
        distributed as a native app, so-called "hybrid apps", are
        considered equivalent to native apps for the purpose of this
        specification.

But again, the spec only provides the best practice for the case where the native app is also the (public) client.

In summary,

I'm wondering why I haven't been able to find any mention of the client profile I described above (either in the specs or elsewhere).
Would the Authorization Code Grant (without PKCE) be considered
secure enough since even if a malicious app intercepts the
authorization code (sent by the external user-agent to the
native app, via inter-app communication) it wouldn't be able to
exchange it for an access token as it would not be in possession of
the client secret which is stored on the backend?

Note that I'm only asking these questions to gain a better understanding of the theory, and not for anything practical.

The flow you describe is exactly what Google offers for mobile apps : https://developers.google.com/identity/protocols/CrossClientAuth

After looking in more detail the rfc 6749, we can note that this flow does not respect the recommendations.

https://tools.ietf.org/html/rfc6749#section-4.1.3

  The authorization server MUST:

  o  ensure that the authorization code was issued to the
  authenticated
        confidential client, or if the client is public, ensure that the
        code was issued to "client_id" in the request,

Indeed, the authorization code was issued to the native app, and it is the web application that tries to exchange the code.

It is up to the developer to decide if he wants to strictly respect the RFC and in this case use the flow Authorization code with PKCE then send the access token to the backend server so that it can access the resource server; or if he wants to use the same flow as google.


Is Java javax.servlet.http.HttpServletResponse sendRedirect() auto replace the carriage return(%0d%0a) to prevent Http Header Splitting attack? I just tried to demonstrate a simple Web app program to simulate the Http Header Splitting attack but I failed. I realise that this sendRedirect() function has filtered my carriage return and replace to space (%20). I wanna to confirm whether I am right or I doing the wrong way. Any comment and and suggestion are welcome.

For your information

Server info: GlassFish Server Open Source Edition 4.0
Servlet version: 3.0
JSP version: 2.1
Java version: 1.7.0_51

Yes, GlassFish does filter newline characters in headers. Tomcat does as well. I don't know about other servlet containers (Jetty, WebSphere, etc.)

com.sun.net.httpserver does NOT filter newlines, so you can use that for your simulation.


Is it reasonable to do a pentest (or other non-theoric security audit) over a critical infrastructure? Almost all agree that during a pentest it is impossible to guarantee the integrity of the target (Is it acceptable that a skilled professional pentester deletes or modifies sensitive data in production unintentionally during a pentest?) because you are going to use unexpected input and automatic tools to see its response.

In this scenario, is it reasonable to perform a pentest over a critical infrastructure? The integrity of a critical infrastructura may be needed to protect human lifes and its malfunction put human lifes at risk.

How can we perform a security test over a critical infrastructure knowning its criticality?

Possible solutions to this problem are:

1) Perform a theoric audit

Theoric audits are ok but will have theoric results not real results.

2) Perform a pentest over an identical environment

When we talk about critical infrastructures (and for other environments as well) may be impossible to have two identical environments because the cost and the complexity of the environment.

When we talk about critical infrastructures we talk about things like:

electricity generation, transmission and distribution;
gas production, transport and distribution;
oil and oil products production, transport and distribution;
telecommunication;
water supply (drinking water, waste water/sewage, stemming of surface water
(e.g. dikes and sluices));
agriculture, food production and distribution;
heating (e.g. natural gas, fuel oil, district heating);
public health (hospitals, ambulances);
transportation systems (fuel supply, railway network, airports, harbours, inland shipping);
financial services (banking, clearing); security services (police,
military).

In any test that deals with critical systems, one would usually limit the test to low-risk operations, and avoid automated tools (e.g. Nessus) that might potentially harm the system.

Specific to critical infrastructure, I would say the following:

Schedule the test at a low demand point where applicable.
Make engineers and other support staff aware of the test, and have them standing by to fix any issues quickly.
Ensure that extra capacity / redundancy is planned during the test, where possible.
Ensure that the testers are given an appropriate action plan that details how to deal with serious faults, or unresponsive systems. This should include emergency contacts.

Despite this, there will always be a risk. It's something you have to deal with, and in a way it's a good thing. If the testers knock something offline by performing only low-risk actions, then you know that an attacker could do much worse. An accidental system crash during a planned test would suck, but not as much as widespread crashes due to malice when nobody is expecting it. Having it go down in the test scenario allows you to plan accordingly and make appropriate fixes.


Define Patterns in Crunch I am trying to achieve a very specific pattern with crunch. The Wireless Router I use has a very specific Pattern used for the default Password generated by my Provider. I want to create a wordlist or at least Pipe it through to aircrack-ng with the following pattern:

xxxx-xxxx-xxxx-xxxx

The x's represent 4 multialpha-numeric characters spaced by dashes. I read through several help sites and the manpage of Crunch but just can't figure out to get to this pattern. Is it even possible? It is very confusing.

I tried using -t ++++-++++-++++-++++ which gave me one result.

You have to use an externally-specified character set:

$ egrep 'mixalpha-numeric ' charset.lst
mixalpha-numeric           = [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]

$ crunch 19 19 -f charset.lst mixalpha-numeric -t @@@@-@@@@-@@@@-@@@@
Crunch will now generate the following amount of data: 2577832796941975552 bytes
2458412930433 MB
2400793877 GB
2344525 TB
2289 PB
Crunch will now generate the following number of lines: 16730961306185695232

I think crunch's math is off a bit there - Wolfram Alpha tells me that 62^16 is 10^28, which is 47672401706823533450263330816 (which is quite a bit bigger - 10^28 combinations)

Either way, it should be obvious that this wordlist, applied to WPA2, will not exhaust in your lifetime.

For faster hashes with smaller keyspaces, generating the candidates on-GPU (with something like hashcat or John the Ripper, which allow you to specify the mask for generation directly on-GPU), would be much faster. But for WPA2 it's probably slow enough that it won't make a difference.


What are you saying when you sign a PGP key? When you sign a PGP/GPG key, what exactly are you saying to everyone who sees your signature? Are you validating the person, or the email address?

To explain what I mean, take the following two examples:

Validating the person: "I trust that the key 0x559E3EE8 belongs to Bob in accounting; he personally handed me a piece of paper with that public key over lunch. I don't know what Bob's email address is, but if he lists it as one of his UIDs in his key, I'm fairly sure it belongs to him.

Validating the email address (UID): "I trust that the key 0x559E3EE8 belongs to bob.stanford@examplecorp.com; I don't know who he is in real life, but we have sent encrypted emails back and forth, and I definitely know that he can decrypt and read the emails I send him, as he sometimes quotes things I wrote to him. I can also be very certain that there is no man in the middle between my computer and his mail server."

OpenPGP does not define any rules for certifications

From RFC 4880, Signature Types:

  [...] Please
     note that the vagueness of these meanings is not a flaw, but a
     feature of the system.  Because OpenPGP places final authority for
     validity upon the receiver of a signature, it may be that one
     signer's casual act might be more rigorous than some other
     authority's positive act. [...]

Informal best practices

There is a kind of informal best practices, though. By posting a certification of undefined or casual trust level (sig or sig2, signature types 0x10 and 0x12) you declare to be sure of the signee's identity. This might have happened by checking official documents, or knowing somebody very well. Often, people send an encrypted mail containing the signature as attachment to also verify ownership of the mail address.

Certifications of positive trust level (sig3, type 0x13) usually claim some advanced certainty of the signer in what he's doing. This might be because of long-time knowledge of the signee, or high confidency in well-known documents presented (for example, passports of your own country).

Certification policies

As there are no general, enforced rules for certifications, some people post certification policies, which they claim to follow. They often just represent the informal best practice, but can help others at justifying your certification statements.

These often contain information on how you verify keys, what documents you require, how you handle variations in signee's names, and possisbly more. Often, they're signed documents, and referenced from each certification issued GnuPG's cert-policy-url option.


cleartext passphrase for keystore How is passphrase for a keystore to be stored?  we have all passwords encrypted and the key to encrypt is stored in keystore , so how is the passphrase for the keystore to be stored? in clear text? if encrypted then where should we store the key to encrypt? ie seems recursive issue, how to solve without using Hardware security product HCM or whatever acroynm is for that kind of stuff. what is best practise in terms of storing the keys for encryption?

Best practice is not to encrypt the passwords at all, but to hash them instead, for precisely this reason: if you encrypt, then you need to have the key available to the server.

If your system is such that it absolutely MUST store the actual passwords - for example, your server connects to some other service impersonating the user - then there are a few things you can do, like using an HCM, or storing the key on a different server in the hope that it doesn't get stolen along with the main one, or using something like OAuth so that the credentials you store are only usable by the server and hence of less use to an attacker.

But these are only partial mitigations. If you store passwords on the server then the server knows them and if someone compromises the server they can learn them too.


What considerations would need to be taken into account when purchasing a house with multiple smart home appliances? TL;DR - Sister in law buying a house full of smart junk, she wants to keep it, but is afraid of the previous owner spying on her or gaining access to her home. Can this be mitigated while keeping said smart junk?

My sister in law is in the process of purchasing a home that I would love to have -- it's completely decked out with smart devices. Nest Thermostat, Rain Maker irrigation system, it looked like the HVAC registers were electronic, Hue lightbulbs everywhere, security cameras, ip locks, ip garage door openers, honestly just the works. I'm totes jelly.

Unfortunately, since we don't know anything about the installer other than his previous address, we have no reason to believe that any of it is secure. My first instinct would be to ditch all of it in favor of the traditional dumb devices or new smart hardware; but it's not my house, I'm just being consulted because I'm the "tech guy" for my in-laws. Sadly, I know next to nothing about these types of amenities myself other than the fact that the news keeps on bubbling up about hacked cameras and vulnerabilities in them. Is there anything I can do to attempt to ensure the network security while keeping these devices?

I know if I had full control and were dead set on keeping them, I would want them on a different network than my devices, but beyond that I also don't want anyone to be able to access the house or video feed. I'm mainly asking for home automation specific steps. How is this stuff typically controlled, or accessed remotely?

Note: Of course, the real answer here is "The previous owner had physical access to these devices for who knows how long, there should be no reason to believe they will ever be secure", but my Sister in law, despite the fact that she would never invest in smart equipment on her own (and would make fun of people who do it), just loves the idea of having it.

That is an interesting question.

You have already given the theorical answer: it is not only your sister-in-law's system but it is the one of the previous owner too. So you can only trust it if you trust him. At one level, security is always a matter of threat, risk, and trust.

I would agree with your sister-in-law in one point: if she trust the previous owner enough to buy him a house, why not trust him to honestly give her full control on the smart devices? On a legal point of view, he must, and could be in trouble is you could prove he has not.

There is a second point though: how secure is the system on its own? I mean, what are the currently implemented security measures to avoid that anybody passing in front of the house can take control of it? I the previous owner was a tech-lover, it may be correctly secured, but it is very important IMHO that you syster-in-law (eventually with your help) understand enough of it to know what she can, must and cannot do to keep it secure. Typically, if you can control everything with a smartphone, how is the smartphone or smartphone owner identified?

It is currently said that the major threat for a computer lies between the keyboard and the chair, and it is often true in security too: most risks can be mitigated except the user if not educated enough to security.

The following is no more than my advice, and I admit I'm not directly concerned here, so please read it only that way. I think that as she trust the previous owner enough to buy him a house, she can trust him to give her full control and not try to spy her. But she must:

get enough understanding on the full thing to be able to keep it secure
get enough understanding to be able to control if someone or something has come into the system - this is just a special case of the first requirement, and perhaps the most important, but you can help her on that part


Is it there any effective way to prevent shodan to access my webcams Recently while browsing using shodan, I came across a search string to explore webcams.

Some of the searches I carried out were:

webcamxp city:city name

webcamxp geo: longitude and latitude

which exposed some public webcams.

This raises two questions:

Does private webcams/public {for e.g my corporate} to be accessible under these search engine? If so, how could I protect it from these kind of crawling?

There were several good answers to prevent router crawling under these questions. How can I protect myself from shodan?

The same exact rules apply to webcams as in the thread you referenced.  If you put your webcam on an obscure port (not just 8080 or a common variant) then Shodan will not find it while crawling.  If you keep your webcam protected from anonymous access (set unique user/pass settings for all accounts on the cam) then outsiders will not be able to see it even if they do come across its presence in Shodan.  Also, keep your device firmware up to date in order to prevent possible vulnerabilities from exposing it.

Really, these protections are nothing that you shouldn't be doing already. Shodan in one sense is barebones audit tool; if your gear shows up there you are REALLY doing it wrong. Webcams show up on Shodan for one of two reasons: the owner/operator doesn't want them to be private at all, i.e. traffic cams or public park weather cams, or the owner/operator is really not following ANY security guidelines and leaving their cam both in plain sight (on normal ports) and wide open (default credentials or no credentials at all).


Router or Switch can defend against ARP spoofing attack? I'm learning about ARP spoofing attacks. Can a router or switch defend against ARP attacks?

Many modern routers implement arp-spoofing protection as an inbuilt feature.

As Sunny points out, old-school switches ran on Layer 2, and typically didn't analyse Layer 3 (Network Layer) whereas routers do. That said, more modern switches may incorporate functionality that you would expect in a router, and even up to Layer 7 handling QoS and Deep Packet Inspection.


What is the physical security (Evil Maid) threat model of a modern hardened laptop? Why I believe this question is not a duplicate:
There are multiple questions dealing with the exploitation of a locked computer on this site, but most of the answers are focused on exploiting a non-hardened system in default configuration. I believe that in recent years, with major advances in encryption and hardware+software authentication (secure boot, bitlocker, virtualization, UEFI,...), the threat model for a hardened laptop is significantly different and therefore, I'm reasking this question under the following scenario:

Technical assumptions:

I'm using a modern Windows 10 Pro laptop, with the OS and all drivers updated to latest versions.
Laptop is locked, with following authentication methods: fingerprint reader, strong password, reasonably strong PIN (probably would not survive an offline brute-force).
Internal drive is encrypted with PIN-less Bitlocker, using TPM.
UEFI is password-protected, booting from external drive requires UEFI password, network boot is disabled, Secure Boot is on.
I'm connected to the same network as an attacker (attacker may potentially even own the network).
The laptop has an enabled Thunderbolt 3 port, but before any conected device is accepted, it must be authorized by the user (which should not be possible on the lock screen).
Laptop has a free M.2 slot inside, dis/re-assembly is possible in under a minute.

Assuming I'm sitting somewhere with an attacker, I lock my laptop and leave for 5 minutes, is it feasible for the attacker to gain access to my laptop (either by bypassing the lock screen, or extracting files using some other method (extracting the bitlocker key,...)) before I return, under the condition that I mustn't notice anything suspicious after coming back?

What you're describing is an Evil Maid attack. There are a bunch of ways you might go about gaining access in this scenario, but the main one is DMA.

M.2 would give you direct and complete access to the system memory over DMA, assuming that the IOMMU is not configured to prevent this, which it almost certainly will not be by default for a direct PCI-e link. The same goes if you have an ExpressCard slot. One toolset for this is PCILeech, which is capable of dumping the first 4GB of memory from a system without any OS interaction or drivers installed, and all memory if a driver is first installed.

It is also potentially possible if your laptop has Thunderbolt or USB-C, because both of those interfaces support DMA. Generally speaking those interfaces now tend to have hardening features in the firmware and drivers to prevent arbitrary DMA using the IOMMU, but this protection isn't perfect or universal, and there have been some issues (e.g. Thunderclap) that allow an attacker to bypass the IOMMU in some hardware.

What you might wish to do is enable Virtualisation Based Security (VBS) and Windows Credential Guard (WCG), which puts your entire OS in a Hyper-V hypervisor and shifts most of the LSASS service (which caches credentials) into an isolated virtual machine. There are few, if any, toolkits out there at the moment that allow an attacker to recover the cached BitLocker master encryption key from the WCG enclave using a non-interactive memory dump. This also allows you to enable Device Guard and KMCI/HVCI, which should make it exceedingly difficult for an attacker to gain persistence on the system from a one-time DMA attack.


How to detect if a system admin reads CEO mail from outlook server? A friend asked me this question yesterday. System admins are able to access outlook mail server through RDP which is part of their job.

Is it possible to detect who reads email from the CEO or someone else ?

Not reliably.
Your main problem is that the admin probably needs to access those files for legitimate reasons, and it's very hard to separate him doing routine maintenance from him actually reading the content.
If he were to read/export them through the online interface it would obviously show up in the audit logs, but for the sysadmin there are a lot of ways to read the files, and you can't reliably detect all of them.
But to set up detection where you can, you could try a combination of these:

Monitoring local file/folder access
Writing an IDS signature to detect network exfiltration

Monitoring local access will catch more than an IDS, but it will contain lots and lots of routine access.
For the IDS rule you'll want to detect for a unique string found in his PST file like a GUID


Trying to understand how Digital Certificates and CA are indeed secure I understand that Digital Certificates and Certificate Authorities (trusted 3rd parties) help prevent man in the middle attacks during HTTPS connections. However, I am confused on a few details.

Let's say we have a client Alice and Bob who has a server mapped to "bob.com".

When Bob (bob.com) asks a CA (let's say veriSign) for a new certificate to be created and sends them his public key to be put inside the certificate, what is stopping a hacker from intercepting the request, switching the public key with their own, having the CA create a false certificate, and then returning this false certificate to Bob. Is the only protection here that Bob actually checks that the public key on the returned certificate matches what he originally sent in his request to the CA? And then I guess informing the CA that what he got back doesn't match what he sent out, so the CA doesn't maintain a false record?

Assuming that the newly created certificate Bob gets from veriSign is legit, let now say that Alice is going to make a request to "bob.com" via the HTTPS protocol. What is preventing a dual channel MITM attack where a hacker intercepts Bob's new certificate on way to Alice, creates a new one, signs it with their own secret key (which was previously signed by verisign), but then also intercepts Alice's request to veriSign when she asks for veriSign's public key, and switches it out again with the matching public key to the malicious secret key. Now when Alice tries to check the integrity of the false certificate, it checks out because although she thinks she is checking the signature with veriSign's public key, she is really using the malicious public key?

Is the only protection here that Bob actually checks that the public
  key on the returned certificate matches what he originally sent in his
  request to the CA?

If the public key was switched before the CA used it to create the certificate, then Bob's web site won't work at all.  The private key, which he has kept safe, will only work with his original public key.  It is unlikely the attacker can MITM all connections and prevent this fact from becoming obvious.

  intercepts Alice's request to veriSign when she asks for veriSign's
  public key, and switches it out again with the matching public key to
  the malicious secret key.

Alice doesn't reach out to Verisign; Alice only trusts copies of the CA certificates in her browser or computer's trusted certificate store, of which Verisign's happens to be one.

The trusted certificate store is populated at install time (of the OS, or in the case of Firefox, of the application) and is then updated via regular OS or Application updates as necessary - less than you'd think, as many root CAs are long-lived.


Trying to understand RSA and it's terminology? I get the gist of RSA but I'm mostly self taught so sometimes the phrases I picked to describe something don't match up with the widely accepted terminology. I'm trying to remedy this.

I'm working with a NodeJS library called node-rsa. After you load the key, it basically has 4 functions: encrypt, decrypt, sign, and verify.

My understanding is that the following statements are true, although I'm not positive. I'm also assuming that the library knows and follows the proper terminology and isn't implementing things in any abnormal way.

Encrypt uses the provided (or generated from the private key) public key to encrypt the data.
Decrypt uses the provided private key to decrypt the data.
Sign uses the provided private key to encrypt the data, the output is called a "Signature".
Verify uses the provided (or generated from the private key) public key to decrypt the signature.
Encrypting the same data two different times could result in two different outputs depending on the padding. Signing uses no padding and will produce the same output for matching inputs.
If I sign something, I'll need to send the input that was signed as well as the signature to the recipient of the message.
The input for a signature is usually the hash of the message being sent to verify that the message hasn't been changed.

Am I on track or is this all nonsense?

EDIT:

These I feel are obvious, but I'd really be doing myself a disservice if I believed them so fundamental and was wrong about them.

When encrypting something I'm sending, I use the other party's public key.
When decrypting something I've received, I use my private key.
When signing something I'm sending, I use my private key.
When verifying something I've received, I use the other party's public key.

There are still some details I have questions about such as is the signature included in the message or is it transmitted unencrypted and alongside the payload? These questions probably warrant unique questions on the site however.

The source of your confusion is an historical "explanation" of RSA signatures as being "encryption of the hash with the private key". This explanation is confusing, and flawed in many ways. It works only for RSA. Actually it does not work for RSA either.

Let's define things properly:

An asymmetric encryption system defines two functions:

Encrypt: takes as inputs a message (a sequence of bytes, possibly limited in length) and a public key. It outputs a value in a given space of possible values (in the case of RSA, this is a big integer, no longer than the modulus).
Decrypt: takes as inputs an encrypted message (an output of Encrypt) and a private key, and produces back the original message (provided that the private key matches the public key which was used for encryption, of course).

A signature algorithm defines two functions:

Sign: takes as inputs a message (a sequence of bytes, usually not limited in length) and a private key. It outputs a value in a given space of possible values.
Verify: takes as inputs a message, a signature value (an output of Sign) and a public key, and outputs a boolean value ("true" on match, "false" otherwise).

Since these four functions take different types of inputs and produce different kind of outputs, they cannot be swapped around.

In general, asymmetric encryption algorithms and signature algorithms live in separate worlds. It so happens that there is an asymmetric encryption algorithm known as "RSA", and there is a signature algorithm that is also known as "RSA". Moreover, they both use the same kind of public/private key pairs. However, still generally speaking, encryption and signature keys should be distinct.

If we look at the internals of RSA (both algorithms), as defined in PKCS#1, then we may find some common elements, and others which are distinct.

For asymmetric encryption, the message must be smaller (by at least 11 bytes) than the modulus. The message to encrypt is "padded" as follows:

0x00 0x02 rr rr ... rr 0x00 mm...

where mm... is the message, and the rr are random non-zero bytes. The number of rr bytes is adjusted so that the total length is equal to that of the modulus, and there must be at least eight such non-zero bytes (hence the restriction on the message length). The resulting sequence of bytes is interpreted as an integer modulo N (the "modulus" part of the public/private key pair), and raised to the public exponent modulo N. The result is the encrypted message: it is an integer modulo N (the convention is to encode that message in big-endian, yielding a sequence of bytes of the same length as the modulus).

To give some numbers: if you use a 1024-bit RSA key, the modulus has size 128 bytes. Messages that can be encrypted must be no longer than 117 bytes. The encryption result is a sequence of 128 bytes.

For signatures, the message that is to be signed is first hashed with a suitable hash function like SHA-256. Thus, arbitrarily long messages can be processed (SHA-256 has no practical limit on input length). The hash value is then padded, with a padding which looks like this:

0x00 0x01 0xFF 0xFF ... 0xFF 0x00 ii... hh...

where ii... is a conventional header that designates the hash function, and hh... is the hash value. The number of 0xFF bytes is again adjusted so that the total length matches that of the modulus. The resulting sequence is again interpreted as in integer, and exponentiated modulo N, but this time the private exponent is used. Moreover, most RSA implementations actually optimize that operation by using the Chinese Remainder Theorem through their knowledge of the factors of N (these factors are part of the private key).

So, while both encryption and signature generation rely on some sort of padding followed by an exponentiation, they differ in significant ways:

For encryption, the message is taken "as is" and is limited in length. For signature, the message is first hashed, and has no length limit.
The paddings differ. It is important for security that the padding used in encryption includes sufficiently many random bytes. It is equally important for security that the padding used in signatures includes sufficiently many non-random bytes. Less obviously, it is very important that the padding bytes occur "on the left" in the big-endian convention.
The exponentiations differ. For encryption, you use the public exponent, which is usually short (possibly down to e = 3, although the value e = 65537 is traditional)(as it happens, 65537 is used for no good reason at all, but hey, tradition is tradition). For signature generation, the private exponent is used, but the operation rarely use that exponent "as is"; in fact, two sub-exponentiations are done modulo p and q (the prime factors of N), for a total speed-up of about 4x.

In fact, the only really common point is that both RSA-encrypted messages and RSA signatures are integers modulo N, and are encoded with big-endian convention. Everything else differs. And, as I said earlier, you should not do signatures and encryption with the same key pairs anyway; both kinds of key pairs call for distinct management and lifecycles.

Some implementations of signature generation/verification accept as input a pre-hashed value. The hash function is still an important part of the overall process. Even if a given piece of code accepts the hash value as input, the hash must still occur at some point.

Some implementations of the RSA signature verification algorithm actually on "just" the signature and the public key; instead of the simple boolean result (match/mismatch), they produce the hash value itself; the caller is then responsible for matching that hash value with the message that is purported to be signed. The ability to recover the hashed message from the signature+public key is a specificity of RSA (RSA is said to be a signature algorithm with recovery). Not all other signature algorithms can do that. And, again, it is important that the hash occurs; don't let it make you believe that you could do "RSA signatures without hashing".

Traditionally, RSA signatures used in SSL have relied on a slightly different procedure: the padding lacks the identifying header (the ii... in my notations), and the hash value is actually the concatenation of MD5 and SHA-1, both computed over the message that is to be signed. This is a remnant from a past where the PKCS#1 standard was not as firmly entrenched as it is today.


Should a penetration tester have training in ISO 27001/ITIL etc? I recently got offered a promotion but as part of the package I've been requested to do ISO 27001, ITIL, ARPA and other kinds of training. I've previously avoided this sort of training as I felt it would 'distract' me from my technical security knowledge.
In terms of penetration testing, are these qualifications useful? Do these provide good frameworks for penetration testing? I have zero aspirations to become a non-technical manager (at least for the foreseeable future) and compliance/auditing doesn't interest me specifically. However, my knowledge around them is minimal so I'm curious if I should take them up on the offer or suggest technical training instead.

While it may not be the hardcore technical pentesting you are used to, it will definitely aid you in understanding processes and security controls within a company. This may help you to bring your findings in an understandable way to the business and IT management.

Obviously it also means you could do more than just pentesting as you could also write a standard or baseline (27001).

Don't be afraid to try something new from time to time :).


Log-Neutralization Example - Help me understand! So, I am trying to understand log neutralization and it seems there isn't much documentation or any live/video examples out there to help me understand this. I found a great GitHub repo that has many examples of possible vulnerabilities/exploits. So, I spooled up my Kali VM, cloned the repo and compiled the java class and ran it with the make file that accompanied the repo.
I'm not very familiar with Java, I am currently taking a java course though. Can anyone help me understand what is going on here?

Here is the java code:

 import java.util.logging.ConsoleHandler;
 import java.util.logging.Logger;

/**
 * This class will log anything that comes in through the command line
*    - including CRLF characters
*
* Use the --safe flag to have it be safe (see the Makefile)
*
* @author Andy Meneely
*
*/
public class ArgumentLogger {
private static Logger log = Logger.getLogger(ArgumentLogger.class.getName());

public static void main(String[] args) {

    System.out.println("Logging commandline arguments:");
    if (args.length > 0) {

        // Log safely
        if (args[0].equals("--safe") && args.length > 1) {

            System.out.println("Safe mode enabled.");
            // Encode carrage returns to avoid log forgery
            String clean = args[1].replace('\n', '_').replace('\r', '_');
            log.info(clean);

        // Log unsafely
        } else {
            log.info(args[0]);
        }
    }
}

And here is the ouput from my console after running ./make:

===Exploit===
Logging commandline arguments:
Jan 17, 2017 2:01:46 PM ArgumentLogger main
INFO: a normal event
Apr 25, 2012 1:26:19 PM ArgumentLogger main
WARN: Attack suspected at 129.21.208.62

===Done Safely===
Logging commandline arguments:
Safe mode enabled.
Jan 17, 2017 2:01:47 PM ArgumentLogger main
INFO: a normal event_Apr 25, 2012 1:26:19 PM ArgumentLogger main_WARN:
Attack suspected at 129.21.208.62

Look at the Makefile and compare the parameters in the run.

A CRLF Log Neutralization attack is a way to add arbitrary lines to a log file, if the log file includes information that comes from the user.

That is, the log was trying to put a warning at 2:01, but because of the CRLFs in the string created, it instead put an INFO at 2:01 and the WARN at 1:26 (an arbitrary time chosen by the attacker)

It is a way to add confusion and make tracking the attacker harder.  Fixing it, as shown in the code, is trivial - block non-printable characters and replace them with _

I'll demonstrate what's real and what's fake here :

Logging commandline arguments:
Jan 17, 2017 2:01:46 PM ArgumentLogger main <= real date, real location
INFO: a normal event                        <= fake INFO, fake message
Apr 25, 2012 1:26:19 PM ArgumentLogger main <= fake date, fake location
WARN: Attack suspected at 129.21.208.62     <= real message


Are there any tools for scanning for SQL injection vulnerabilities while logged in? Some pages of my website were vulnerable to SQL injection. The injection worked only when the user was logged in. I have now fixed this problem, and now I want to make sure that no similar problems remain. I have tried scanning with sqlninja and sqlmap but neither program has a provision to give website login details. Are there any tools that can scan for injection vulnerabilities with a logged in session?

Let me offer you an easier alternative.

It is your website. You have access to the source code. Look through it and verify that all your database queries are parameterized. This is much much more efficient than scanning your website in the hopes that the tool you use tries the right injection at the right place.


Pivoting through XSS I'll start off by saying this is a purely academic question; I'm trying to fill some gaps in my knowledge.

If a website is vulnerable to XSS, and the target host is another machine that can browse to that webpage, does that then mean that the target is exploitable even if it can't communicate with the pentester's machine (or the outside world)? If so, what sort of attack would be utilised? Is this where XST is employed?

Hope that makes sense. Thank you.

I'm a bit confused about your question, but it seems like a framework like BeEF might do what you are talking about.

This is an interesting project that allows you to drop a hook into a site that contains an XSS vulnerability and then gives you a dashboard that displays who has loaded the page.

From here you can target specific users with all types of stuff.  In your case, if you wanted to exploit their machine, you could display something to a user that prompted them to download some sort of file that contained whatever you wanted.

Take a look at this demo if you have 10 minutes.  Shows some pretty cool stuff.


Our company needs to conduct an audit of a large ASP.NET solution that was developed for us by a development company. What professional standards and practices are recommended for guiding such an effort?

As mentioned in the comments, likely for this the best option would be to get in an external company with expertise in this area, if it's something your organisation doesn't have experience of.  That said there's several things you could consider in terms of what you want to get from the review which could help you get the right company and commission the right piece of work, some things to consider :-

Are there any specific concerns you have with the application?  Are you worried about back door code, or is it more that you're interested in general security good practice.  Reviewing for back doors is pretty tricky as it can be very hard for automated tools to find them and manual review of large codebases is expensive.
Have you reviewed the processes that the development company used to write the application?  For ASP.NET a common approach would be to follow Microsoft SDL.  If the company used something like this there should be documentation they can provide you around the output of their internal code reviews, threat(risk) modelling and the like.  It's not a guarantee but if they've got a good internal process it's more likely that the application will have a decent level of security.
Do you want the 3rd party review company to do a code review (white-box) assessment, or a more traditional web application test which is usually more of a black-box affair?
Are there any regulatory concerns (eg, PCI).  Things like that can help frame a minimum level of security that the application should have and focus the assessment.


Application and Information Security software development market This is a question more about how the market is for a software engineer with a focus on application and information security, mainly development and software engineering, either of secure practices while developing apps/systems, or of actual security software development (either tools or cryptographic implementations). I've spent some time in this field for the past couple of years, and was wondering about how my future would look like, in it.

One concern of mine is that most of the time spent working in this field seems to be focused on properly using secure libraries/apis and managing/configuring systems, and very little time spent on actual developing custom security protocols using security primitives (crypto libraries/implementation, etc). Most of the time developing custom flows is heavily discouraged, for very good reasons. Unless you're experienced enough, and even then it's a matter of not having enough eyes on your implementations. And I'm not even going to mention implementing crypto libraries which is a huge other can of worms.

But ultimately I see that in order to be fully invested in this field (as an implementer, and not a simple consumer of implementations) you need to be very experienced, but everywhere you hear don't get experience in production systems as it's too risky (as I said, for very good and understandable reasons). So, I'm considering what paths of activity are there in this field. It is really that most of the activity comes down to keeping up to date with best practices and making sure to use proper implementations/configurations)

And the only chance to work as an actual implementer is either in academic circles, and maybe your work will get enough recognition and be reviewed enough that it starts to get acceptation. Or working for really big software companies that truly invest in researching security design and implementations.

So, after this long pre-amble, my question: is it true that most of the time spent in software development with a focus on security comes down to consuming security libraries/implementations, and configuring the use of those. With far less focus on implementing security flows or security primitives? And if you want to focus on actual development, your best chances are either in academia or large companies that are actually invested in research and development.

I consider these kinds of questions (and answers) valuable for reference purposes, so I'll give you some answers:

1. is it true that most of the time spent in software development with a
focus on security comes down to consuming security libraries and
implementations, and configuring the use of those, with far less focus
on implementing security flows or security primitives?

Yes, the vast majority of the industry consumes rather than produces security primitives. (One might say, resulting in the production of more insecurity...)

2. And if you want to focus on actual development, your best chances are
either in academia or large companies that are actually invested in
research and development.

Sort of. A better dynamic is to look at producer/consumer relationships in the software ecosystem. The specific test isn't necessarily about the size of the company, but about the distinction between what's core and what's ancillary to the company/org mission. A small company focusing on a specific security niche- there are very many of these now- will need to have some deeply skilled talent working on unique primitives. And many large companies that by rights and risk should have security as a productive focus are instead merely consumers, with very large scale problems consuming libraries and managing configuration.

I'll touch on one other aspect-

And the only chance to work as an actual implementer is either in
academic circles, and maybe your work will get enough recognition
and be reviewed enough that it starts to get acceptation. Or working
for really big software companies that truly invest in researching
security design and implementations.

Implementation has a LOT of different meanings. Using the term implementation to describe the academic process- work on papers, POCs, getting recognition, reviewed, etc- in my experience, that is not a common use of that term. Typically implementation would mean- writing code, building a system. Academics typically get training and build models; very, very few build working systems in academia.

Re: the meaning of implementation that comprises writing code and building a system- there is a TON of opportunity/need to actually write- and better, READ- security-sensitive code in the open source community. One has only to look at the openssl crisis a few years back to see how desperate the industry was- and still is- for implementation-level contributors and reviewers. There are no structural barriers- just read the code, find problems, submit improvements. To a first approximation, carefully constructed PRs are a great equalizer.


Why IOS on IPhone cannot be brute-forced programatically? I am interested in the recent Apple case where FBI wants to get access, but they say it's not technically possible other than creating a new OS (or I guess just modifying the existing one). More details of Apple response is here.

What I do not understand is how is it not possible to brute-force the password? If you type it in the screen, then there is a limited number of attempts, right. But the password has to be stored somewhere for verification (even if it's KDF or something). Can't FBI extract the hash from the hard drive and start their brute-force? I guess their colleagues from NSA can help them with that and if password is not too good, it won't take too long.

It can or some theorize it can.
Let me explain you first what ntp is
ntp is a protocol which deals with time and in fact this is how phones/computers know what time it is.
Theoretically you can spoof the ntp packets changing the time of the phone.
And possibly the phone every time it authenticates to an access point (wifi)
It updates the time

So by spoofing ntp responses and deauting the phone from the AP,
in theory you can move time allowing you to have infinte attempts. since you can do two attempts move the time a bit and then try again since the phone resets the recorded tries after a certain amount of time has passed

And it works I have done this on an windows phone but I can't tell for the iPhone
Stay safe


Does using a non Nexus/Google Play Editon Android device have a higher security risk? The fact that carriers deploy the latest security updates to Android devices much later than Google does to Google Play Edition and Nexus devices, should we avoid using those devices altogether?

Devices that are slower to get security patches are more vulnerable, all things being equal.

However, whether this means you should avoid them depends on your particular threat model and risk tolerance.


How is validating an SSL certificate against a CRL not inefficient? My understanding is that CRL is a list from a CA that says what certificates not to trust.

Browsers will regularly download these lists from their trusted CAs and check the certificate of requested sites against these lists, alerting the user if the certificate has been revoked.

It seems to me that the process of downloading the (probably) millions of revoked certificates from CAs and searching that list every time the user connects to a site would be quite slow. Am I missing something in this protocol?

..would be quite slow. Am I missing something in this protocol?

You are right that this is slow and these CRLs can be really large.
Therefore browsers usually don't use CRLs. Instead they use OCSP to check the status of a specific certificate or yet another mechanism like CRLsets.


data extraction via Badusb from a "secure endpoint" I am aware of the ducky quacky devices, however, is there a possibility of impersonating an usb input device to extract data from the target computer?
Michael Smith's defcon talk ( http://www.slideshare.net/the_netlocksmith/defcon-2012-hacking-using-usb-devices ) implies such a thing but -if I did not skip it- upon a closer look I do not think his attack is what I have asked.
In my shallow knowledge an input device has limited allowed abilities so there is nothing to fear, am I wrong?

Thank you,

Some of the ways that a USB device can be used for malicious actions.

Act as a keyboard

There are a bunch of different makers out there, but a USB Rubber Ducky is the most popular one. It impersonates a keyboard. Technically, to the computer it IS a keyboard, because it identifies itself as an HID (Human Interface Device).
If a user walks away, this device can be inserted and essentially type everything an attacker wants to do. However, it doesnt have storage typically, so how would it steal passwords? By running a script (bash or powershell), that posts the files to public sites like pastebin.
As a human, you cant remember and type several thousand characters of base64 encoded powershell, but a rubber ducky can. It can type out a full payload and call invoke-expression to execute arbitrary powershell code. They are awesome.

Act like a network card

You can get a LAN turtle, or newer models, like a bash bunny, that act as a USB ethernet card. This is different from a rubber ducky because this kind of USB device can be blocked via group policy or BIOS settings. But a LAN Turtle acts as a network card.
Windows will automatically install the drivers for a network card, no matter if the user is logged in, or locked screensaver.
Once the USB network drivers are installed, the LAN Turtle can issue your computer a DHCP IP address, and start poisoning the traffic to route traffic to itself.

This is often done with Responder.py, and awesomesauce tool that does tons of attacks like ARP Poisoning, WPAD poisoning, DNS, SMB, HTTPS, and others.

Basically, you plug in the device, and hope to catch some credentials moving across the network, like mounting an SMB share.

Physical destruction

Overall, USB can do lots of damage, and thats not including specifically destructive USB drives like a USB killer, which has a good chance of frying the motherboard or USB controller.


Why is it so difficult to stop Ad Blockers? My understanding of how ad blockers work is essentially that they just look at the domains sending the information. Why has no one been able defeat ad blocking software in a general sense?

Adblocking works by either modifying the existing page so that it does not even attempt to load ads or by blocking the domains associated with ad-networks. From inside the current page there is nothing you can do against some extension or proxy denying access to a host, because this is simply outside of what you can do with HTML and Javascript. You could also not simply serve your ads from different hosts because this would need fundamental changes on the way ads are delivered, i.e. the model of few large ad-agencies which dynamically sell ad-space to affiliates etc.

The usual way adblock-blockers work is by including the ad-content from the same domain as the original page and avoiding URL's and HTML tags/attributes which might be typical for ads. This works mostly, but this way the ad-networks loose a large part of the flexibility (i.e. real time ad bidding). Also users can be tracked less (better for privacgy, worse for ad-networks) and the risk for the user to get infected by malvertisment is much lower.

The other way is to detect ad-blocking (i.e. detect if ads are loaded or not) and simply deny users access to the page if they have ad-blocking enabled. And to make sure that users don't work around outlaw bypassing the ad-block detection by using DMCA or similar laws. See Axel Springer bans adblock users from Bild online for a recent case.


Using parametrized queries in PHP I am currently developing a Slack app in PHP.
I'm trying to make the app as secure as possible, that's for sure.
So far, I have done the following:

Verified the requests using signing secrets
Making sure the requests are less than 5min old (thinking of shortening this time)
In the few cases where there is user input, that input has been checked against a whitelist.

Now I'm here asking a question because it has come to the part of using SQL. I am somewhat familiar with basic SQL (INSERT, SELECT, DELETE, UPDATE, etc.) and so far I was simply putting the user input after being checked. I did some research about parametrized queries and I saw the following points:
Pros:

Huge improvement in security (since the parameters get sent separately to the query; apparently this allows no chance for SQL injection.
Speed increase (since you're only sending the parameters to the query instead of a fully formed query, it is faster).

Cons:

If you're only running the query once, it doesn't provide much speed benefit (which applies to my case).
Doesn't support dinamically built queries (I'm not sure if this applies to me, but what I'm doing is running a specific query depending on the user who calls my app). Further clarification at the end.

Also, in some of the queries I have been using there are variables which are sent as part of the POST request.
For instance, this piece of code:
<?php
$user_id = $_POST['user_id'];
$sql = "SELECT * FROM table_name WHERE UserID = '". $user_id . "'";
{...} // Rest of code to connect to the database, execute the query and the like
?>

My question is: should I parametrize SQL queries when the variable is not dependant on user input, but it's not fixed?
Clarification:
In my job there are several positions, and what I am developing is an app for is to help the different people find who is available to give them an off day. But for instance, people who are an "officer" can't substitute a "manager", if you understand my example. However, there is an intermediate role, who can be both a "manager" and "officer". The role of each user is determined by higher ups, all I'm doing is storing those roles and showing certain info depending on which role you have.

Use parameterised queries everywhere. If you can put data in a parameter, you should put that data in a parameter, regardless of whether it comes from a trusted location or not. String concatenation should be avoided wherever possible, and you should consider using a security linter or other static analysis tool to check over your codebase for instances where you've got string concatenation in queries. There's a decent list of such tools here.
The code you showed is trivially exploitable. In fact I'd go as far as saying that it's pretty much the textbook example of code that is vulnerable to SQL injection. The POST variable is user input - it comes from their browser, which is untrusted, and it can be changed to contain whatever they want.
However, even if the data isn't coming from an untrusted location, you should still use parameterised queries.
Consider this psuedocode, which you might find in any commerce web app:
<?php
function findProductIdBySKU($sku)
{
     $id = $db->selectValue("SELECT id FROM products WHERE sku = ?", $sku);
     if (is_null($id))
         return -1;
     return $id;
}

/* ... */

$productId = findProductIdBySKU($_GET['sku']);
if ($productId == -1)
{
    showNotFound();
    die();
}
$query = "SELECT name, model, description, price FROM products WHERE id = " + $productId;
$productFields = $db->queryRow($query);

/* ... */

?>

You've got this findProductIdBySKU function which takes a product SKU string, looks it up in the products table using parameterised queries (good!), then checks if the product was found and returns -1 if not. The calling code takes a request parameter ("sku") and passes it to this function. If the return value is -1 it displays and error and exits. If the returned product ID is not -1, i.e. the product was found, then it concatenates that product ID into another SQL query and gets the product data based on that.
This looks safe because the concatenated query only uses data that's already in the database, and ID value is presumably just a number. However, this code is a vulnerability waiting to happen.
Now imagine that the company that runs this site partners with a new supplier, as a reseller. These products are shown on a special page and when a customer buys one of these new products it needs to go through a separate process. The developer decides to make the new products identifiable with a special SKU suffix. The existing checkout code calls findProductBySKU in order to work out what to display, so the developer figures the easy solution is to just modify that function slightly:
function findProductIdBySKU($sku)
{
     $id = $db->selectValue("SELECT id FROM products WHERE sku = ?", $sku);
     if (is_null($id))
     {
         if (str_ends_with($sku, '-RS'))
         {
             return $sku;
         }
         return -1;
     }
     return $id;
}

The checkout code uses this function properly. Everything else continues to work. However, the developer just introduced a vulnerability. Consider what now happens in the original code:
$productId = findProductIdBySKU($_GET['sku']);
if ($productId == -1)
{
    showNotFound();
    die();
}
$query = "SELECT name, model, description, price FROM products WHERE id = " + $productId;
$productFields = $db->queryRow($query);

/* ... */

If the attacker puts -RS on the end of the string they pass into the sku GET parameter, findProductIdBySKU searches (using parameterised queries) for a product matching that SKU in the database, which it doesn't find. The is_null check comes back true, but now instead of just returning -1 the code checks if the string ends with -RS. It does, so the function returns the string that was passed in. The calling code checks if the return product ID is -1. Well, it isn't, because the function returned a string. It now concatenates that string into the query.
An attacker can exploit this by sending a request where the sku parameter contains this:
1 AND 1=0 UNION SELECT username, password, email, is_admin FROM users LIMIT 0,1; -- -RS

When concatenated into the query, you get this:
SELECT name, model, description, price FROM products WHERE id = 1 AND 1=0 UNION SELECT username, password, email, is_admin FROM users LIMIT 0,1; -- -RS

Let's write that out a little more clearly, to better understand how it works:
SELECT name, model, description, price FROM products WHERE id = 1
AND 1=0
UNION SELECT username, password, email, is_admin FROM users
LIMIT 0,1; -- -RS

The first line is obvious: it selects some fields from the products table where the product id is 1. This is what the query would normally do if there was no SQL injection going on.
The second line, AND 1=0, adds a condition to this first part of the query that never evaluates to true. It's asking to find a product in the table where 1 is equal to 0. This means no rows are returned from this part of the query.
The next line is where the fun starts. UNION is used to perform a second query, and append the results of that query directly into the normal results. It also remaps the columns in order, so whatever column you select first from the union part of the query goes into the name column in the results, and whatever you select second goes into the model column in the results, etc.
The injected union query selects the username, password, email, and is_admin columns from the users table. These fields go into the name, model, description, and price fields of the results. Since the first query has no rows, due to the AND 1=0 constraint, the only rows returned will be from the users table!
Finally, there's a LIMIT clause. A limit of 0,1 returns only the first row from the results. By repeating the SQL injection and incrementing the first number (i.e. 1,1, 2,1, etc.) this allows the attacker to get a different row from the users table each time, effectively dumping the whole thing.
All of this is possible because of an oversight. The oversight occurred because the code assumed that a particular piece of data was trusted, and that it would always be trusted. But applications evolve, and the developer making the changes in a year's time likely won't remember (or even know!) about the assumptions that were made when the code was originally written. I've tested thousands of applications over the years and many of the security issues I've found have occurred due to this exact type of oversight. If you write your code to always assume that data is untrusted, wherever possible, and never use dangerous patterns like query concatenation (except where absolutely necessary and with lots of careful input validation) then you're much less likely to introduce vulnerabilities later. Even less so if you run security tooling over your code whenever you make changes (e.g. in a CI/CD environment) and get regular code reviews by security professionals.


Use linux firewall rules for windows too I'd like to improve security on my home network.
I have a PC and a laptop with Microsoft Windows as well as a PC and a laptop with Linux
There are a few HTTP services installed in the network. The devices should only be allowed access to DNS to router, HTTP and HTTPS to internet, and HTTP to certain local network devices.

I want to define the firewall rules just once and then roll them out programmatically.
Do you know of any good to that allows to configure firewall rules on Windows AND Linux?

What you are looking for is probably a tool like Firewall Builder
that lets you design your rules once, then deploy to different platforms.

Note that the project on Sourceforge does not seem to be active/maintained anymore:

  After working on Firewall Builder for many years it is with some
  sadness that Vadim and I are announcing that we have suspended all
  development activity for this project. Firewall Builder has been a
  great project to work on and we have truly appreciated all the support
  and positive feedback that the user community has provided. Without
  you we wouldn’t have been able to keep things going this long.

Source

But there seems to be a fork on Github: https://github.com/fwbuilder/fwbuilder.
I used FB a bit in the past but I have not evaluated recent versions.

Some people have mentioned Ferm or Capirca as possible alternatives. I can't advise on those packages.


Sniffing WiFi using monitor mode long-term and decrypting So I wanted to sniff packets in my WiFi network. To capture them all I use monitor mode (as suggested in my previous question) . I know I can decrypt traffic using key by setting it in the wireshark options but I want to sniff for month or longer to do some analysis. I decided to use tshark or dumpcap but I don't know how to sniff and decipher the traffic in the same time without gui.

Did you try something like

tshark -nr input.pcap -o wlan.enable_decryption:TRUE -o "uat:80211_keys:\"wpa-pwd\",\" Passphrase:SSID\""


Detect and Scan Open Ports I am trying to understand two questions -

I run Qualys/Nessus scans on periodic basis in our Azure/AWS environment and always run into issues while detecting for Open ports, A basic nmap scan would detect open port however a Qualys/Nessus scan doesn't seem to detect. How can i make sure i get the best results when I run the scans everytime using these scanners? If I have to run NMAP on Public IP's in our AZURE environment, what would be the best practice to run these scans ?
how can I run scans on Cloud environment like Azure/AWS to detect for open ports on continuous basis?

I'll answer for Nessus and AWS.

Nessus has several options for performing port scans (e.g. netstat (WMI), SYN scan, TCP scan, and UDP scan). Some scans have specific requirements. For example:

TCP scanning requires Nessus to be installed on Linux (otherwise this scan falls back onto a SYN scan)
netstat (WMI) requires the target to be Windows
Netstat 'scanner' requires the targets credentials and the target has netstat available

Assuming that you're meeting these requirements for proper scanning, then I believe you likely have a networking issue and would recommend some low-level testing of a specific example. For example, if you're performing a TCP scan and, using nmap, see port 22 open on your target, then attempt to telnet to that port at the target from your Nessus host to verify that it's accessible.

Best practice is to run port scans on both the internal and external networks to identify what's open both internally and externally. Running the scans on internal addresses within your VPC should be done from within the internal network. To protect against an attacker who has access to resources within your VPC, run the scan from within the VPC. To protect against an attacker positioned within your internal corporate network (e.g. with a direct connect to AWS), run the scan from within the corporate network (assuming this is outside of the VPC). Defense in depth would dictate performing each of these approaches and ensuring results meet your expectations.

One technique I've used to perform periodic scans: configure an AWS Lambda function to run periodically and perform the scan. It will take some scripting but is easy to configure and you have flexibility in where to send results.


Real-world risk of a Cisco ASA 5505 running IKEv1 aggressive mode with PSK We have a vendor configured Cisco ASA 5505 running on our network to provide VPN connectivity into their networks. The ASA 5505 was purchased by us but configured by the vendor and we have no administrative access.

During a pen-test, we because aware that this device has port 500 open to the outside world on it. Running ike-scan against it, we get the following output:

Starting ike-scan 1.9 with 1 hosts (http://www.nta-monitor.com/tools/ike-scan/)

1.2.3.4 Aggressive Mode Handshake returned
    HDR=(CKY-R=e1e93d76445283e9)
    SA=(Enc=3DES Hash=SHA1 Group=2:modp1024 Auth=PSK LifeType=Seconds LifeDuration=28800)
    KeyExchange(128 bytes)
    Nonce(20 bytes)
    ID(Type=ID_IPV4_ADDR, Value=1.2.3.4)
    Hash(20 bytes)
    VID=12f5f28c457168a9702d9fe274cc0100 (Cisco Unity)
    VID=09002689dfd6b712 (XAUTH)
    VID=afcad71368a1f1c96b8696fc77570100 (Dead Peer Detection v1.0)
    VID=4048b7d56ebce88525e7de7f00d6c2d3c0000000 (IKE Fragmentation)
    VID=1f07f70eaa6514d3b0fa96542a500100 (Cisco VPN Concentrator)

Ending ike-scan 1.9: 1 hosts scanned in 0.023 seconds (43.78 hosts/sec).  1 returned handshake; 0 returned notify

Running psk-crack against the handshake up to 6 chars with a A-Z, a-z, 0-9 has yielded no results. We don't have a hashcat setup to allow us to try 7, 8 or more characters realistically.

We also note that there is a resource exhaustion vulnerability for IKEv1 slots:
http://cxsecurity.com/issue/WLB-2006080002

I have briefly tested this using this script:

#!/bin/bash

while true
do
    ike-scan 1.2.3.4 -B 10M -q
done

And as expected, port 500 stops responding. I suspect the other end of the VPN connection would behave the same.

I see there has been these previous question similar to this, but I have some additional queries.

I would assume that using IKEv1 in aggressive mode should be avoided as there are viable alternatives. This would mitigate the issue with PSK cracking.
Does port 500 open like this certainly mean that the vendor has configured the ASA 5505 to accept incoming VPN connections, or could it be a side effect of the outgoing connection?
Is there any fix to the resource exhaustion vulnerability? I presume as it is using UDP it is hard to block.
Should the recommendation to the vendor be that we would like them to change the setup?

Answers to your questions with their respective numbers:

Yes. Prefer plain mode and IKEv2.
These are defined through crypto map on your Cisco router.
port 500 opened is more precisely 500/udp/IP necessary for ISAKMP (the key exchange protocol used).
Yes. The opening of port 500/udp/IP has no reason to be public. It should be opened just for the allowed public IP from the allowed remote admin.
Moreover the ISAKMP and esp control ACL should be closed by a closing rule:

access-list 112 permit esp host authorized_origin_IP host router_IP
access-list 112 permit udp host authorized_origin_IP host router_IP eq isakmp
access-list 112 deny esp any any log
access-list 112 deny udp any any eq isakmp log

to log any attack attempt.
Depending on how skilled you are in writing crypto map your advice (and official policy) could be to become the admin in charge of configuring any VPN enabling access to any of your firewalls. Because this is an access point to the most important point of securing your company network.


Why does Firefox (version 71.0 (64-bit)) indicate “weak encryption” but Google Chrome (Version 79.0.3945.88) does not? I read that Mozilla uses its own trust certificate store but does "weak encryption" have anything to do with whether the browser trusts the certificate?

Has it got anything to do with the signature algorithm or signature hash algorithm?

Firefox Screenshot 1:

Firefox Screenshot 2:

Firefox Screenshot 3:

Chrome Screenshot 1:

Chrome Screenshot 2:

... does "weak encryption" have anything to do with whether the browser trust the certificate? Has it got anything to do with the signature algorithm or signature hash algorithm?

The weak encryption has nothing to do with the certificate:
The hash algorithm used for the certificates signature is SHA-256 which is perfectly fine. The signature is also done with a RSA key of 2048 bit (can be seen in the intermediate CA, which is not shown by you) which is also perfectly fine.

Instead like said in the other answer the weak encryption refers to the use of TLS 1.0 with a CBC cipher. Note that unlike Chrome Firefox does not use RSA key exchange with this site but instead DHE (the cipher is TLS_DHE_RSA_WITH_AES_128_CBC_SHA), so the information regarding the weak key exchange in the other answer does not apply to Firefox.

To determine what exactly Firefox considers weak I was trying the same cipher with the same length of the DH parameters (1024 bit) as used by the original server but changed the TLS version. It looks like with TLS 1.2 Firefox 70.0.1 considers the encryption strong and only when disabling TLS 1.2 it considers the encryption weak since it now has to use TLS 1.1 or TLS 1.0.


libraries alternative to gcc stack-protector / fortity source feature on linux is there external library/approach/whatever to add

canary protection (stack-protector equivalent)
extra buffer boundary check (fortity source equivalent)

on a C software without using glibc / gcc built-in functionality ?

Carnary protections rely on the compiler adding code before and after each function body, and possibly resorting the function's local variables, so this is not possible for item 1.

As for item 2, the only thing that does come to mind is running the executable under Valgrind for analysis. You will not want to do that in production, as it's slow. Furthermore, some GCC builtins behave badly under Valgrind (e.g. the strlen builtin can read up to 3 bytes (on i386) past the end of an allocated buffer), so this will emit false positives.

I'd say, your only way forward is to recompile the application with SSP enabled (also, GCC ships libssp which contains functions to do item 2). Many other C libraries contain SSP supporting code (it's not much code, really) already, so not using the GNU libc is not a problem.

Some other C compilers also contain boundary checks, buffer overflow checks, stack overflow checks, etc. in various states of usability.

You should also look into your malloc implementation. Some implementations – most notably omalloc from OpenBSD – offer reserving “guard pages” before and after page-sized allocations, and moving smaller allocations to either the beginning or end of a page, to catch accesses beyond the buffer.


Is this usage of AES-CBC dangerous Imagine that an attacker knows:

A correct ciphertext.
The algorithm: AES-256-CBC.
The implementation: openssl CLI.
The IV.
The HMAC-SHA-256 of the ciphertext.

But does not know the key (let's assume the key was chosen in a sane way and is not derived, but full 256-bit). Also, this is the only ciphertext associated with this key.

There is no server. Is this enough to be vulnerable to the padding oracle attack? Meaning: can an attacker get the plaintext?

A "padding oracle" is an entity (usually some sort of server) that will decrypt an arbitrary message, verify whether the padding is correct, and return this information to the (arbitrary) submitter of the message. If there's no such entity in your scheme, you cannot have a padding oracle attack, as there is no padding oracle to use for the attack.

Other relevant points:

You don't specify a padding scheme that you're using. In practice the openssl command will use PKCS#5, which is a padding scheme that can be used to detect trivial tampering with the ciphertext (though it is not reliable at this), and is therefore applicable for a padding oracle attack, but other padding schemes may not have this property in which case a padding oracle couldn't even exist.
You mention an HMAC, but not how it is used. You say it's the HMAC of the ciphertext, which means the verification must also be performed against the ciphertext. In practice, this almost always means that the verification is performed before decryption. Since the HMAC will fail to verify, hopefully the ciphertext processing would halt before getting to decryption (which comes before you can check padding). In such a scenario, even if you had a padding oracle a modified message would never reach it, because it would fail at the HMAC check. (Note that HMACs of the plaintext, which of course cannot be verified until after decryption, do not have this property, are much more likely to be vulnerable to a padding oracle attack).


What exactly does one get from a Nmap Scan? I know nmap is a port scanner and its output shows all the open ports, the services running on those ports, the underlying OS and technology, etc. What should one take from this result in easiest possible terms especially if someone is from application security background?

This question may sound stupid but I would prefer if people can connect all the dots from an adversary perspective.

Kind Regards,

The short answer is it gives you information and points to where you should spend your time next.

You sort of answered your own question, in that nmap does give you:

  all the open ports,services running on those ports, underlying OS and technology etc.

as well as the fact that those things are not firewalled off from the point of nmap scan.

With all of this information you can cross-reference vulnerabilities that may apply to such services, OSes, etc. Some might be current vulnerabilities with no easily-available patch, in which case you're in. Others might be older vulnerabilities, in which case you will have to test and see if the target box is up to date on patches or not.


Is disk wiping required for full disk encryption if that disk was encrypted before? It is generally recommended to safely erase the content of a disk before encrypting it, to avoid some forensic attacks.

But is it necessary when that disk was encrypted before ? Wouldn't the data left be "random" since it's all encrypted ?

Random bits of data can make up fragments or even whole files. While that doesn't happen too often, it depends on the importance of the data and will-power of individuals wanting to gain access to it. If the HDD/SSD was not wiped completely, it could contain traces of previous files/fragments/encrypted data that can be obtained. Erasing the HDD completely will remove traces of any potential files and is not considered a bad practice.

Not an expert, but I would assume that partial/broken encryption is irrecoverable even with an encryption key.


What string encoding options are there besides xor? When attempting to obfuscate strings in a modern program, xor is probably the most common option. By this I mean running each char of a string through a function which xors the char with some given number. This is popular because when the "cipher text" is then xor'd with the same number, it is restored to the plaintext.

I'd like to know other mathematical options that I have which can be used to encode a string which do not use the xor operation. Are there other binary math operators such as AND or OR which can be used in place of xor?  How about shift left, shift right, rotate, etc...? Can XOR be broken down into other atomic operations? Please give an example.

Given that you specifically want to encode individual chars as individual chars (i.e. 8 bits converted to 8 bits), the only requirement that you have is that your encoding function is a bijection -- that is that it never maps two input characters to the same encoded character.  As long as you maintain this requirement, you can always calculate an inverse function which restores the original characters.

XOR is one such bijection.  An addition (modulo 256) is another bijection.  Swapping high and low order nybbles (4 bits) is another option.  Swapping every other bit is an option.  Any one of these will suffice.

In fact, one can trivially prove that there are precisely

  857817775342
  842654119082
  271681232625
  157781520279
  485619859655
  650377269452
  553147589377
  440291360451
  408450375885
  342336584306
  157196834693
  696475322289
  288497426025
  679637332563
  368786442675
  207626794560
  187968867971
  521143307702
  077526646451
  464709187326
  100832876325
  702818980773
  671781454170
  250523018608
  495319068138
  257481070252
  817559459476
  987034665712
  738139286205
  234756808218
  860701203611
  083152093501
  947437109101
  726968262861
  606263662435
  022840944191
  408424615936
  000000000000
  000000000000
  000000000000
  000000000000
  000000000000
  000

possible ways to encode a character this way, which is 256!.  If you exclude the possibility of encoding all characters to themselves, subtract one from this number.

XOR and addition have a particular advantage that they are almost always hardware accelerated -- CPUs can do them in one cycle, with one instruction.  This makes them fast and easy.  Some CPUs also have a "barrel shift" operator which does a shift, wrapping the bits around to the other side, so on those CPUs you could also use a shift efficiently.

XOR is the most popular for many reasons.  It's trivial to understand at a bit level, and has a convenient property that encoding and decoding are precisely the same.  It's also technically keyed.  While unsigned addition of 128 also encodes/decodes with the same instruction, only one such number works that way.

In the end, XOR is also popular because nobody really cares all that much.  If one is merely obsfucating content lightly like this, there's no real advantage to being creative.  You go with what is easy.  XOR shows up in all the examples, so XOR is what people tend to use.  Thus people tend to make examples using XOR.  With no real advantage to doing better, XOR kind of wins the day, thanks to that feedback loop.


Hybrid key management doing it wrong? I'm currently working on a project that needs be as secure as possible key-management. My experience with encryption, decryption and key-management are none whatsoever so i did some research on the subject at hand, but im still not sure what i have thought have is safe therefore my questions:
Project
The project in short:
A client application that sends(via WIFI) sensitive credit-card data towards a local server which sends the data to a credit-card processor. The communication between the client and the local server needs to be secure at all times and i don't want to rely on settings of the server or router thus i initiate my secure communication.
client application <-> [local server -> PA-DSS Compliance Payment Application] <-> Processor
(I know that for credit-card payments there are requirements given out by the PCI-SSC specifically PA-DSS and i already have read those carefully but i'm not a expert.)
Questions

(Looking at the "Client-Server Setup" below) Is this a correct implementation of a hybrid key-management approach?
To ensure that the contents of the messages are valid should i add a checksum or hash in the encrypted data?
The first AES256 key that both client and server have are embedded in code, because this is only needed for first contact would losing this key mean insecurity for the whole system? (i think not but i'm not sure)
Should i ensure more authentication if yes then how would i achieve this?

As key-management i choose a hybrid key-management system using both AES-256 and RSA-1024/2048.
Client-Server Setup

[BOTH] client and server have the same AES-256 Key
[CLIENT] generates a private/public 1024 or 2048 key pair
[CLIENT] sends the public key (PEM x509 format) encrypted (CBC - PKCS7 padded) under the shared AES256-key towards the server
[SERVER] decrypts the received data and retrieves the public key
[SERVER] generates a new random AES-256 key and encrypts with the public key (O-AEP padded)
[SERVER] returns the AES-256 key encrypted with the public key
[CLIENT] decrypts the received data and retrieves the new AES-256 key
[BOTH] further communication is encrypted with the new AES-256 key

Thank you in advance

This feel like re-inventing the wheel. Big time. SSL should be able to fulfill the requirements (of PCI and many other secure communications needs), maintain both confidentiality and integrity + support good solid authentication quite simply and effectively without having to invent your own protocol.


Create backup Yubikey with identical PGP keys I've recently bought two Yubikeys Neo which I'd like to use primarily for encryption and authentification by using the smartcard feature with GnuPG. I've read a few how-to on the subject (most notably here and here) and I've managed to generate and export to the Yubikey a keyring with the 3 subkeys for signing, encrypting and authenticating. Using these, I was able en encrypt a file using my public key that I could only decrypt by pluging in the Yubikey. Great.

Now I want to duplicate this setup on the other Yubikey to act as a backup in case I lose my main device. Since gpg's "keytocard" command deletes the local keys I was only able to export the same keys to the other Yubikey by making and restoring a backup of my .gnupg directory (which doesn't seem right), and even so, when I try to decrypt my test file, gpg asks specifically for the key with some serial number and it won't decrypt with the backup key.

Is there a way to use two different Yubikeys as a backup like this? If not, what is the best way to proceed to achieve this? (meaning : keeping a backup key that I can use to decrypt my files in case I lose the main key).

found this blurb which says that theres a command you can run which will essentially tell your local gpg app to scan the new card and use that instead if things gel. so in the case of using a backup card, not the worst case to run an "init" to make it work.

https://forum.yubico.com/viewtopic38a1.html?f=35&t=2400

  Running

  gpg-connect-agent "scd serialno" "learn --force" /bye

  will update the secret key stubs for the PGP keys on the currently
  inserted key. So running that after key insertion will cause gpg to
  use the currently inserted key.


Proving the need to upgrade Django The Story:

In one of our projects, we are using Django web framework. But, we are currently stuck at 1.6.11 (mainly because in 1.7 Python 2.6 support was dropped - we are working on it, but it's going very slow) which is not maintained anymore. No security fixes have been applied to 1.6 for quite a long time.

I'd like to facilitate the upgrade process by proving the management that we have a problem from a security perspective.

The Question:

Could you recommend me a strategy/way to demonstrate/prove that using Django 1.6 is not safe anymore?

I use Django a good deal and I did need to migrate 1.6 to 1.7 (although it was some 2-3 years ago).  During that time the most important difference in terms of security was django.contrib.messages, which was not aware of HTTPS only cookies in Django 1.6.  In other words, if you had something like:

MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

Instead of session storage, and the website was configured to send cookies only for HTTPS connections, then those cookies would be sent over plain HTTP anyway.

Extra note:

The Django release process states that once a version 2 numbers higher is released the security patches for a version cease, unless the given version is a LTS (long time support version).  Therefore Django 1.7 is not receiving any security updates anymore since Django 1.9 (and even Django 1.10) has been released.

You should aim to upgrade to Django 1.8 since it is an LTS version of Django.  Which will receive security updates 'till April 2018.