Where to store refresh token if not in local storage? In general it's recommended not to store refresh tokens in local storage. The Auth0 documentation advises against it.

Even though I am aware of the underlying threats, what I am not aware is if there are any alternatives as to how to store those tokens in order to have persistence within the duration of a user's session when the API server is different than the client. If the tokens are only stored in memory, then the user will have to login every time he closes a tab for example and later on visits the site again.

Finally, I think anyway the refresh token rotation would mitigate the risk of having the tokens stolen. So in the lights of that, the above recommendation doesn't look very valid.

Storing the refresh and access token is in JavaScript memory is generally considered much better than cookies or other browser storage.

You still don't need to worry about asking the user to login every time. The authorisation server (Auth0 in your case) maintains its own session (SSO Session) behind the scenes which is persistent. So it survives even if the user closes the browser.

This means that even if you have "lost" the refresh token stored in memory (e.g. if the user closes the tab), you just need to re-run the authorisation code flow to get new refresh and access tokens (i.e. redirect the user to the authorisation server). This should be silent to the user (i.e. they won't see the login screen) because of the same SSO session that is maintained by the authorisation server would still be active.


John the ripper not displaying cracked password When using john to crack Windows LM hashes it says it has cracked the passwords but does not display anything. See image below.

https://imgur.com/SnltTPK

You're not seeing them because they're invisible. :)

aad3b435b51404eeaad3b435b51404ee (LM) and 31d6cfe0d16ae931b73c59d7e0c089c0 (NTLM) correspond to an empty password.

This blog post explains in a little more detail, with command line examples to show how an empty password is hashed.


Android N - Security Crypto Provider is deprecated As mentioned in "android developer's blog" , http://android-developers.blogspot.in/2016/06/security-crypto-provider-deprecated-in.html , security Crypto provider is deprecated on Android N. And also they will remove "Crypto" provider from the SDK also.

  Note 1: as a temporary measure to keep apps working, we decided to still create the instance for apps targeting SDK version 23, the SDK version for Marshmallow, or less. Please don't rely on the presence of the Crypto provider in the Android SDK, our plan is to delete it completely in the future.

My question is are they talking about whole javax.crypto package ?

Currently my application is using following imports :

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

Do I need to remove these all ? I have tried to build this application using API version 24 and it is not showing any error msg.

My question is are they talking about whole javax.crypto package ?

No. They are referring to the Crypto provider for javax.crypto.

  Do I need to remove these all ?

No. So long as you did not manually specify to use the Crypto provider, you are fine. Search your code for the string "Crypto" (with a capital C).


Determine private key size using public certificate I have a public certificate in a PEM (.pem) file

-----BEGIN CERTIFICATE-----
MIICsjCCAZqgAwIBAgIJAMA1YIQ2JLXDMA0GCSqGSIb3DQEBBQUAMBExDzANBgNV
             ...
29V/R9RZOoSBHDzGPL84wm4qojMuwQ==
-----END CERTIFICATE-----

Its total size is 942 characters.

Now I would want to deduce from it the size of private key and asymmetric generation system. Is this possible ?

The public and private key have the same size (with regards to security, the file size differs of course). It's identical to the size of the modulus when it is regarded as an unsigned integer (and the key size is a full number of bytes, i.e. a multiple of 8 - otherwise it is the location of the highest bit set to one).

You are however showing a full X509 certificate. That certificate contains the public key. You can easily view the public/private key size by typing:

openssl x509 -text -noout -in [yourcert]

It will contain lines with:

Subject Public Key Info:
    Public Key Algorithm: rsaEncryption
        Public-Key: (2048 bit)

Where [yourcert] is the file containing the certificate and the value 2048 is an example. Note that rsaEncryption may be used to indicate signature generation as well.


Is there cryptographic material in a phone's SIM card that can be used with RSA encryption? Given that a smart card stores a private key that can't be extracted, it appears that a SIM card is similar to a smart card in these respects.

I need to store (or use an existing) private key on a phone and use that to decrypt data sent from a webservice.  I also want the private key store to have the following properties

Can't be easily cloned (difficulty level is subjective)
The private key is available to the programmer for use (Objective C, Java, Javascript, etc)
The private key can't be extracted, and is protected by a hardware means

Is such a facility available in any phone from any manufacturer?

A SIM card is a smart card. It follows all the relevant standards for smart cards, it is produced by smart card vendors.

A smart card is "just" a tamper-resistant computer. It has its own CPU, RAM, ROM, storage area (often EEPROM). Power and clock are provided from the outside. The device is supposed to be resistant to physical extraction of the internally stored data: it is equipped with a lot of sensors which detect a breach of the outer cover, operations in out-of-range conditions (temperature too low or too high, clock rate departing from the expected frequency...), and, ultimately, should self-destruct if advanced reverse engineering is attempted on it.

Of course, this is all a question of money. Direct inspection with an electron microscope and lasers is said to cost a few thousands of dollars; in past years, it was quite an industry among satellite pay-TV hackers (especially in countries which received the signal from the satellite but could not legally subscribe for lack of a commercial infrastructure -- I saw it happen a lot in North Africa, with European TV). Also, investigation methods for the extraction of secret key from a smart card have been seriously studied by both academics and the industry. Finally, a smart card being a small computer in its own right, it uses software and thus has bugs, some of which being exploitable.

I have recently worked with that kind of product. This is a smart card which can fit in the "SIM format" and yet can store and use dozens of RSA keys. The keys are generated on board, and performance is quite acceptable for many usages (less than 1 second for a 2048-bit RSA signature). The card has been certified to conform to FIPS 140-2 Level 3 and EAL 5+, which are both rather impressive (they don't guarantee that the card is unbreakable, but they demonstrate that the vendor had least invested substantial efforts and money towards that goal).

What I explain above is that it is technologically possible to have a SIM-like card which stores and use asymmetric keys for cryptography, with a resistance to private key extraction which is not negligible.

Now, of course, the problem is that existing, deployed SIM cards are not necessarily able to do that. The core functionality of a SIM card is to store a symmetric key and use it for an authentication protocol with the phone provider network. This is called A3/A8 in the GSM world. This is symmetric cryptography only, which is computationally much easier and can be done with a basic 8-bit CPU, not requiring any accelerator circuitry. Such cards are quite cheaper than RSA-able smart cards, and phone companies are known to always try to lower their costs as much as possible (order of magnitude for the production cost of an individual card is around 5$ for a RSA-able card, less than 1$ for a card which does only symmetric crypto).

Some companies have deployed SIM cards which can compute signatures, but I don't think you can expect it from most existing SIM cards (yet). The technology is there, now a commercial incentive is needed.

A further complication is whether access from an Android app would be allowed. Within a phone, the SIM card is quite isolated, because it is used as the legal basis for communication billing: if the card can be hijacked from a malware app, then it becomes too easy for customers to claim that their phone was hacked and then refuse to pay their bills.

You don't "encrypt with the private key". With a private key, you decrypt or you sign. I suppose your use case is that of authentication: you want to make sure, from the server, that a specific user is on the other end of the line.


Center for Internet Security Version 6.1 Critical Security Control 16-10 My project is implementing The CIS Critical Security Controls, Version 6.1
Can anyone please give me some advice on how we can address sub-control 16.10 which says.....

"Profile each user’s typical account usage by determining normal time-of-day access and access duration. Reports should be generated that indicate users who have logged in during unusual hours or have exceeded their normal login duration. This includes flagging the use of the user’s credentials from a computer other than computers on which the user generally works."

Is there any way to add such user access constraints as day names, date range, time of day and access duration to a Windows O/S and report when attempts are made to use the user account outside these constraints?

Is there any way to add such user access constraints as day names,
  date range, time of day and access duration to a Windows O/S

Days names and times of day can be controlled using the Logon Hours attribute of Active Directory.  You can set it manually, on one or on a selection of users, or you can use a script to automate the process.  You'll also need to Force logoff when logon hours expire to actually force them off at the end of their time.

As for logon duration, it's possible for you to calculate it from the logs, but not to configure a maximum in Active Directory or Windows.  (That's not completely true.  With Microsoft Live Family accounts, for example, you can impose both time-of-day and duration limitations on your children if they're under 18.  I haven't seen that feature show up in corporate Windows, however, probably due to the lack of children in most corporations.)

  report when attempts are made to use the user account outside these constraints?

You can extract this information from logs (if you're using a SIEM, you should be able to make it alert or report).  For example, Windows Event ID 4625 ("An account failed to log on") entries with Status = 0xC000006F mean "User logon outside authorized hours."


SSL connection process I have a couple of questions about SSL connection process between client and server.

1) During connection process server sends his certificate to the client. Certificate contains his public key and digital signature. How is this digital signature formed? Is it static or generated independently for each connection?

2) When client receives this digital signature he has to decrypt it. Which public key is used for it? Public key of the server or public key of the CA?

1) During connection process server sends his certificate to the client. Certificate contains his public key and digital signature. How is this digital signature formed? Is it static or generated independly for each connection?

The digital signature contained in the certificate sent by the server is generated by a Root CA which the client trust (your browser). This means that a Certificate Authority that you trust has signed the certificate that you are validating. In real world, a Root CA has sign an intermediate CA certificate that has sign the server certificate. The digital signature is a Hash of the server certificate signed with the CA private key.

  2) When client receives this digital signature he has to decrypt it. Which public key is used for it? Public key of the server or public key of the CA?

This process is called Certificate Chain Verification. You verificate the digital signature of the server certificate using the public key of the CA that has sign the server certificate. If it's correct, then now you must verificate the digital signature of that CA with the public key of the next CA, until you hit the Root CA that you must trust in order to validate successfully the certificate (along with other checks that are performed).


Cross subdomain PHP security? I understand there are security risks with regards to cross subdomain session cookie attacks which are covered in other posts. However what about PHP script security?

If a user with subdomain FTP access on a cPanel server uploads a PHP script, can the privacy of other subdomains on the same domain be compromised, eg could the script obtain a file listing from another sub-domain or include files from the parent directory?

FTP access is restricted to the sub-domain directory.

Typically yes, but it depends on how the web server is configured.

If someone can run a PHP script on a server, he can execute commands, get file listings and include other files. However, this is still bound by normal user rights. On most systems all PHP files are executed as the "apache" or "httpd" user, which would need read access to all these files. This means that any PHP script can be read from any other PHP script.

However, it is possible to secure this. It is even possible to run two subdomains on two totally different webservers, which would make access between servers impossible.


Is it safe to upload videos in cloud tools like video editors? What I have is a video file(with delicate pieces of frames in it) that I want to be edited using cloud apps, without looking further in site maps and that's not always possible too, if you have to share that file instantly, I'm not sure that general assurance of discreteness will be applied by the site owners and even will be deleted if I ask for that. that must make sure it may not fall in things where it's not intended to be used by someone, so I can share personal data. can owner rights be lost, or will high valuable information in upload files be lost, and security people are not often faced to upload their files to random sites to edit their work?
Many tools are available to give personal data away.

If you're asking a technical question, then no. If you upload your data to some website then website has the ability to do whatever it wants. Use offline editors to protect your privacy.

If you're asking a legal question, then it depends on the website's ToS and the laws that are applied to owners of the website. Also this is the wrong place for legal advice and I'm not a lawyer.


How should I authenticate my SPA frontend with my API since I´ve got no authentication process in the site? We are designing a web site for selling financial products online.

The following is a high level description of the components:

Our frontend will be a SPA built with AngularJs.
The frontend will communicate with an API hosted in Heroku.
The API will expose web resources which allows the execution of the
business process.
The API hosted in Heroku serve as a passthrough between the frontend
and the real services which actually do the tasks.
The purchase process is designen to not ask for user/password or
account creation at any point.

We have some queries we execute thru the API which returns confidential information -confidential according to the local law-

We want the frontend to authenticate to the API to retrieve this information still NOT asking for credentials to the user.

We thought about a local persistence of the credentials and obfuscating the request but that would be easy to break with a proxy so the request can be read clearly.

What would be an option for this need of authenticating the frontend without asking for credentials to our clients?

If your app is entirely client-side... then anyone who uses it can reverse-engineer anything it does.  This is just part of what you get from not operating your own backend.

You're asking for a way to authenticate to the backend without authenticating.  This is not possible.


Is the Wire messaging app secure? The Wire app appears, on the surface, to avoid many of the pitfalls that other messaging apps have - it's fully end-to-end encrypted, and it's open source. It supports video calling, and it has clients for smartphones, desktops, and web. Unlike e.g. WhatsApp, you can use the web client even when your smartphone is off.

On their privacy page, they state that

  Text messages and pictures use Off-the-Record (OTR) end-to-end
  encryption. Wire uses the Axolotl ratchet and pre-keys which are
  optimized for mobile messaging.

However, Moxie Marlinspike has said that they do not use the Signal protocol:

  Wire does not use Signal Protocol, they used some of our code to
  create a protocol of their own devising that we do not recommend.

I'm unable to find any other details on this. Is there any commentary on Wire's encryption? Is Wire secure?

Edit 2017-05-17: it looks like Wire stores a list of everyone you've communicated with in plaintext on their server, but this may change in the future.

To answer your first (and easy) question: Yes, they use Signal's protocol.

The second question is a tough one. (But since they do use Signal's protocol, you might as well use Signal, don't you think?) They're not completely open source, btw. Only the app is, the server software is not. To my knowledge, there's no security audit. I'm not sure how they handle metadata, which is a huge deal (to me, at least) and the reason why I personally use Threema. The guys behind Wire are Skype developers, which doesn't exactly inspire confidence since Sykpe is/was one of the least secure messengers around. Also, how do they generate money? The app is free. There are no ads. That should raise suspicion, if you ask me.


Same Origin Policy and CSRF-Tokens If we trust browsers that they satisfy Same Origin Policy without bugs, would we still need CSRF-tokens?

Assuming server doesn't have CORS enabled:
As far as I know we are not allowed to do POST requests cross-origin, then why is there a CSRF token?

If server has CORS enabled: (assuming both GET and POST, because I don't see the point of CORSing POST but not GET)
We could GET the page, read the token and POST a correct request.

If we trust browsers that they satisfy Same Origin Policy without bugs, would we still need CSRF-tokens?

Yes, we will. Due to the fact that there are other requests that don't fall under SOP like form submit, loading scripts..etc

  Assuming server doesn't have CORS enabled: As far as I know we are not allowed to do POST requests cross-origin, then why is there a CSRF token?

Even when CORS is disabled, the browser will complete XHR POST requests, the attacker won't be able to access the response, but the request will be completed and a he will successfully accomplish the CSRF attack.
This, however, will fail in case of PUT , PATCH and DELETE requests since the browser will first issue an OPTIONS request to the request endpoint to verify the request.

  If server has CORS enabled: (assuming both GET and POST, because I don't see the point of CORSing POST but not GET)
  We could GET the page, read the token and POST a correct request.

This would be a vulnerability with the server itself. CORS should not be open to all remote hosts, only the ones you own (trust).


What should be used as a salt? I always hear that it is best to use salts on top of stored passwords, which then somehow gets concatenated and hashed afterwards. But I don't know what to use as a the salt. What would be a good salt?

The classical recommendation for a salt for password hashing is:

A random value of 128 bits or more;
obtained from a cryptographically sound random number generator (/dev/random or /dev/urandom on modern day Unixes);
unique for each entry (i.e. don't re-use the same salt, generate a new salt for each new password);
stored in plaintext in the database (so that the salt is available when verifying the hash).

There are plenty of past discussions of related topics. And most importantly, you should not implement your own password hashing scheme -- you should use a proven, well tested, peer reviewed implementation (bcrypt/PBKDF2).


Block AzureRM PowerShell Module Is there a way to block AzureRM PowerShell module commands from being executed by certain Azure AD users somewhere in Azure group policy? Or is there a way to do this with PowerShell tools?

To my knowledge, Azure Resource Manager PowerShell scripts use the same permissions as the Azure portal, so no, you cannot prevent a user from running a PowerShell commandlet and still let them perform the same actions on the Azure portal.   This link provides more information about managing Windows Azure Permissions


Canadian police mentioned a new line-trapping technique, but what is that? The police in Canada are saying that there is a new technique ("line-trapping") where the scammers told a lady to call the police to confirm some fraudulent details, but when she hung up and called the police, the scammers were still on the line and acted as the police. The article does not get into any technical detail.

I was unable to find anything technical about this scam online. Is this something specific to the York Police switchboard, or is it something potentially larger than this particular event? Is it even a real "new technology"?

https://www.cbc.ca/news/canada/ottawa/line-in-trapping-technology-1.5387822

Because there is no technical information, the below is pure speculation

I can think about 3 methods in which the attackers could have continued tapping the device and intercepting calls.

Method #1 - Ghost Cell Tower

Assuming that the attackers had physical proximity to the victim, there are tools that enable the interception of phone calls and other communications. some call them Ghost Cell towers, and the most known "solution" in the market is a stingray.
The mobile device is always looking for the closest cell-tower, and by leveraging that inherent "vulnerability" it is possible to replicate the cell tower interaction with the mobile device to intercept the calls. It's quite widely used by law enforcement agencies including the US and Canada, and the attackers might have gotten their hands on such a device, intercept the call and continue the fraudulent activity even when the victim called the police.

Method #2 - Roaming Enforcement

A harder approach, but one that is also widely used by attackers. again an inherent "vulnerability" in the cell networks is the ability to send a request to a carrier to move a user to a different carrier for roaming (in example, if you are flying abroad and the phone immediately connects to a foreign carrier, but you are still billed by your local carrier for those calls / data usage). In recent years there were evidences of attackers gaining access to less secure carriers (e.g. in africa) and transmitting a roaming request for a victim, to intercept SMS OTP requests mostly for financial hacking (e.g. bank accounts). if the attackers had a grip over a third party carrier, they could roam the device to that carrier and for a small period of time be able to route phone calls or intercept SMS requests. To date I haven't heard of that method being used for phone calls, but mostly for SMS phishing / fraud. You can read more about those attacks in the great blackhat presentation by Hendrick Shmidt, Daniel Mende and Enno Ray

Method #3 - Attackers infected the victim's device

If the attackers had access to the device through a malware of any sort, they were probably able to alter the phone numbers for the "police line" or route calls. I didn't see the article suggest whether the victim had an android or an iphone device but for android it should be quite easy. there are companies that sell such technologies to enforcement agencies (e.g. NSO) and a similar tool might have found it's way to the attackers.

You can also read a bit more on GSM risks in this article by the GSMA:
https://www.gsma.com/security/wp-content/uploads/2019/03/GSMA-Security-Threat-Landscape-31.1.19.pdf


Malicious QR Code and Mitigation I just started reading a little on QR code, so I'm not entirely familiar with QR Code capabilities, but a thought crossed my mind today.

I scanned a QR Code on a postcard I received, and it immediately took me to a website.

Just like URL shorteners, is there any protection from obscuring a malicious site in the QR code?

I also noticed you can use QR Code for multiple other things such as VCards, Youtube videos, etc...

Can you embed code that then gets executed on the client when scanned?

Again, I just started reading around, so my understanding of this technology is pretty feeble, but primarily what I'm looking for is some ideas of potential threats from scanning QR codes, as well as potential mitigation techniques.

  This question was IT Security Question of the Week.
  Read the May 4, 2012 blog entry for more details or submit your own Question of the Week.

A QR code is nothing more than an encoding of data.  URLs being encoded as QR codes are just one specific usage.  As you say, it suffers the same problems as URL-shorteners in that you might never actually know where it goes until it takes you there.  However, any decoder could provide a safe landing zone before allowing a browser to be launched.

Because the QR code can encode any data up to a specific maximum, the use of the QR code is only limited by the applications which scan them and make use of the data.  This allows a wide and blind attack area.  Furthermore, the decoder itself could have a variety of buffer overflows to exploit.


Nmap scan produces all "unknown" I scanned both localhost, and the IP address of the LAN adapter, and this is the produced output.

Starting Nmap 5.51 ( http://nmap.org ) at 2012-10-12 18:06 Eastern Daylight Time
Skipping SYN Stealth Scan against localhost (127.0.0.1) because Windows does not support scanning your own machine (localhost) this way.
Nmap scan report for localhost (127.0.0.1)
Host is up.
PORT      STATE   SERVICE
1/tcp     unknown tcpmux
3/tcp     unknown compressnet
4/tcp     unknown unknown
6/tcp     unknown unknown
7/tcp     unknown echo
9/tcp     unknown discard
13/tcp    unknown daytime
17/tcp    unknown qotd
19/tcp    unknown chargen
20/tcp    unknown ftp-data
-------redacted-for-posting-purposes-------
60020/tcp unknown unknown
60443/tcp unknown unknown
61532/tcp unknown unknown
61900/tcp unknown unknown
62078/tcp unknown iphone-sync
63331/tcp unknown unknown
64623/tcp unknown unknown
64680/tcp unknown unknown
65000/tcp unknown unknown
65129/tcp unknown unknown
65389/tcp unknown unknown

Nmap done: 1 IP address (1 host up) scanned in 0.11 seconds

Unknown for all ports scanned. I then proceeded to scan "scanme.nmap.org", and had regular output as expected upon scanning that service.

Any suggestions?

The problem is with Windows and scanning the local machine. Nmap on Windows does not work the same way as it does on Linux due to differences in how the NIC is accessed. It is not actually connecting to each port from a separate process, but is connecting to itself. This is why the scan results in all ports being listed, and results in the connection to each port being omitted.

As a test, scan port 8 and 18 (omitted in the scan above). Assuming you originally did a default scan, those ports would not be tested. If you specifically test them, they should show up as 'unknown', too.


List of all available nmap script arguments I need to do a scan, for example with http-sql-injection.nse
nmap script.

I already know that I should use --script-args to set arguments, but my question is not about it.

How can I look on the whole pack of arguments, that this script (or any of nmap's scripts) can take?

Accordly with the nmap documentation in "Example 9.2. script help", the nmap's parameter that displays help about the script is:

nmap --script-help <filename.nse>

Namely:

nmap --script-help http-sql-injection.nse

If you look at NSE documentation written by own Nmap's creator:

  3.1. description Field

  The description field describes what a script is testing for and any importantnotes the user should beaware of.
  Depending on script complexity, the description may vary from a few
  sentences to a few paragraphs. The first paragraph should be a brief
  synopsis of the script function suitable for stand-alone presentation
  to the user. Further paragraphs may provide much more script detail.

Fyodor explain that the "description" field is used to describe everything about the complexity that the script itself might have. So, go ahead and look deeper into how the script was made:

 $ vi /usr/share/nmap/scripts/http-sql-injection.nse

...

 11 description = [[
 12 Spiders an HTTP server looking for URLs containing queries vulnerable to an SQL
 13 injection attack. It also extracts forms from found websites and tries to identify
 14 fields that are vulnerable.
 15
 16 The script spiders an HTTP server looking for URLs containing queries. It then
 17 proceeds to combine crafted SQL commands with susceptible URLs in order to
 18 obtain errors. The errors are analysed to see if the URL is vulnerable to
 19 attack. This uses the most basic form of SQL injection but anything more
 20 complicated is better suited to a standalone tool.
 21
 22 We may not have access to the target web server's true hostname, which can prevent access to
 23 virtually hosted sites.
 24 ]]

This explain why the http-sql-injection.nse script do not shown "usage options" whether that's what you expected to see.

The NSE scripts has a tradition to include "usage options" inside a comments. Such thing that was documented on the section "8.1 The Head":

  Next comes NSEDoc information. This script is missing the common
  @usage and @args tags since it is so simple, but it does have an
  NSEDoc @output tag:

---
--@output
-- 21/tcp   open     ftp       ProFTPD 1.3.1
-- |_ auth-owners: nobody
-- 22/tcp   open     ssh       OpenSSH 4.3p2 Debian 9etch2 (protocol 2.0)
-- |_ auth-owners: root
-- 25/tcp   open     smtp      Postfix smtpd
-- |_ auth-owners: postfix
-- 80/tcp   open     http      Apache httpd 2.0.61 ((Unix) PHP/4.4.7 ...)
-- |_ auth-owners: dhapache
-- 113/tcp  open     auth?
-- |_ auth-owners: nobody
-- 587/tcp  open     submission Postfix smtpd
-- |_ auth-owners: postfix
-- 5666/tcp open     unknown
-- |_ auth-owners: root

Since the documentation does not explicitly show the use of "@usage", look yourself in /usr/share/nmap/scripts/:

$ grep -iR -A5 "@usage" /usr/share/nmap/scripts/
/usr/share/nmap/scripts/ajp-brute.nse:-- @usage
/usr/share/nmap/scripts/ajp-brute.nse--- nmap -p 8009 <ip> --script ajp-brute
/usr/share/nmap/scripts/ajp-brute.nse---
/usr/share/nmap/scripts/ajp-brute.nse--- @output
/usr/share/nmap/scripts/ajp-brute.nse--- PORT     STATE SERVICE
/usr/share/nmap/scripts/ajp-brute.nse--- 8009/tcp open  ajp13
...


What are the security measures taken on GPS transmissions? I was just reading this article on how phone GPS work and the improvements that Apple had done to reduce the amount of time those calculations take on a regular iPhone.

That makes me wonder: what measures have been taken so that none of us are around transmitting fake GPS data that would make people get lost more often than usual?

I'm going to start off my assuming that you're referring to the Civilian segment of the NAVSTAR (US/NIST) based system and not the encrypted military version.

Short answer is that there is no cryptographically secure encryption in place over the transmitted NAVSTAR Ephemeris data.  It's not impossible to spoof this signal, just technically very difficult and requires precise synchronization of many different systems.  (It's not at all like "Tomorrow Never Dies")

Understanding how the GPS Space Segment works will illuminate why this is inconsequential to the performance of the system.  There are currently 24 active space vehicles (SVs) and 4 spares in orbit around the earth right now.  Each SV is identified by a C/A (Course or Acquisition) code that is uniquely identifiable.  The NAVSTAR base signal is transmitted at 1575.42 MHz and every SV transmits on the same frequency.  How do they avoid stomping all over each other you ask?  They use Code-Division Multiple Access (CDMA - yes, like Verizon and your cell phone) to allow the receiver to filter out the signal (arranged by C/A code).

Each SV transmits what's called the Ephemeris data, these are 6 parameters (and a few extra for corrections) that allow the receiver to exactly calculate the positions of all 28 SVs in orbit for a precise time (that time delivered by those SVs).  You can then use the calculated position of the satellites to determine the pseudorange from the SV to you, and therefore your position.  Huzzah!

Now, to break it.

You would have to have

The ability to generate and encode a properly formatted NAVSTAR Ephemeris message
The ability to directionally target this message (and signal) towards your intended victim
The ability to completely drown out the standard NAVSTAR broadcasts on L1, L2 and L5 (unlikely, as the signal level itself is down at around -159 dBw broadcast and looks like static.)

If even you were to put these systems in place, your signal would appear as a very directional skew, and only to the select few people in its path which make spoofing it a very expensive and cumbersome task.  (What's likely is that your receiver will think you are somewhere in the middle of the Earth.)  It's much easier to just jam the signal altogether and remove the user's ability to navigate through space and time.

High level GPS/NAVSTAR Overview - Slides

High level GPS/NAVSTAR Overview - Text

More detailed signals specification

EDIT :
I found a fantastic TED Talk describing a series of possible exploits for GPS as well.


What Information is Exposed When I Send A Message From My Mobile Device When I send a text message and/or an email, with or without location services turned on, what information is available to the recipient of that message if they know how to read the data behind the original message? IE: Location, my device, the service I use, etc.

I ask because I would like to know what information I am exposing by sending a message from my phone. (I understand that the actual text of an SMS message itself is completely unsecure.)

this would totally depend on the specific application you are using to send the message.  A text message is going to expose different information than a message sent through a private app such as 'whatsApp', or 'Skype'.

Typically For messaging apps the end recipient will at least have your cellphone number, time the message was sent, content, and potentially location (depending on the app).  Emails contain the IP address which sent the message in their headers.  Since you are on mobile though, the IP assigned to your device might not be a great indicator in terms of geolocation.  I've seen mobile phones geolocate their IP to a neighboring state.

With the exception of emails, most messaging apps don't let you see the behind the scenes headers (even if you're sniffing the network).  Only the app/service provider might have access to that.


Are python's popen (and similar) functions affected by Shellshock? Basically which python's functions trigger bash (and might be impacted by shellshock), and which don't ?

I have come up with this question by seeing in some scripts the popen() function.

My question relates to both Python 2 and 3.

Any program that, at some point, calls bash is affected. In particular the os.system function is vulnerable if the system has bash as /bin/sh, so any program calling it (or some equivalent) is vulnerable too.

The popen functions can be vulnerable, depending on the arguments passed. Quoting from the documentation:

  Also, for each of these variants, on Unix, cmd may be a sequence, in
  which case arguments will be passed directly to the program without
  shell intervention (as with os.spawnv()). If cmd is a string it will
  be passed to the shell (as with os.system()).

to my understanding this means that calls like:

os.popenx(['executable', 'some', 'arguments'])

are safe because no shell is invoked, while commands of the form:

os.popenx('executable some argument')

are vulnerable because a shell will be used to interpret the string as a command line.

Also note that all popen functions are deprecated since python2.6 and should have been avoided since then. The subprocess module provides a much better interface to launching subprocesses which is shellshock safe by default. If you don't pass the shell=True argument your program wont launch subshells and hence wont be affected by shellshock.

To safely use subprocess you should avoid using the shell=True argument as much as you can (this was true even before the discovery of shellshock and is already well documented as a security hazard anyway).

In particular, if you want to simply launch an executable use subprocess.call:

subprocess.call(['executable name', 'arg1', '--opt1', 'opt-arg', ...])

if you don't want to write the list of strings by hand you can rely on the shlex module:

subprocess.call(shlex.split('executable-name arg1 "quoted arguments are correctly handled" etc'))

If you want to retrieve the output of the command use check_output instead of call.

If you want to run a pipeline of commands like cmd1 | cmd2 | cmd3 you can still avoid launching a shell:

cmd1 = subprocess.Popen(cmd1_command_line, stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(cmd2_command_line, stdin=cmd1.stdout, stdout=subprocess.PIPE)
cmd3 = subprocess.Popen(cmd3_command_line, stdin=cmd2.stdout, stdout=subprocess.PIPE)

Use shell=True only if strictly necessary, and in such a case consider explicitly passing the environment to the shell using the env argument.


Encryption / Decryption algorithm generic across JRE (Sun/IBM) Is there any encryption algorithm that is generic across all platforms? Is RSA generic across SUN/IBM JRE?

Another question: will base64Encoder / base64Decoder sun.misc.BASE64Decode / sun.misc.BASE64Encoder behave the same way in IBM JRE?

Also are there differences in using this algorithms in the 32bit / 64bit JREs? If yes, then how to tackle them?

The standard name documentation of the Java Cryptography Architecture (JCE) contains a section about implementation requirements. For both Java 7 and Java 8 it contains the following entries for Cipher with regards to RSA:

RSA/ECB/PKCS1Padding (1024, 2048)
RSA/ECB/OAEPWithSHA-1AndMGF1Padding (1024, 2048)
RSA/ECB/OAEPWithSHA-256AndMGF1Padding (1024, 2048)

to make sure you got the right one, specify the complete string (excluding the key sizes within the parenttheses of course). So that would be "RSA/ECB/OAEPWithSHA-1AndMGF1Padding" for OAEP padding.

RSA is a set of internationally standardized algorithms (defined in the PKCS#1 standards and the RFC's derived from those standards). The implementations should confirm to the test vectors for any platform. RSA for instance uses big endian encoding, even on little endian platforms.

The Base64Encoder is a Sun internal class. It may even be inconsistent across implementations and it may disappear without warning. It is used a lot unfortunately so Oracle and others may decide to leave it in place, just in case. You should never ever use Sun internal classes. Many static code validators and even IDE's will flag this as an error.

For Java 8 compatible runtimes you should use the Base64 class. For earlier versions you should go with a library. The Apache Commons Codec is often used. Google Guava is used a lot as well and has a set of codecs too.

Base 64 has been around for a long time. It should not run any differently on 32 bit or 64 bit on any platform, as long as you are sure you use the same character encoding. UTF-8 encoding - compatible with US ASCII for base 64 - should be preferred.

Finally there are the Java Bouncy Castle libraries and provider. The Bouncy Castle libraries contain an ever growing amount of cryptographic functionality that can be used on any Java runtime. The provider is used to allow much of this functionality to be used through the Java JCA/JCE. And it of course also contains a Base64 class in the "lightweight" API.

As long as you use the API correctly Java is fully compatible on 32 and 64 bit, big endian or little endian processors. It should not even matter if you use Linux, Windows, MacOS. Android should be compatible as well, although it is not an official Java distribution.


Why ASP.Net Identity sends sensitive information to clients? As far as I understand, Identity sends to the user an encrypted token with some user information like the user name and expiration date. Then, when a new request arrives to the server, it decrypts it and will have available all the user claims and some other information.

My question is, in case there is no need to send the authetication information to other servers (for example if you are authenticating against another web site) would it be more safe not to send as much information to the user? Perhaps we can just send a large code to the user and then match it with an in memory collection or database.

I know that if someone is able to intercept that code she will be able to also make valid requests, but when the "ticket" expires it will not longer be valid for anyone until making the login process again. However, if that code is compromised there won´t be any other information than that.

I hope I am being clear with my question, if not, please let me know it so I can improve it.

DISCLAIMER: I am not a Microsoft employee and I do not know the exact causes of presenting ASP.NET Identity. My opinion base on documentation and some practical experience.

The main purpose of presenting ASP.NET Identity by Microsoft was to make the authentication mechanism more generic, reusable and testable. There also show up some new ways of user authentication using social media which have happen to be more and more popular and would be nice to support.
To achieve those goals some standard behaviors have been implemented in library like Cookie-based authentication (using OWIN middleware), where some user data are put into the encrypted token and provided as authentication cookie.

I think that you are correct in your exact use case. But thinking of different scenarios that ASP.NET Identity can be used, you can use the same code and same mechanism (after some easy reconfiguration), which means that it is quite easy to change the behavior of an application.

If you would like to change authentication mechanism to your idea, you still can do this without breaking the rules of ASP.NET Identity. The only you have to do, you need to implement some interfaces presented with ASP.NET Identity and add this to your app stack.


why is it insecure to use userdata in url parameter names? On the OWASP site on XSS it says that it is safe to put userdata in GET parameter values when encoded.

However, userdata should not be used anywhere else, so not in the scheme, the domain or parameter names. Unfortunately I can't find any clues why it would be unsafe in parameter names.

Can anyone show me an example or explanation of what might happen if you do? Obviously I would still use url encoding on the parameter name.

In the scheme, an attacker could use the javascript protocol to perform XSS:

click

The data protocol could also be used in attacks.

Apart from that, OWASP is not really talking about domain or parameter names here, as this guide is strictly about defending against XSS in different contexts. Depending on your application, you might still want to have control over it though, but that's not relevant to XSS.

Regarding XSS, parameter names are not special and can be treated the same way as parameter values. OWASP probably does not mention them explicitly because user-supplied parameter names are not very common.


Standards for CA cert revocation and time-constrained cryptographic algorithm parameters I'm working on software that will be in use for foreseeable future (15 years+) that will need to validate XAdES-A signatures (long term archival, similar to PAdES-A, but for XML). That means, it will have multiple CA certificates required for its verification, different signature algorithms and different digest algorithms.

As such, I see two problems:

getting information which CA certificates lost their validity before their notValidAfter date (because of CA compromise, cease of operation, etc.)
marking algorithms (like SHA-1) or key lengths (like RSA 1024) as insecure after some date

Is there some standard for files with such information? If I create my own, should I rather choose to save this information as OIDs (algorithms) or just as human-readable names (I'm using Java if that has anything to do with this...).

About trusted CA list formats, see RFC 5914 ("Trust Anchor Format") and the behemoth Trust Service Status List format. European Union tries to maintain such a list.

For the algorithms or key sizes, as far as I know, the recommendations are for human consumption, not in a computer-readable format. See this site for pointers (e.g. to the NIST recommendations). Contrary to lists of trust anchors, we do not expect regular activity there, and it will be by burst (changes to our notion of security of algorithms and key lengths come from cryptanalytic research results, which appear rather unpredictably -- because Science works that way).


Increasing tomcat session id increases security Tomcat gives a configuration sessionIdLength to be configurable, but does increasing the session id increases its security or its just security through obscurity

It increases the difficulty of brute-force guessing session identifiers. This only increases security in general if session guessing is a realistic attack.

The default value of 16 (128 bits) is pretty standard across web frameworks and already makes brute-force guessing very difficult. See OWASP's justification for this length.

Unless you have conditions that are different from the average web app (for example if you have a very large number S of simultaneously active guessable sessions), it is unlikely you'll get any benefit from increasing the length of the session ID beyond 128 bits.

(On the other hand, it doesn't cost you much either.)


Unexpected emails have been sent - do I need to wipe my Android? A few days ago I received a Notification from my Android saying that it could not send mail because an attachment was too large.

I opened my Gmail App and found 5 messages in the Sent Mail folder that I had not sent.

The messages were all to people in my address book. Some had two year old timestamps.  Most were empty with no subject or message.  One had a large MP4 attachment which I deleted.

One of the messages looked like this:

date: 2014/09/30,12:37:00
to: johnwilson@example.com
subject: Try this
message: Maybe it needs message text

I ran Symantec Mobile Security, and it found no problems.  I also scanned with Avast and with Dr. Web and found no problems.

My phone is not rooted.  Nothing else looks suspicious about my phone: it runs fast -- no weird data usage.  There are no strange apps installed, and nothing has been installed recently on the device.

Do I need to wipe my phone?

Is there some other check I can run on my Android to see if I've been pwned?

You should not only focus on your cellphone, as there are other possibilities how this can happen. If a mail is sent from a pc it will also be shown in you GMail App, so this is no evidence that your mobile phone is the root of the mails.

Look at your Google Account's recent activity, perhaps your password has been guessed or stolen from somewhere. There you can see the date and ip from all login activities related to your account.
Further you should check all permissions you gave any software on your account.

I would strongly suggest to change your Google password and to take a look at two factor authentification for advanced security.

To your actual question:

There are plenty of scanners out there for Android, and according to a german IT magazine the best ones are:

Avast Mobile Security
Dr. Web Anti-virus Light
F-Secure Mobile Security
IKARUS mobile.security LITE
Lookout Security & Antivirus
Kaspersky Mobile Security (Lite)
Zoner AntiVirus Free

EDIT:

GMail always shows these notifications, even if the action was taken on a computer (at least it works this way for me, I took a quick test)

With your new information, it strongly looks like one of your systems is compromised. It could be your cellphone or your PC. You really should check both. If you can swipe you cellphone without a loss of important Data it may be a good idea (But remember to get reserve codes for your two factor authentification, it may depend on your phone).


How does Google detect new devices for two factor authentication When you enable two step verification for google accounts, you get sent a code by SMS to enter in addition to your username and password the first time you log in with a new device.

How do they detect that you're on a new device? I imagine for security it's probably a serverside generation of a device fingerprint, however surely one iPhone 5 is much like another - how can they be differentiated given the way the service works?

It uses cookies (more specifically, the SMSV cookie h/t @Tomer). Use chrome in normal mode and login with 2FA. Open an incognito session* of Chrome and it will be a "new device". The only difference between the two is that the latter doesn't have any cookies (maybe it also has a different set of extensions, but it is unlikely that Google is using browser fingerprinting*)
In fact, I am under the impression said cookie only lasts for 30 days.
*make sure that if you have any extensions, they are ALL allowed in incognito mode, and you will see there is no "browser fingerprinting", as per @David Houde's answer.


Tracing the attacker I have seen from:
http://www.scientificamerican.com/article/tracking-cyber-hackers/

"The source field can be changed [spoofed] by an attacker to make it
seem like it's coming from someplace it's not"

From what I know, IP spoofing only allows one-way communication, as server replies the spoofed address, and therefore its attack is limited. Isn't that right?

I suspect they are oversimplifying. You're correct in that generally two way communication with a spoofed IP address is not possible. There were tcp sequencing attacks but they have not been practically possible for years.
However, there are so many other ways to hide your IP address, e.g., tor, pivoting off compromised hosts, using a VPN that won't keep logs, free WiFi, etc..
It's probably just easier for them just to say spoofed than to enumerate all the ways you can mask your address.


How to defeat software keyloggers Is it possible to defeat software keyloggers?

I remember reading long ago about programs run from a USB which will defeat keyloggers.

The software works (if I remember correctly) by intercepting keyboard events to the system, and randomly replacing your keystrokes with random keys, and then counteracting the randomness with a backspace or copy and paste type algorithm.

Does this kind of software exist, and is it reliable? I'm sure a dedicated attacker could read his/her logs, but for use in a library or other public location this approach could seemingly work.

The generic issue with such countermeasures is that they defeat only some keyloggers, and are themselves defeated by the next generation of keyloggers. In this case, it would be easy for a keylogger to take into account the backspace events (the keylogger sees all keyboard events, so in it sees backspaces) to rebuild the actual password. In fact existing key loggers should already do that, because human users use the backspace key occasionally, too !

Another generic issue with an anti-keylogger software is that it is software. A software keylogger, in order to enact its malevolent functionality, must intercept keypress events, and this requires privileged access to the operating system, at least administrator-level. An evil piece of code which obtains such access will not necessarily stop there; it may also scan for the launch of known anti-keylogger software and deactivate it. Malware and virus do that in general, against anti-malware and anti-virus software.

An additional reason why a keylogger would block out your envisioned anti-keylogger software is that keylogger writers generally dislike competition -- if they find other keyloggers from their fellow keylogger writers, they promptly kick them out. Your anti-keylogger software, from the outside, really looks like a keylogger, since it intercepts keypress events; it is then likely to be deactivated by another keylogger which just wants the monopoly of key logging.

Therefore, if software such as you describe exists at all, then it cannot be considered as reliable. It might enjoy some partial success against a few keyloggers, but this won't last.


How to read the key3.db file? The file key3.db contains the key that is used to encrypt the Firefox passwords stored in logins.json file.

I don't use master password in Firefox, but according to this article, my passwords are encrypted with a random key that is stored in key3.db file.

I tried to open the file using the SqliteBrowser, but I got an error: "Invalid file format". Can anyone know how to read this file so I will be able to get the key for my Firefox passwords?

If no master password is set, Firefox uses an empty password.

For a dirty Python script to decrypt and dump the data (plus some more), see the following code. It is an old project of mine and I just updated the reading of the passwords and usernames which were saved in signons.sqlite before (now in logins.json). I can't guarantee that (everything) is working, but it did in my test case.

#!/usr/bin/env python

from ctypes import *
import struct
import base64
import platform
import os
import sqlite3
import json

# TODO: if python 3. use
#from configParser import ConfigParser
# else
from ConfigParser import ConfigParser

#
# Some little firefox forensic script delivering following data:
# - saved passwords (decrypted if no master pw is set)
# - visited pages
# - download history
# - form history
# - cookies
#
# TODO:
# - flash cookies and stuff
# - finish comments
# - add little brute forcer for master pw
# - dump master pw ?
# - add some more compatibility stuff (mac if requested, else fuck it)
# - use some user defined exceptions instead plain exception
# - cache
# - think about which data from the db to return ;)
#
# ATTENTION: On my win7 system i needed a newer sqlite version.
# see http://code.activestate.com/lists/python-tutor/96183/
# - easy (and dirty) solution: get new sqlite.dll, replace in ...python/DLLS/
#
# CREDITS:
# - Decrypt saved passwords: https://github.com/pradeep1288/ffpasscracker
# - Myself for doing a .schema on every db to get the structure *yay for me*
#

#Password structures for firefox >= 3.5 ?!
class SECItem(Structure):
    _fields_ = [('type',c_uint),('data',c_void_p),('len',c_uint)]
class secuPWData(Structure):
    _fields_ = [('source',c_ubyte),('data',c_char_p)]
(SECWouldBlock,SECFailure,SECSuccess)=(-2,-1,0)
(PW_NONE,PW_FROMFILE,PW_PLAINTEXT,PW_EXTERNAL)=(0,1,2,3)

class FileNotFoundException(Exception): pass

class Firefox_data_generic(object):
    """
    Some general informations:
    - Every timestamp is a unix timestamp in millisec (/1000 to use with pythons time stuff)
    -
    """

    def __init__(self, profilpath = None, compatibility_infos = None ):
        if platform.system().lower() == 'windows':
            find_profil_path =  self.__find_profile_path_windows
            load_libraries = self.__load_libraries_win
        else: # TODO. care about mac (which i don't atm)
            find_profil_path = self.__find_profile_path_linux
            load_libraries = self.__load_libraries_linux

        if profilpath is None:
            self.profilpath = find_profil_path()
        else:
            self.profilpath = profilpath
        self.default_profil = self.__get_default_profile()

        if compatibility_infos is None:
            self.ff_version, self.platform_dir, self.app_dir = self._get_info_from__compatibility_ini()
        else:
            self.ff_version, self.platform_dir, self.app_dir = compatibility_infos

        load_libraries(*self.ff_version)

        # set up for the specified ff version
        major, minor = self.ff_version
        # We don' care about stone age ff versions
        if self.ff_version < (3, 5):
            raise Exception('Nobody got time for implementing the features for this fucking old ff version')
        # download history moved from downloads.sqlite to places.sqlite
        if major >= 26:
            self.get_all_downloads = self.__get_all_downloads_places
            print 'get downloads from places.sqlite'
        else:
            self.get_all_downloads = self.__get_all_downloads_downloads
            print 'get downloads from downloads.sqlite'

        #print 'Profilepath is:', self.profilpath

    #############################################################
    # Placeholder
    #############################################################
    def get_all_downloads(self, profile = None):
        """ returns [(url, fileName, saveTo, size, endTime, done), ...]
        monkey patched to __get_all_downloads_downloads for version < 26 (TODO: ?)
        or else to __get_all_downloads_places
        """
        raise NotImplementedError('get_all_downloads not implemented')

    #############################################################
    # General working functions
    #############################################################
    def _get_info_from__compatibility_ini(self, profile = None):
        if profile is None:
            profile = self.default_profil
        config_file = '/'.join((profile, 'compatibility.ini'))
        if not os.path.isfile(config_file):
            raise FileNotFoundException('compatibility.ini not found at "%s"' % config_file)
        config = ConfigParser()
        config.read(config_file) # TODO: catch return (list of succesfully read configs)
        major, minor = config.get('Compatibility', 'LastVersion').split('_')[0].split('.')[:2]
        # TODO: check if value exists
        return ( (int(major), int(minor)), config.get('Compatibility', 'LastPlatformDir'), config.get('Compatibility', 'LastAppDir'))

    def get_all_visited(self, profile = None):
        """ Return all visited urls in the form of [(url, visit_count, last_visit_date), ...]
        Ordered by date asc.
        If no profile path is suplied use the default one.
        Should work from v. 3.0 and above (TODO: ?)
        """
        if profile is None:
            profile = self.default_profil
        db_path = '/'.join((profile, 'places.sqlite'))
        if not os.path.isfile(db_path):
            return None # TODO: raise exception
        con = sqlite3.connect(db_path)
        ret = con.execute('SELECT url, visit_count, last_visit_date FROM moz_places where visit_count > 0 order by last_visit_date asc;').fetchall()
        con.close()
        return ret

    def search_history(self, custom_filter, profile = None):
        for elem in self.get_all_visited(profile):
            if custom_filter(elem):
                yield elem

    def test_master_pw(self, password, profile = None):
        if profile is None:
            profile = self.default_profil
        self.libnss.NSS_Init(profile) # TODO: check for errors here ? Init it once for all functions ?
        keySlot = self.libnss.PK11_GetInternalKeySlot()
        ret = self.libnss.PK11_CheckUserPassword( c_int(keySlot), c_char_p(password)) == SECSuccess
        self.libnss.PK11_FreeSlot(c_int(keySlot))
        self.libnss.NSS_Shutdown()
        return ret

    def is_master_password_set(self, profile = None):
        return not self.test_master_pw('', profile)

    def get_saved_passes(self, profilpath = None, decrypt = True, masterpass = ''):
        """ Try to get and decrypt saved passwords.
        The result (if successfuly) is in the form:[(hostname, httpRealm, formSubmitURL, usernameField, passwordField, username, password, encType, timeCreated, timeLastUsed, timePasswordChanged, timesUsed), ...]
        username and password are decrypted if no master password is set or they are not encrypted (doh) or the decrypt flag is set to False.
        In this cases the unaltered data is returned.
        """
        # decrypting part from https://github.com/pradeep1288/ffpasscracker
        # for db schema: http://www.securityxploded.com/firepasswordviewer.php#for_firefox_3_5_and_above
        #  or just do a .schema moz_logins in the signons.sqlite /* signons.sqlite is gone and replaced by logins.json */
        if profilpath is None:
            profilpath = self.default_profil

        db_path = '/'.join((profilpath, 'logins.json'))
        if not os.path.isfile(db_path):
            raise FileNotFoundException('signons.sqlite not found at "%s"' % db_path)
        with open(db_path, 'rb') as fd:
            login_data = json.load(fd)

        # care about 'would_block' (-2) ?
        if self.libnss.NSS_Init(profilpath) != SECSuccess:
            # TODO: react to this
            print """Error Initalizing NSS_Init,\n
            propably no usefull results"""
            raise Exception('NSS_Init failed') # TODO: error code ?

        # TODO: check errors
        slot = self.libnss.PK11_GetInternalKeySlot()
        self.libnss.PK11_CheckUserPassword(slot, masterpass)
        self.libnss.PK11_Authenticate(slot, True, 0)

        pwdata = secuPWData()
        pwdata.source = PW_NONE
        pwdata.data=0

        uname = SECItem()
        passwd = SECItem()
        dectext = SECItem()
        con = sqlite3.connect(db_path)
        ret = list()
        for row in login_data['logins']:
            if not decrypt: # not encrypted
                row["encryptedUsername"] = base64.b64decode(row["encryptedUsername"])
                row["encryptedPassword"] = base64.b64decode(row["encryptedPassword"])
                ret.append(row)
                continue
            # decrypt it
            uname.data  = cast(c_char_p(base64.b64decode(row["encryptedUsername"])),c_void_p)
            uname.len = len(base64.b64decode(row["encryptedUsername"]))
            passwd.data = cast(c_char_p(base64.b64decode(row["encryptedPassword"])),c_void_p)
            passwd.len=len(base64.b64decode(row["encryptedPassword"]))
            if self.libnss.PK11SDR_Decrypt(byref(uname),byref(dectext), 0)==-1:
                raise Exception('Username decrypt exception with:' + str(row))
            row["encryptedUsername"] = string_at(dectext.data,dectext.len)
            if self.libnss.PK11SDR_Decrypt(byref(passwd),byref(dectext), 0)==-1:
                raise Exception('Password decrypt exception with:' + str(row))
            row["encryptedPassword"] = string_at(dectext.data, dectext.len)
            ret.append(row)
        self.libnss.NSS_Shutdown()
        con.close()
        return ret

    def get_all_cookies(self, profile = None): # yummy
        """ Returns all cookies in the form of [(baseDomain, appId, inBrowserElement, name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly), ...]
        Should work for versions >= 3.0 (TODO: ?)
        """
        if profile is None:
            profile = self.default_profil
        db_path = '/'.join((profile, 'cookies.sqlite'))
        con = sqlite3.connect(db_path)
        ret = con.execute('SELECT baseDomain, appId, inBrowserElement, name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly FROM moz_cookies;').fetchall()
        con.close()
        return ret

    def get_all_form_history(self, profile = None, orderBy = 'firstUsed', orderASC = False):
        """ Returns all form history in the for of: [(fieldname, value, timesUsed, firstUsed, lastUsed), ...]
        Should work for versions >= 3.0 (TODO: ?)
        """
        if profile is None:
            profile = self.default_profil
        db_path = '/'.join((profile, 'formhistory.sqlite'))
        con = sqlite3.connect(db_path)
        ret = con.execute('SELECT fieldname, value, timesUsed, firstUsed, lastUsed from moz_formhistory order by %s %s;' % (orderBy, ('ASC' if orderASC else 'DESC'))).fetchall()
        con.close()
        return ret

    def search_form_history(self, custom_filter, profile = None, orderBy = 'firstUsed', orderASC = False):
        for elem in self.get_all_form_history(profile, orderBy, orderASC):
            if custom_filter(elem):
                yield elem

    #############################################################
    # Version and platform specific functions
    #############################################################
    def __find_profile_path_windows(self):
        """ Should work for win >= 2000 (TODO: ?)
        """
        # TODO: should work for Windows 2000, XP, Vista, and Windows 7, (win 8 TODO: ?)
        path = '/'.join((os.environ['APPDATA'], 'Mozilla/Firefox/Profiles'))
        if not os.path.isdir(path):
            raise FileNotFoundException('Profile folder "%s" not found.' % path)
        return path

    def __find_profile_path_linux(self):
        # TODO: check where the default profile path on different distros are
        path = '/'.join((os.environ['HOME'], '.mozilla/firefox'))
        if not os.path.isdir(path):
            raise FileNotFoundException('Profile folder "%s" not found.' % path)
        return path

    def __get_default_profile(self):
        try:
            profile = ( p for p in os.listdir(self.profilpath) if p.endswith('.default') and os.path.isdir('/'.join((self.profilpath, p)))  ).next()
            return '/'.join((self.profilpath, profile))
        except StopIteration:
            return None

    def __load_libraries_win(self, major, minor):
        #TODO: check relevant version changes
        os.environ['PATH'] = ';'.join([self.platform_dir, os.environ['PATH']])
        self.libnss = CDLL('/'.join((self.platform_dir, "nss3.dll")))

    def __load_libraries_linux(self, major, minor):
        #TODO: check relevant version changes
        #TODO: could that lib be somewhere else (not in path) ? (i.e: is this safe ?)
        self.libnss = CDLL("libnss3.so")

    def __get_all_downloads_downloads(self, profile = None):
        #TODO: untested but should work
        if profile is None:
            profile = self.default_profil
        db_path = '/'.join((profile, 'downloads.sqlite'))
        con = sqlite3.connect(db_path)
        ret = con.execute('SELECT source, name, target, maxBytes, endTime, state FROM moz_downloads;').fetchall()
        con.close()
        return ret

    def __get_all_downloads_places(self, profile = None):
        if profile is None:
            profile = self.default_profil
        db_path = '/'.join((profile, 'places.sqlite'))
        con = sqlite3.connect(db_path)
        ret = list()
        for download in con.execute("""SELECT url, a.content, b.content, c.content from moz_annos a, moz_annos b, moz_annos c, moz_places p
            where a.place_id = b.place_id and b.place_id = c.place_id and p.id = a.place_id
            and a.anno_attribute_id = (select id from moz_anno_attributes where name = 'downloads/destinationFileName')
            and b.anno_attribute_id = (select id from moz_anno_attributes where name = 'downloads/destinationFileURI')
            and c.anno_attribute_id = (select id from moz_anno_attributes where name = 'downloads/metaData');
        """).fetchall():
            values = json.loads(download[3])
            ret.append( (download[0], download[1], download[2], values['fileSize'], values['endTime'], values['state']) )
        con.close()
        return ret

if __name__ == '__main__':
    profile = "C:/Users/USERNAME/AppData/Roaming/Mozilla/Firefox/Profiles/FF_PROFILE"
    ff = Firefox_data_generic()
    print 'version and paths:'
    print ff._get_info_from__compatibility_ini()

    print 'Master password is set:', ff.is_master_password_set(profile=profile)

    print "Test some password", ff.test_master_pw('test1234567')

    print 'passwords:'
    print ff.get_saved_passes(profilpath=profile, decrypt=True, masterpass="")

    print 'cookies:'
    print ff.get_all_cookies()

    #print 'form history:'
    #print ff.get_all_form_history(orderBy='name', True)
    print 'form history from search bar:'
    print list(ff.search_form_history(lambda x: 'searchbar' in x[0]))

    #print 'visited sites:'
    #print ff.get_all_visited()
    print 'visited sites with login in url:'
    print list(ff.search_history(lambda x: 'login' in x[0]))

    print 'downloads:'
    print ff.get_all_downloads()

It should work on Windows and Linux, but I just tested the changes on a Windows system.

Edit: I replaced the script to crack the passwords with one to just dump different information (including the passwords and usernames in decrypted form with a given password)


How to Build Pre-Master Secret I'm implementing a TLS-like system, which uses ECDHE-RSA-AE-GCM-SHA, and I've faced two interrogations.

At the end of the handshake ( and before the ChangeCipherSpec message), both the client and the server have to build the same Pre-Master Secret.

On what  data is based this secret ? Since I haven't found the answer in the RFS's (4492 and 5246), I'd say this :

the Server Public ECDHE Key (send within ServerKeyExchange message)
the Client Public ECDHE Key (sent, ciphered, with the ClientKeyExchange message)

It's, for me, the logical components, since Mallory couldn't retrieve the Client Public ECDHE Key, because encrypted with the server PublicKey. If yes, the signature of the ServerkeyExchange message would be wrong, and the Client would know that attempt.

I'm aware that this isn't a proper justification at all, and, when speaking of cryptography, these kinds of reasoning are bad (when not wrong), but since I haven't found the answer in the RFC, all what's left is here...

And moreover, what algorithm do we use to actually build the Pre-Master secret ? Is it a classical hash function (SHA, ...) ?

I know that SHA is used for expanding the MasterSecret (from the random numbers and the Pre-Patser Secret), but for its little brother I'm in the fog...

"ECDHE" means "ephemeral Diffie-Hellman (with elliptic curves)". This is what the pre-master secret comes from. The client generates a random DH key pair (a DH private key and the corresponding public key). The server also generates a random DH key pair. They send to each other the public parts of their respective key pairs.

The client uses its private DH key, combined with the DH public key from the server, to obtain the premaster secret.

The server uses its private DH key, combined with the DH public key from the client, to obtain the premaster secret.

By the magic of Diffie-Hellman, they both obtain the same value for the premaster secret. But, still by that magic, eavesdroppers, who only saw the public keys from both client and server but no private DH key at all, cannot rebuild the premaster secret.

("ciphered" is not a word; you probably mean "encrypted". But no, there is no encryption here. The DH public keys are public and, indeed, sent as-is over the wire.)


How can an NGO ensure secure mobile communication between HQ and their delegates in the field? I work for an NGO that does engineering projects in several developing countries. Our delegates who are doing the field work are for the most part not very tech-savvy, i. e. they wouldn't know how to set up GPG properly. We are rather small and don't have the possibility to provide a VPN connection. They do have their own smartphones and laptops with them.

How can we ensure secure, encrypted communication with our delegates in the field? An example would be secure submission of test results.

and don't have the possibility to provide a VPN connection

What has size (or budget) got to do with it? Both Android and iPhones (and many more mobile devices including Laptops running MSWindows, Linux of MacOS) provide PPTP, L2TP and IPSEC out of the box. They will also happily connect to HTTPS services.

The "server" end only needs an accessible IP address, a physical device and some software. And you must already have the first 2 if you are providing services such as email.

However if good rather than basic security is required then you should be looking at delivering a remote desktop type service - just delivering the display to the device - since you can't assure the physical security of the device, you cannot trust its integrity.

Trying to lock down the device, remotely manage it and maintain an encrypted filesystem is a common approach for enterprises (and required if you are going to maintain sensitive data on the device) but this is where the costs escalate even faster than the attack surface. A further issue is that this a BYOD model - why should you have control over a device not owned by you.

IMHO providing secure access to a centrally hosted user interface is more secure and cheaper. It also solves the ownership issue of BYOD.


What is more secure: single long hash, or combination of two shorter? Fictitious scenario:

User accesses a restricted data (available online) identified by random string (supported by captcha to make brute-forcing more difficult).

So data is not protected by a user/password account, but each case info is identifiable and accessible to all who know such random, unique string.

What is more secure:

single 10 chars random string (length is just for sake of example - could be longer)

sample:

YuE9sfQGf6
2 x 5 chars random strings

sample:

YuE9s
fQGf6

Let's say the allowed chars (in random string) are: a-z, A-Z, and  0-9.

Your "random strings" are what cryptographers would call keys: a key is a secret value with no implied internal structure (as opposed to a password which is "a key which fits in a human brain").

In your first case, users will be granted access based on their ability to present a specific sequence of 10 characters in the a-zA-Z0-9 alphabet. These are 62 possible signs, so there are 6210 = 839299365868340224 possible keys. An attacker trying to force his entry in will have to "guess" the sequence, which he cannot do except by trying possible keys in any order (we assumed "no implied internal structure", which means "uniform probability"). On average, the attacker will have to try half of the possible keys before succeeding, and that's 419649682934170112.

Now suppose that we are in the second case: the user will be accepted only if he enters two 5-character strings in two text fields. Both values are to be right if access is to be granted. In that situation, there are 625 combinations for each string, for a grand total of 625*625 = 839299365868340224 possibilities, which is exactly the same count as previously, so it does not matter.

That is, unless you botch it. "Botching it" would mean, here, telling the user if he got one of the two 5-character strings correct, even if the other is not. For instance, the two entry fields are in successive pages, and your server will show the second page only if the first string was correct. In that case, the attacker can crack both 5-character strings one after the other: that's 625/2 = 458066416 tries on average for the first string, then 458066416 again for the second string. The attacker then succeeds in (on average) 916132832 tries, i.e. 458066416 faster than with the non-botched implementation. That's what I call an epic fail. (Such a failure has already happened, from Microsoft themselves.)

It is simpler, and safer, to require entry of all 10 characters in one go. How you display them, as one text field, two text fields, or a bunch of heart-shaped balloons floating in the screen, has no importance, as long as you do not leak information about which ones are correct. The only information that the verification system should give is whether all characters were correct, or at least one was not.


GitHub pages and same origin I am working with the security team at my work to get a website accredited before I can publish it...It is a very simple webpage hosted on Github pages with only some javascript.

I kind of reached a roadblock in terms of creating the code to secure the website enough.
Since this is a community of security experts, I thought I would ask.

The problem is that according to security:

  the site is still has frameable response, to effectively prevent
  framing attacks, the application should return a response header with
  the name X-Frame-Options and the value DENY to prevent framing
  altogether, or the value SAMEORIGIN to allow framing only by pages on
  the same origin as the response itself.

So, I am trying to add all the security code that I can think of in terms of meta tags and script (this is github pages and I can't do any .htaccess)

Here are my meta. (I know some of them don't work on firefox or chrome, but I added anyway)

<meta http-equiv="Content-Security-Policy" content="
default-src 'self';
font-src 'self' https://fonts.gstatic.com;
frame-src 'self' https://a.tiles.mapbox.com https://docs.google.com/ https://www.mapbox.com;
img-src 'self';
script-src 'self'  https://ajax.googleapis.com 'unsafe-inline' ;
style-src 'self' https://fonts.googleapis.com/ 'unsafe-inline' ;
">

<meta http-equiv="Access-Control-Allow-Origin" content="Origin">
<meta http-equiv="X-XSS-Protection"  content="1;mode=block" always>
<meta http-equiv="X-Content-Type-Options" content="'nosniff' always">

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

<meta name="referrer" content="no-referrer" />
<meta http-equiv="X-Frame-Options" content="deny">

Then I added a script just after the head tag at the start of the page

<script>
 if (self == top) {
     var theBody = document.getElementsByTagName('body')[0];
     theBody.style.display = "block";
     }
  else {
    top.location = self.location;
     }
 </script>

I test locally, if a page tries to embed the website, it is redirected to the actual website.

Upon discussion, I still receive the feedback that

  Kindly check if SAME ORIGIN policy in place , this will may resolve the issue for remaining web browsers.

I am honestly a little bit lost on what else should i secure. I think the problem for the security team is that in the response headers they still see

access-control-allow-origin:*

any help is really really appreciate... what am i not understanding? which meta tags or javascript am i missing? is there a way to change access-control-allow-origin:* for github pages?
I love the security team and creating secure code... I don't want to frustrate them and myself more.

Any help is appreciated.

You can prevent clickjacking using the X-frame-options header as you mentioned but a more modern approach uses the CSP header. You best use both: CSP vs X-frame-options

Access-control-allow-origin:* should be avoided on state changing pages or private pages. Since you mention it is "hosted on github" I don't assume it has a dynamic nature and it will not accept request that modify state or show private info. Therefor the issue might be mute. The header allows another website to call your site and make the result accessible to the domain on which that site is hosted.

If you can explain what you site does, it might be clear what the impact is. I don't know if and how you can change github response headers. This post might be helpful

Specific to CORS on GitHub, it seems that all pages now return the wildcard source.


Does non-persistent data ever need to be encrypted? Does non-persistent data ever need to be encrypted?
If I had a project with confidential data stored in non-persistent class variables should I be doing anything to protect this data?

I am developing for an iOS application.

PCI DSS v3 section 6.5 calls out the need to protect sensitive data even if it is in memory, to help thwart memory scraping attacks.  So if you expect to need PCI compliance, yes, you should protect sensitive data even if it's in memory.

I don't know what technology you are using, but even non-persistent data can stick around for a while.  For example, strings in .NET don't get automatically destroyed when the all of their references are gone.  Strings are stored on the heap and will remain there until the garbage collector removes them.

Encrypting data in ram can be tricky since you now need to protect the encryption key.  A native feature like .NET's Secure String, or a hardware security module can be useful in such situations.

I have seen this finding on penetration tests.


Stolen Remote Desktop Protocol (RDP) credentials I would like to know how to guard against RDP-renting services such as dedicateexpress.com which rents out stolen corporate laptops credentials. Are there IDS for such events?

Truthfully the best way would to protect yourself from having your credentials stolen is to protect them.

If you are building a login script make sure the password is not hardcoded into the script.
Have a strong password against bruteforce
Change your password every 30 days or so (Windows has a built in reminder that can be turned on)
Do not share the password with anyone you do not trust
Keep your system up to date so all vulnerabilities are patched

  Are there IDS for such events?

I was not able to find one but you could use the RDP log file to make sure there is no intrusions (Depending on your windows machine the log system is in different locations. A quick Google search will find you the location)


Is my authentication method secure? I have built a web-facing tool which is mostly for internal use, but some of our clients will also make use of it. When building the registration/login parts I had a thought about who would be using it and how they would use it.

Often, there will be an account that is owned by a client, and the account will have many users, who will have varying levels of access to do things.

When a new user needs to be added to an existing account, there is a problem. I see a common situation in many other tools where an admin who is already authenticated (logged in) will have access to a "create new user" section where they can set up a new user, choose a password etc. and pass the new credentials onto the new user. This opens up more issues than I care to mention, but I'm sure anyone reading this can think of many.

I thought of the following alternatives

Admin creates the new user account and an email is sent to the new user who must then use a link in the email to set a password before the account can be used. I like this idea but a typo in the email address could give someone else access which is undesirable.
Admin creates a time-limited one-time-key which they can give to a new user. New user then enters their details on a registration form along with the OTK, which authenticates that user as being a member of the desired client/account.

The second option seems far better, the only thing being transmitted insecurely is the key which is single use and time limited, and can be redacted by the admin if necessary, but I haven't seen this method in use anywhere and wonder why.

Are there any flaws with this method that I have overlooked?

What other options have I not thought of?

You could  this the following way:

Instead of having the admin create the account and contact the user, have the user request access through a web form. The user can set an initial password right there, and also gives his e-mail address.

Then, the admin gets notified that there is a new user registration request which he has to approve.

The admin then needs to authenticate the user before approving him; this could be done by the system automatically verifying his e-mail address (depending on whether you automatically trust everyone at a given mail domain - I'd counsel against it), or by handing out one-time access tokens to specific people beforehand, to be entered as part of the registration form (much more secure).

So basically this is your solution, just with the initial contact reversed.

This reversal has one (slight) advantage: If you do verification automatically by e-mail, you've now solved the misspelled e-mail problem. Consider Alan Turing requesting access and misspelling his e-mail address so that the authentication request goes to Alai Turing instead. Alai might pretend to be Alan, but he won't be able to sign in, since he doesn't know Alan's password. You'll just have to make sure that passwords can't be reset until after the first successful sign-in (basically an account is only considered authenticated and active when both a sign-in and e-mail verification have occured)

Note that the automatic e-mail verification I described only protects against accidental misspellings of the e-mail address. If Alai signs up with the full intent of posing as Alan, this won't protect you.


What security policies and practices could one practice to safegaurd against being inebriated? My passwords for the most part as well as access procedures I could do while inebriated/intoxicated. Be it a simple login/password login to email or VPN and accessing a database.

This might sound weird but what can one do to help prevent access if one was inebriated via their own means or another person's means in order to get them to gain access?

I am not looking for practices and procedures for me (don't set up my intervention just yet!) but practices that could be applied to anyone not in a sound state of mind to prevent compromising a system they have access to.

I don't think there is one good answer but here are some suggestions. You could utilize a captcha with extra visual artifacts or more characters than normal on every login. Perhaps a simple riddle or a bit of javascript that forces a user to click on targets with a time limit like this. I think the most feasible, reliable option would be requiring two-factor identification with a PIN from a phone app that will only be displayed on the phone if the user passes a breathalyzer test. Such devices do exist for Android and at least one option exists for PC although I think a smartphone-based option is superior. Hopefully this helps or at least provides some additional ideas.


Does Google Assistant listen to everything? I just upgraded to Google Assistant on my phone, and it overheard me ask a colleague a question. It then searched it to try and find the answer. Does Google Assistant listen to everything? I definitely did not say "ok google". Even with a keyword, doesn't that mean it's listening to everything until you say the phrase "ok google" and that triggers the search? Is there any way to control when it listens or executes a search?

Yes, it does listen to everything but only activates and streams to Google on keyword activation. It has to listen all the time to trigger itself.

Once you say the keyword it will stream a few seconds before you said 'Ok Google' listen to your question then send the data to Google for an answer.

All this data is logged as well, here is a guide to find and delete voice recordings: https://qz.com/526545/googles-been-quietly-recording-your-voice-heres-how-to-listen-to-and-delete-the-archive/


Tracking unique web site visits without logging IP addresses On Monday, some IP address xxx.xxx.xxx.xxx visits my site. I log it.

On Tuesday, another IP address yyy.yyy.yyy.yyy visits my site. I log it.

If the two IP addresses are equal, I throw out the second one because I'm only interested in unique visits to my site. If they are not the same, I keep both in my log.

Question: Is it possible to do this without ever logging the IP addresses themselves, by using some kind of hashing/encryption, in such a manner that it is not possible to deduce the IP addresses from the hashed/encrypted data?

At first glance, it seems to me that this would be impossible, because you can always brute force all the possible IP addresses into whatever hash/encryption scheme you're using, until it matches your hashed/encrypted data - and thus deducing the original IP address.

But I hope I'm missing something. Maybe it's possible to bring time into this to make this achievable somehow?

I'm not knowledgeable enough in security to know the possibility or impossibility of this. Any advice would be appreciated.

Additional information: I'd like to store as much information as possible (without, of course, being able to deduce the original IP addresses). For instance, I may not necessarily want to store merely the all-time total of unique visitors. Instead, I may want to know the total unique visitors during a particular day, week, or a month. So actually storing all of the encrypted/hashed IP addresses would be important. So, in this sense, I was wrong when I talked above about "throwing out the second one".

Note: I'm looking for some scheme under which nobody, not even me, can deduce the IP address. Some solutions have been provided that are such that I can myself technically deduce the original IP address, but I don't even want ability to do so myself. This sounds impossible, but who knows. Maybe some trickery exists out there for achieving what I want?

First of all: Why are you so concerned with not storing IP addresses? It's not private data; the OS or NAT router happily includes it with every sent packet. Okay it's kind of necessary, but what I mean is that they aren't really private. Also, random IPs are not really useful for hackers, and it's not a privacy concern when you can only see them yourself.

Secondly, it's not really useful to save IP addresses with the goal of counting unique visits. Not only can one IP have hundreds or thousands of users (like schools), but a single user can also easily occupy a /16 subnet or two (many people's IP changes every few days or so), not to mention laptops and mobile phones. A better technique would be session cookies, which are unfortunately restricted to the browser (and thus one device, so not counting people but the number of browsers really), but it's a lot better than IP addresses.

Lastly, if you still want to go with storing IP addresses, there are basically two ways:

Bloom filter, as mentioned before. This is not 100% correct though, but probably good enough for this purpose.
Using a hashing function which takes forever to compute. Sha-2'ing the IP a couple million times, it's impractical to brute-force it.

(There are about 3.7 billion globally usable and unique IP addresses, so if it takes 50ms to compute one hash, it takes 2.9 years before you have 50% chance of brute-forcing one of them, not taking Moore's law into account.)


How to know if there is an audio hidden message in an audio file? Can we hear it? How many types for hiding audio in an audio file are there? And would we be able to realize or hear an hidden audio message in a song in all types of steganography?

An MP3 file consists of many frames. A frame is a piece of data of about 1000 bytes long, with a little sound data in it. Each frame consists of a header and some data. The header contains the bitrate for the frame, whether the sound is in stereo, and so on. A player plays a file by looking for these headers, decoding the frames and playing the sound.

You can put any data that does not look like a frame header in between the frames and the file will still play correctly. The player simply ignores your data and searches for the next frame when playing. By hiding data in between the frames, the sound is not modified at all.

Another way is to use some bits in the header to hide the message. The "private" bit, for example, is unused by most applications and can be used to store a bit of data. This would go unnoticed when playing the file.

If you want to hide data in the sound data itself, you have to change the sound data a bit to contain your message. Whether this is audible depends on how much the original data is changed, and whether it is done with knowledge of the MP3 specification.


Unable to use PUT method on server seemingly allowing PUT I've just scanned a target and noticed that HTTP PUT is allowed.

So, just to verify I used nmap:

# nmap --script http-methods <IP>

Starting Nmap 7.25BETA2 ( https://nmap.org ) at 2016-11-11 15:05 CET
Nmap scan report for <IP>
Host is up (0.16s latency).
Not shown: 989 closed ports
PORT      STATE SERVICE
21/tcp    open  ftp
22/tcp    open  ssh
23/tcp    open  telnet
25/tcp    open  smtp
80/tcp    open  http
| http-methods:
|   Supported Methods: GET HEAD POST PUT DELETE CONNECT OPTIONS PATCH PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK TRACE
|_  Potentially risky methods: PUT DELETE CONNECT PATCH PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK TRACE
111/tcp   open  rpcbind
139/tcp   open  netbios-ssn
199/tcp   open  smux
443/tcp   open  https
| http-methods:
|   Supported Methods: GET HEAD POST PUT DELETE CONNECT OPTIONS PATCH PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK TRACE
|_  Potentially risky methods: PUT DELETE CONNECT PATCH PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK TRACE
995/tcp   open  pop3s
32768/tcp open  filenet-tms
MAC Address: <MAC> (VMware)

Nmap done: 1 IP address (1 host up) scanned in 10.47 seconds

Great. So that would mean that I can upload files using the HTTP PUT method.

I tried using curl:

# curl http://<IP>/ --upload-file ./test.html
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<TITLE>403 Forbidden</TITLE>

Forbidden

You don't have permission to access /test.html
on this server.

<ADDRESS>Apache/1.3.23 Server at 127.0.0.1 Port 80</ADDRESS>

and nmap again:

# nmap -p 80 <IP> --script http-put --script-args http-put.url'/',http-put.file='./test.html'

Starting Nmap 7.25BETA2 ( https://nmap.org ) at 2016-11-11 15:09 CET
Nmap scan report for <IP>
Host is up (0.15s latency).
PORT   STATE SERVICE
80/tcp open  http
MAC Address: <MAC> (VMware)

Nmap done: 1 IP address (1 host up) scanned in 7.10 seconds

So apparently PUT is allowed, but I can't use it. Am I doing something wrong or are there other safeguards in place, which I'm not aware of?

What you see in the nmap scan is the response to an OPTIONS request. It simply says that these are the things the webserver will accept (i.e. are not disabled).

That does not mean that the webserver has a means for implementing those requests; typically PUT/POST/DELETE will be handled by some sort of logic engine outside the webserver itself. Similar for the webDAV commands - but these will usually only be exposed where webDAV is explicitly installed (the webDAV module is an external component).


Directory names using extensions a security risk? In our app (PHP, MySQL) we allow users to create templates which are stored in their own subdirectory (which is named by the template name).

Someone suggested to use standard file name sanitization but I am not too comfortable to allow user to name their template 'mytemplate.php'

IS allowing extensions on directory names a security risk?

Well, renaming only the folder  is more a matter of good practice. In the case you want the user to access his template folder like: site.com/templates/mytemplate.php; I would recommend you implement "Friendly URL" (Semantic URL), so in this case you would pass the 'mytemplate.php' like a variable and not like a folder name.


Will installing a Graphical User Interface in a server be a security problem? I'm not a CLI-lover, sometimes I prefer to do some tasks in a server using a GUI rather than using the CLI (it speeds up my work), but I don't know if installing a GUI and accessing it using VNC and SSH will compromise the server security.

Every new service or program can pose a new security risk because they can have their own vulnerabilities. X11 has their own CVE's, for instance. Then when you access it over something like VNC, you introduce other potential problems and possibilities for misconfigurations.

So, yes, there are inherent risks, but nothing specific for GUIs.


Is it secure to make user able to disable 2FA with 2 security questions if they have lost backup codes? I am developing an application and users are able to add 2FA to their account. however if a user has lost backup codes of 2FA and logged out of account on all of devices, is it safe making them able to disable 2FA using pre-set 2 security questions ?

I wouldn't say using security questions for pretty much anything is "secure".

There have been so many compromises of personal information, ranging from financial (Equifax) to social (Facebook) it's not unlikely that answers aren't compromised.

Questions like mother's maiden name, school history, first car, etc. Could be part of a breach, or phished out of an email or dating app (commonly show occupation and education history by default now).

The ability to bypass or disable 2FA is one of the current weaknesses in how it's been employed recently. Depending on your resources I would suggest a few alternatives.

Let them pick 'nothing' (and the account is forever locked)
Consider allowing users to use their Google/Facebook accounts to login (you don't hAve to worry about 2FA as that's Google/FBs issue)
let them specify a recovery email (other than their normal email, which gets recovery email)
send a physical letter to the account on file
send an email/call/SMS then wait a period of time (days) and if you don't hear back from the account owner allow a login without 2FA (idea is they would respond if the attempt was invalid/not from them).


How to verify email addresses in GnuPG UIDs? I have been reading up on key signing policies and best practices.  Something I have been unable to figure out is how to verify the email address attached to a UID of a GnuPG key.

I can verify the name using an ID, but how do I verify the email address?  I am not just trying to determine that the address is valid, but also that is belongs to the person who controls the private key.

The most common case I've seen so far is to sign the key and then send the signed key (well, just the single signature) via e-mail to the purported e-mail address. If there's more than one e-mail address on a key, to each address you only send the signature for this address, encrypted with their public key. Do not upload the signature to a key server or make it available otherwise. Then either the person receives the signature and is able to decrypt it and everything is fine, or they don't and you don't care.

This of course only solves the problem in the keysigning party case (or similar), e.g. you certifying to other people that the ID consisting of name (which you checked with an ID document) and e-mail address (checked with the above protocol) is correct. To be sure yourself you would need to delete the signature locally (or not import it into your keyring in the first case) and then wait until the recipient has uploaded it to a keyserver.

There's a tool that implements this protocol: caff.