Estimate the time to crack passwords using bcrypt I am reading on the Ashley Madison password exposure case. Dean Pierce was able to output about 4000 cracked passwords within 5 days given his system. I'm assuming that he generated a table of hashes to compare 1 to 1. My question is, how long does it take to crack or fully test a bcrypted password given any cost [n]?

In June 2015, using eight GTX TitanX video cards, they were able to get hashcat to perform:

14,455 hashes/second (cost factor 5, i.e. 32 iterations)

With a rig of 8 video cards, they got:

155,642 hashes/seconds (cost factor 5, i.e. 32 iterations)

Of course nobody actually ever used bcrypt with a cost factor of 5.

At the time of publication of BCrypt (1999) the default costs were:

Normal User: 6
Superuser: 8

And also:

  "Of course, whatever cost people choose should be reevaluated from time to time."

The question is how long should a hash take to compute. At the time of deployment in 1976, crypt could hash fewer than 4 passwords per second. (250 ms per password)

In 1977, on a VAX-11/780, crypt (MD5) could be evaluated about 3.6 times per second.   (277 ms per password)

You should be adjusting your bcrypt work factor so it takes 250-500 ms to compute.

Our implementation uses the cost factor 11 as a lower bound. And it then benchmarks the system, increasing the cost if it's being computed too fast.

And the function to check a password forces you to deal with the consequences of that:

Boolean passwordRehashNeeded;
BCrypt.CheckPassword(rawPassword, savedHash, out passwordRehashNeeded);

Sometimes a re-hash is needed:

because we're going from 2 -> 2a -> 2x -> 2y -> 2b -> ...
hardware is too fast these days, and is calculating your saved hash in 230 ms

Hashing speeds

Back to the question of time to crack. For different bcrypt cost factors, the CPU a the eight video card monster, the hashing speeds are:

| Cost |             Hashes/sec         |
|      | i7-2700K@3.5GHz | 8xGTX TitanX |
|------|-----------------|--------------|
|  5   |        384.04   |  115,642.00  |
|  6   |        192.02   |   57,821.00  |
|  7   |         96.01   |   28,910.50  |
|  8   |         48.00   |   14,455.25  |
|  9   |         24.00   |    7,227.63  |
| 10   |         12.00   |    3,613.81  |
| 11   |          6.00   |    1,806.91  |
| 12   |          3.00   |      903.45  |
| 13   |          1.50   |      451.73  |
| 14   |          0.75   |      225.86  |
| 15   |          0.38   |      112.93  |
| 16   |          0.19   |       56.47  |

Time to crack

The time to crack a password depends on the password. We all know that corporate password policies forbid strong passwords.

If it's a password being enforced by a corporate policy of complexity and expiration, then it will by definition be a weak password, and be broken much more easily.
If it's a password that follows best practices (*e.g. no complexity requirements, no forced expiration), then it will be much stronger.

For example:

Weak: Tr0ub4dour&3 (e.g. 1011 bits)
Strong: correct horse battery staple (e.g. π40.89316, aka 1020.33003 bits)

The passwords demanded by security auditors are intended to weaken the system:

| Cost |   Time to crack - 8 way GTX TitanX       |
|      | PCI-compliant password | Good password   |
|------|------------------------|-----------------|
|  5   |                 5 days |       29M years |
|  6   |                10 days |       59M years |
|  7   |                20 days |      117M years |
|  8   |                40 days |      234M years |
|  9   |                80 days |      469M years |
| 10   |               160 days |      937M years |
| 11   |               320 days |    1,875M years |
| 12   |               641 days |    3,750M years |
| 13   |             1,281 days |    7,499M years |
| 14   |             2,562 days |   14,999M years |
| 15   |             5,124 days |   29,998M years |
| 16   |            10,249 days |   59,996M years |

NIST says your password policy is terrible

In 2017 NIST even reminded auditors how dumb their password polices are. The better password rules are:

no complexity requirements
no forced expiration
allow any character (e.g. correct horse battery )
check passwords against corpus of previous breaches
minimum of 8 characters
no SMS 2FA
no What is the eye color of your first pet's favorite maiden name?
no password hints

Personally, I believe that a password policy should be:

password is estimated to take 50 years to break

Getting a password to take an estimated 50 years to break is ridiculously easy (once you teach people that everything IT told them about passwords was wrong.) And as a bonus:

it exceeds most statue of limitations
and hopefully i'll be dead in 50 years

tl;dr: Don't be one of those people who caves when HIPPA, or PCI, or other regulators who come in demanding password complexity and regular expiration requirements. You're just encouraging the idiots, and making the world less secure.

Diatribe about correct horse battery staple

It may be a well known password, but it is not a commonly used one.

For example, Intel's World Password Day 2014 gives the example password:

Compl3xity < Length!

Nobody is arguing that zxcvbn should recognize this is a commonly used password.

And rightly so: it's not a commonly used password!

zxcvbn is intentionally limited to the top 30,000 passwords:

     1: 123456          55893
     2: password        20785
     3: 12345678        13582
     4: qwerty          13230
     5: 123456789       11696
     6: 12345           10938
     7: 1234            6432
     8: 111111          5682
     9: 1234567         4796
    10: dragon          4191
         ...
 11577: hunter2         44
        ...
 28871: hunter22        17
       ...
 29998: scoubidou2      17
 29999: benelli         17
 30000: vasilina        17
        ...
 47022: dimazarya       11
 47023: xpcrew          11

The fact is: correct horse battery staple does not belong in the list of top 30,000 passwords: because it simply is not in the list of the top 30,000 known passwords.

In fact, i would be willing to go far as you say that's it's not used by anyone.

It is no more common that the other extraordinarily well-known password:

173467321476C32789777643T732V73117888732476789764376Lock


What kind of hash does the VeraCrypt tool use? Whirlpool? SHA-512? Or something completely different?

Veracrypt is supporting multiple hash algorithms, which are listed in the documentation.

It supports the following Hash Algorithms:

RIPEMD-160
SHA-256
SHA-512
Whirlpool
Streebog


How wifi sense actually connects to any network? I read that using Wi-Fi  sense, we can share our Wi-Fi  networks with others and it stores pre-shared keys on Microsoft servers. Please help me understand the below scenario:

I am sharing my network (using Wi-Fi  sense) and my Facebook friend who uses windows 10 comes over. How does that person connect to my network automatically if he/she is not connected to any network in the first place? How will my Wi-Fi key be sent to that person's machine before even connecting to the network?

How does that person connect to my network automatically if he/she is
  not connected to any network in the first place?

From Wi‑Fi Sense FAQ in section What does Wi-Fi sense do?, it says that your friend can connect to your network only after he has   shared at least one network with his contacts.

  How will my Wi-Fi key be sent to that person's machine before even
  connecting to the network?

It comes down from a Microsoft server in encrypted form, and is decrypted behind the scenes.

He won't receive it until he tries to get connected to your network. I think it is better if I quote you directly this from the FAQ I mentioned. It shows how Wi-Fi sense determines available Wi-Fi hotsports to which your friend may connect to your shared network:

  Wi‑Fi Sense has a database of information about open Wi‑Fi
  hotspots—and we update that crowdsourced information based on what
  your PC and other participating customers' PCs tell us about those
  networks. Wi‑Fi Sense analyzes some characteristics of open Wi‑Fi
  networks that other Windows customers have connected to and determines
  if they had a good-quality connection. If enough of them did, those
  networks are added to the database and are suggested by Wi‑Fi Sense.
  You and others then get connected to a suggested network when one of
  them is in range.

The very detailed process is not something Microsoft will publish.


CDNs used by Windows Update My question is about CDNs (Content Delivery Networks) and their simultaneous use for legal and questionnable stuff. One specific example is the following.

I'm noticing taffic from our network to the following IP address: 8.26.202.125 . I see from http://robtex.com that this IP address belongs to a CDN provider (Level 3 Communications) and that the IP seems to be used a lot for porn stuff, via rncdn1.com sub-domains among others (see http://www.robtex.com/ip/8.26.202.125.html#ip).

Thinking that I had infected machines in our network (one of the source was a Windows server, and our sysadmins are not addicted to porn!), I fired up Wireshark to find out the contents of the packets. The packets contained what seem to be valid Windows Update requests:

    HEAD /v9/windowsupdate/redir/muv4wuredir.cab?1204161927 HTTP/1.1\r\n
    GET /v9/windowsupdate/a/selfupdate/WSUS3/x86/Other/wsus3setup.cab?1204161927
    HTTP/1.1\r\n
    GET /msdownload/update/v3/static/trustedr/en/authrootstl.cab HTTP/1.1\r\n
    .
    .
    .

I know that these can be good-looking requests that are in fact "bad stuff hidden", but I'm wondering: could this be valid traffic and it's just Microsoft using this CDN for its updates? I find it weird that Microsoft would use a CDN that is also used to serve porn stuff. But then again, we've seen stranger things :-)

Thank you.

According to this interesting technical paper Microsoft do indeed use Level 3 as one of their CDN partners.

As to why Microsoft use someone who also serves porn, they probably don't have a lot of choice. There aren't very many CDNs operating at that kind of level, and most of the customers for that sort of service are porn sites. According to this even more interesting report, YouPorn alone takes up 2% of the Internet's traffic. To Level 3 Microsoft are, relatively speaking, small fry.


Do mail servers follow links in emails as part of a security scan before inbox delivery? I've implemented a passwordless login using a magic link and email. The link can be used only once. One customer is complaining that once they click the link, the page reports that the link is already used. This is indeed what I implemented, but I'm convinced they actually click each link just once. I was in direct contact with the user.

We cannot reproduce this behavior (it works on my computer), so I checked the logs. From what I gathered from the logs, I suspect that some automated mechanism is clicking the login-link before delivering the email to the inbox. Once it reaches the inbox and the user clicks on the link, they're actually the second one clicking it. Some automated tool did it first, then the user does it second.

Here's what raised my suspicion in descending order of contribution:

there's an average of 2 seconds between submitting the email address
and clicking the link in the email. Albeit not undoable, it takes some unlikely amount of effort to accomplish that by hand.
the email address was submitted from a completely different IP address from where the link was clicked. Geo-IP tells me that requests are all made in London, but the link is clicked in the US. Same user, next attempt 5 minutes later request from London, but this time clicked in Germany.
the email address was submitted from a different browser than the browser used to open the link (Chrome vs IE11).

Do mail servers actually follow links in emails as part of a security scan before inbox delivery? If so, what's a recommendable way to make one-time links work when used with such environments?

PS1: This customer works for a large multinational company.
PS2: I'm aware of the pros and cons of passwordless logins.

This is not a new problem.

I haven't had to work around it in a few years, so I don't know if the state of the art has changed, but there are a few things you can try:

1) don't process your link unless it has a special query param in it.  The query param is added by a client-side redirect (I used http://insider.zone/tools/client-side-url-redirect-generator/ to handle some of the cross-browser messiness) but the server-side code would return this with the query-paramless link to the browser.  So:

  user clicks 'https://magiclink.foo.org/ajskdfjwlakefj'

server does not see magic redirect, so

  redirects to 'https://magiclink.foo.org/ajskdfjwlakefj?follow=true'

and server-side code, seeing "follow=true", would process and then invalidate that token.

2) I think you could do the same with a redirect from GET->POST with a form submit, but I haven't tried.

Good luck!


Certificate chain and permission to revoke We have given a certificate chain: X <-- Y <-- Z (X is an end-entity cert, Z is root CA).

Certificates are extended with CRL distribution points info. Because of the fact Y -> X Y is a CA for X. Therefore, Y can revoke X 's certificate by placing it on Y's CRL.

Z is  CA for Y. Z can revoke certificate Y. But, the question is: can Z revoke certificate X?

Short answer: NO, Z can't revoke X directly.
Exception: YES, if Z's CRLs are, due to prior arrangement between Z & Y, in the CRL Distribution Point list of X's certificate that was issued by Y.

RFC5280 refers to this as "Indirect CRL" - where Z can issue a CRL that includes certificates issued by Y. It only works if the verifier knows where to check. The "CRL Distributions Points extension" of certificates is the place they (ought to) look.

It is well known however, that most certification verification algorithms are not strictly quality checked against the standards - and hence this system is fallible to a non-negligible extent.


XXE Injection in docx: entity not defined My goal is to create a docx file that, when uploaded to a server and parsed there, causes the parser to fetch my url so I know it worked.

Unfortunately, I only have Libre Office and not MS Office at my hands. When I open the file with Libre Office, I get an error:

  SAXException: [word/document.xml line 2]: Entity 'xxe' not defined

Seems like I did something wrong with my XML syntax, but I can't figure out what.

The document.xml in the file starts like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><!DOCTYPE foo [ <!ENTITY xxe SYSTEM "thisismyurl">]><w:document (...)

(Replaced my actual url for readability)

And then later, I have:

<w:t>&xxe;</w:t>(...)

I created my file with docem. Using the predefined docem payloads results in the same error. Any idea what could have gone wrong? Thank you a lot!

You probably are supposed to get an error. You just injected "something" into the xml parts of the docx file which the application(Word or Libre) isn't used to reading and thus it doesn't understand how to process and display that. If you're trying to test it, you should be uploading it to a Test Server with a vulnerable parser and then check for any pingbacks to your Server/Url.


What is sizeofblock used for in image_base_relocation table? I am looking at the dll loader in carberp and there is this line i dont understand.

for (DWORD i = 0; i < ((Relocation->SizeOfBlock - IMAGE_SIZEOF_BASE_RELOCATION) / 2 ); i++, RelInfo++ )

You can have a look at the source code on the link below.

https://github.com/hzeroo/Carberp/blob/master/source%20-%20absource/pro/all%20source/BlackJoeWhiteJoe/Source/DllLoader.cpp

I mean i understand the for loop, but what is "sizeofblock- image_sizeof_base_relocation / 2" .

Please help.

According to MSDN : (go down to PE File Base Relocations part)

The relocation section is array of blocks, each one contains:

(IMAGE_BASE_RELOCATION, relocations binary chunck)

In order to calculate how many relocations in specific block you need to take SizeOfBlock out of IMAGE_BASE_RELOCATION subtract the size of an IMAGE_BASE_RELOCATION and split by each relocation size (which is sizeof(WORD)=2 bytes):

(Relocation->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD)

hope this help you


Can anti-CSRF token prevent bruteforce attack? I am not much experienced with brute force attacks but I was wondering

Suppose, you have a website www.example.com and you want to do brute force attack on that login form but that login form is protected by anti-CSRF token.

Is it possible to do brute force password on the CSRF protected form because a unique key created every time ?

on
AntiForgeryToken versus Captcha

It is written there automated submissions are possible on CSRF protected form but I was thinking If I tried to do brute force than I have to create a valid request.

For example :

  http://example.com/login?usrname=[brute]&password=[brute]&anti_csrf=xydh732-7vdbd

than I will use this request to brute force but this anti-CSRF token will expire
after a single request than how can a brute force attack brute username and password?

Simple. You read the anti-CSRF token from the newly requested login page and each time the token is attached to the server's response. In this case, before you submit a POST request, you first read the response to your GET request from the server and the new token will be attached to it. Then you use it to generate new brute-force POST request. There may be other problems you'll come across, like say request rate limiting and so on, but the anti-CSRF token itself doesn't protect against brute force attacks.


Can you get a virus from sending a GET or POST request? If I need to fix up my question in any way please let me know, this is my first question on the site

So there's a game development website I use where you can develop with other people, and within the past few months they introduced a new feature where you can get into the editor with other people. Now, here's the thing. They heavily sandbox things, and for good reason, so in game you can't send http requests from a user's computer, but due to how the game creation tool works, there's a small bug that would allow you to do this.

The worst thing I've thought of being able to do with this is snag someone's IP, which isn't exactly a terrible thing, it's a public IP afterall, but I'm curious if it's possible to infect their computer, give them a virus, or anything else damaging, just by having them send a GET/POST request to a website, and if so how this would work?

I want to convince the creators/designers of the site and development tools to make a fix for this, and a real threat would help my argument a lot. But I can't make the claim without evidence. Is there any real threat to the person sending the request here?

Yes, it depends how that GET/POST request is handled on the receiving party, i.e the client.

While explained in another thread "Yes, you can get a virus just by visiting a site in Chrome or any other browser".  This also counts for any client.  In this case: the program that's handling the response from your web request. No matter if that's a browser, CLI program, library, game, etc.  If a vulnerability exist in the client code which can be exploited, malicious code can be executed.  This malicious code is roughly what you refer to as "a virus".

There are mitigating factors such as isolation, exploit mitigation (DEP, ASLR, ...) but there's always a possibility that this is bypassed.

The worse thing that can happen is that an attacker can execute code on a victims machine, elevate privileges and execute system commands.  Examples?  Steal data, delete files, launch further attacks, ... If someone can execute code it's a complete compromise.


is Cryptpad safe for corporate use (logs which includes hostnames, IP and internal configuration) We don't have an internal Gist for fast sharing snippets and logs extracts with co workers.

Is it safe to use this web service?

quote from GitHub site:

  CryptPad is private, not anonymous. Privacy protects your data,
  anonymity protects you. As such, it is possible for a collaborator on
  the pad to include some silly/ugly/nasty things in a CryptPad such as
  an image which reveals your IP address when your browser automatically
  loads it or a script which plays Rick Astleys's greatest hits. It is
  possible for anyone who does not have the key to be able to change
  anything in the pad or add anything, even the server, however the
  clients will notice this because the content hashes in ChainPad will
  fail to validate.

  The server does have a certain power, it can send you evil javascript
  which does the wrong thing (leaks the key or the data back to the
  server or to someone else). This is however an active attack which
  makes it detectable. The NSA really hates doing these because they
  might get caught and laughed at and humiliated in front of the whole
  world (again). If you're making the NSA mad enough for them to use an
  active attack against you, Great Success Highfive, now take the
  battery out of your computer before it spawns Agent Smith.

  Still there are other low-lives in the world so using CryptPad over
  HTTPS is probably a good idea.

Disclosure: I'm a developer of CryptPad.

The answer to your question is based on how much assurance you need. The idea of CryptPad is to be verifiably ethical, we can prove that we are not doing mass data collection because if we were, somebody would catch us eventually. Therefore we are verifiably better than almost every other service available because with CryptPad, you are not blindly uploading your data and trusting us never to go in the database and read it.

We cannot (at this point) prove that we are not going to leak your data, if for some reason we were very interested in you, we could conceivably take the risk of being caught serving evil javascript in order to get access to your data.

tl;dr it is better than virtually any cloud server available but not better than hosting on your own infrastructure. However if you do choose to host something on your own infrastructure, you may still want to use a Zero Knowledge solution such as CryptPad unless you really trust your system administrators.


XSS in options tag without forward slash I am trying work on an XSS scenario. Would appreciate if anyone can help.

URL: www.example.com/mydata

"mydata" is landing in html as follows:

200 OK
...
Content-Type: text/html; charset=utf-8
...
...
<select>
<option value="mydata"> Anything</option>
</select>
......

Since the "mydata" is in URL I cannot use a payload with forward slashes. Thus, I am not able to use script tag to execute script since I am unable to close it without forward slash. Other payloads like <BODY ONLOAD=alert('XSS')> are not working with options tag.

Does anyone know a way to introduce xss in this scenario?

You have at least basic XSS:

...
<select><option value="XSS"><input type="image" src="https:\\happyorhungry.files.wordpress.com\2011\10\cookie_monster_original.jpg">Anything</option></select>
...

Where your input is:

XSS"><input type="image" src="https:\\happyorhungry.files.wordpress.com\2011\10\cookie_monster_original.jpg


Functional Google 2FA code (via SMS) received from a random (but in use) mobile phone number tl;dr for those who are misunderstanding my post: imagine your friend who uses GMail suddenly tells you they have 2FA enabled, and logged in to their account, and that the 2FA code (SMS) they received upon requesting it came from your number. That would be impossible, right? That's what happened here, except it wasn't between two friends in this case, but between me and a complete stranger.
Original post:
I have a Google account, and for various reasons, I decided to activate 2-factor authentication (2FA) for my account (i.e., input your password, and confirm the login by typing in a 6 digit code sent to your registered mobile phone number). I did this about a month and a half ago.
The first few codes I received came from a sender identified as "Google" by my phone/service provider. Then, on the 21st of January 2020, I received the 2FA code from a mobile number, when I tried to log in. At that time, I didn't think much about it. I just presumed that Google was probably using a couple of additional numbers and whatnot as backups when there were too many 2FA codes to be sent out or whatever. However, I did retain the SMS, as I was surprised to receive it from what was clearly a regular mobile phone number.
Since then, every single 2FA code I've received has been sent by "Google", and I've never received another code from a mobile number of any sort (or for that matter, from a sender with an identifiable number). Being a bit curious, I called that random number from which I had received the code then, and much to my surprise, somebody actually answered.
They seemed equally surprised by the fact that I had received a 2FA code from their number, and were utterly confused. They gave me their first name and location, and told me I could find them on WhatsApp (which I couldn't; I tried using another person's phone to try and find them on WhatsApp, but that didn't work either).
I am really confused now, and I thought I'd turn to the SE community for some inputs.
Some information that might be pertinent in this discussion:

All the "regular" 2FA code messages are always in English (here's the newest one here; I always delete the messages once I use the code, which is why I don't have a history here).

The errant code I received was in German (I live in Germany, the sender's number is also a German number; the person I spoke with confirmed it by stating where they lived). The person told me that they use Google (Gmail?) as well. A text I sent them (after we spoke) asking if they are actually reachable on WhatsApp can also be seen in the screenshot below (I haven't received a response as of the time of writing).

The errant code worked. I had logged in successfully with it, which is what surprised me the most.

I received a "Critical Security Alert" from Google on the 19th of November 2019: "Google noticed unusual activity in your account. Someone else might have signed in and deleted emails. Review your account activity to make sure no one else has access." However, as far as I could tell, I did not lose any data, and I did not see any suspicious activity either, and this was long before I even activated 2FA anyway.

I don't see anything unusual in the Google Accounts Security page.

As far as I know, none of my accounts (with Google or elsewhere) have been compromised.

If it helps, I use Ubuntu 18.04 on a Lenovo Thinkpad X230 at home (and another Ubuntu 18.04 machine at work). My phone is a ZTE Axon 7 running Android v.7.1.1 (there is no way for me to update it!). I can provide a list of apps and the likes if that will be helpful.

My question is: what is going on? Is it possible for a 2FA code to be sent like this?

The SenderId of an SMS can be easily spoofed by anybody betweeen Google and your phone. Note that Google does not directly send you an SMS but uses service providers that have network connections (maybe indirectly) to your phone. And since the Telcos between Google and your phone want to filter out non-person-to-person traffic (because of $), it makes sense for someone on the route to make the SMS look like person-to-person (p2p) traffic by choosing a (random) SenderId that comes from a p2p number. And if that number is already in use, even better. :-)

I work at an SMS aggregator who develops 2FA, delivers SMS for 2FA, uses SMS routes, and has heard of SenderId spoofing.


gpg2 export-secret-keys I created a master gpg key and additional signing subkey as described on Debian wiki page. I also moved the whole .gnupg directory to /my/save/place and deleted the primary key from the original .gnupg directory. So far so good, gpg2 -K shows a sec# instead of sec and gpg2 --homedir=/my/save/place -K shows sec as expected.

Hovewer, if I run gpg2 --export-secret-keys --armor and gpg2 --homedir=/my/save/place --export-secret-keys --armor both commands return something. Although results are different.

Could you please explain what exactly is returned in the former and the latter cases?
What command one should run to get a private key to save with paperkey afterwards?

Where you have the full copy of your key requesting to export the secret key will export the secret master key plus any subkeys, the corresponding public keys and signatures by the master key on the subkeys.

Where you have removed the private master key you will get all that minus the private master key.  That is you'll get any subkeys (public and private), signatures on them from the master key and the public master key (necessary to validate the subkey signatures).

gpg2 --homedir=/my/save/place --export-secret-keys should produce something suitable for paperkey


What software can be used to read data from smart cards? I have recently got this smart card reader. In the description it says that it can be used to read data from fidelity smart cards, library cards, etc.

The technical card compatibility support is as follows:

Supported Smart card: microprocessor smart card ISO7816 1, 2, 3, 4 (protocols
T=0 and T=1, PPS in writing and reading phase) with MCU power supply at 1,8V,
3V, 5V
Supported memory cards: I2C bus (from 1K bit up to 1024Kbits)
Support: the secure memory (Atmel AT88SC153, AT88SC1608, SLE4418/28, SLE4432/42)

I do not have any specific goal in mind, just wondering it would be cool to use the card reader to read data from various cards that I have in house, library cards, transport cards, shops loyalty cards,etc

Beside the card reader what do I need to read data from a smart card?
Are there some software, coding library, to access the data from generic cards?

Thanks, any idea would help.

In the past, i have used CardPeek for this. It is easily extensible through LUA and can therefore adapt to unknown cards. It presents the "files" on the card via a TreeView and offers annotations on "known" cards for the values.

It also has debugging facilities.


Is there any ways to track which certificate is used for https connection in browsers? I encounter a strange SSL error messages in Mac laptop with https connections.

It only happens on some websites such as facebook, twitter with Firefox and Chrome and only happens at work.    It is likely IT is doing sniffing the https traffic with firewall, since the same websites/browser/system works just fine at home internet connection.

Even stranger, with Safari those sites work just fine  at work.

Is there anyway to get details on which certificates, CA were used by various browsers that authenticates the websites.

Yeah, that sounds like IT is man-in-the-middle'ing your HTTPS traffic. Although other things could cause that behaviour also.

I suspect IT has installed root certs into OSX for HTTPS inspection. The clue is that Safari will get its list of trusted root certs from the operating system, while Firefox (and Chrome?) have their own list embedded in the program.

To check, inspect the certificate offered by facebook, twitter, etc in the browser and see if they match.

Chrome

Source

Safari

source

Pay special attention to the Issuing and Root CAs to see if this looks like some sort of internal corporate CA. (I would show you the cert I see for comparison, but unfortunately, my company also uses an internal CA to do HTTPS inspection...)


Refreshing Access Token with Access Token Does it make send to allow a web client app (JavaScript) to refresh Access Toke using Access Token (not Refresh Token) that is about to expire?
What are the drawbacks of using this process?

In fact, you surely must do this in all normal processes. Otherwise, you are forcing your users to go through a full login again.

Given the weaknesses of web tokens like JWT (e.g prone to main-in-the-middle capture and replay attacks), keeping token expiries short is a must. This reduces at least, the opportunities for an attacker to obtain a valid token (via a MiTM attack), and then using it in a replay attack.

If you want to increase token expiry times, you need to add further protections to the communications process such as passing encrypted signature type data such as IP addresses to reduce the risk of a replay attack.


Find out the least insecure mutual cipher algorithm I have set the cipher algorithms for ssh on my server to just chacha20-poly1305@openssh.com, aes256-gcm@openssh.com and aes128-gcm@openssh.com

Now my IntelliJ fails with this error:

  failed: unable to reach a settlement: [aes128-cbc, aes128-ctr, aes192-cbc, aes192-ctr, aes256-cbc, aes256-ctr, blowfish-cbc, blowfish-ctr, cast128-cbc, cast128-ctr, idea-cbc, idea-ctr, serpent128-cbc, serpent128-ctr, serpent192-cbc, serpent192-ctr, serpent256-cbc, serpent256-ctr, 3des-cbc, 3des-ctr, twofish128-cbc, twofish128-ctr, twofish192-cbc, twofish192-ctr, twofish256-cbc, twofish256-ctr, twofish-cbc, arcfour, arcfour128, arcfour256] and [chacha20-poly1305@openssh.com, aes256-gcm@openssh.com, aes128-gcm@openssh.com]

So I will have to enable one of the ciphers that IntelliJ uses, but how do I find out which of this list is the least insecure?

aes128-cbc, aes128-ctr, aes192-cbc, aes192-ctr, aes256-cbc, aes256-ctr, blowfish-cbc, blowfish-ctr, cast128-cbc, cast128-ctr, idea-cbc, idea-ctr, serpent128-cbc, serpent128-ctr, serpent192-cbc, serpent192-ctr, serpent256-cbc, serpent256-ctr, 3des-cbc, 3des-ctr, twofish128-cbc, twofish128-ctr, twofish192-cbc, twofish192-ctr, twofish256-cbc, twofish256-ctr, twofish-cbc, arcfour, arcfour128, arcfour256

Update: I guess, that would be aes256-ctr, but that is just a guess

Yes, aes256-ctr is the right cipher to choose from those available to you.

Since it's not an AEAD, you need to choose a MAC. You should choose an '-etm' one if you can, and among those I'd choose the fastest.

Also make sure you have a strong key exchange (in descending order of preference: curve25519, ecdh-sha2-nistp256, diffie-hellman-group18/16/14, not something with sha1) and strong host key (in descending order of preference: ed25519, ecdsa with nistp256, RSA, nothing with sha1 or DSS).

If IntelliJ doesn't support a secure ssh configuration, complain to JetBrains.


Elaborate websockets security I'm interested in learning more about web sockets security. Read that web sockets were originally in Firefox, removed for security reasons and now added back in with the problem resolved:
http://news.ycombinator.com/item?id=2600022

Intial read of them seems like plenty of oppotunity for vulnerabilities just like traditional sockets in OS.

What are the security risks with web sockets?
How are they currently mitigated by modern browsers?
What else should be done to mitigate the risks?

WebSockets protocol is a tricky beast to evaluate right now, as it's changing frequently. After the flaws in draft-hixie-thewebsocketprotocol-76 of the WebSockets protocol discovered by Adam Barth et al. a few months ago, Firefox disabled WebSockets implementation in about:config preferences. Since then, a new protocol version is in the works, currently up to draft-ietf-hybi-thewebsocketprotocol-07, that tries to fix the flaws discovered. The browsers quickly adapt to the new version - see e.g. Mozilla bug #640003. But - on the other end, WebSocket servers still try to maintain backward compatibility, e.g. Socket.IO server still supports version pre-76.

So you might still succeed in trying to connect to WS server outside the browser, forcing older version of the protocol (see my tool already mentioned in the comments above).

But still - you are unable to send completely arbitrary traffic through WS connection. The frames begin with NUL byte, end with \xFF, with UTF-8 string inbetween (+ a handshake), so cross-protocol-attacks are not so easy to perform. Still, I'd rather use  WSS:// encrypted version than the plaintext one.


Why OpenSSL can't use /dev/random directly? I couldn't find the answer for the reason anywhere, even the wiki page doesn't explain it. This seems like using a PRNG for seeding an another PRNG. The first one (/dev/random) may itself be seeded by a PRNG.

I can 'understand' why the-randoption can't be used directly for generating keys, but I can't see the reason for the main sources. Many people say/dev/randomdoesn't produce enough output, which is wrong when its entropy is fed by a daemon.

Do they consider/dev/randomnot to be a quality source?

Reading bytes from a device can be troublesome (you have to account for syscall specificities, e.g. interrupted system calls) and can potentially be inefficient if reading many small chunks (a syscall has a non-negligible overhead). A custom software PRNG, seeded with bytes from /dev/urandom, gives more control over performance.

(Also, there might be a bit of NIH syndrome here, too.)


Message authentication code based on a single AES block I think I need to use a MAC for ensuring the integrity of a URL that my system will provide to an end user that will use it to download a content from another component of the system, i.e., an URL has to go from one component of my system to another component using the end user as a non-secure channel.

I had thought to use something like AES256(shared_key, MD5 (URL)), i.e., using the output of the MD5(URL) will be 16 bytes that will the input for the AES256, i.e., just one block encryption.

The point is that the key will not be changeb a lot, i.e., lots of MACs will be generated using the same key so and I am not sure if this method is secure on existencial forgery, because, using the same key multiple with AES is not CPA secure.

Please could anybody help on this?

Update:
Thanks very much for the responses

I forgot to mention that in some way I am enforced to use that approach.

However I am a little bit upset with the fact of generating MACs using the same key, I mean, AES with a single block is not CPA secure if the same key is used and I am not sure how this impacts the security of the MAC using the approach that I have described.

Thanks in advance

If you really need to use AES, then you may use CBC-MAC. Be wary, though, of the conditions: CBC-MAC is secure only if:

all messages have the same length, or (alternatively) you always compute the MAC over a structure which begins with a header which defines the message length;
you never use the key for anything else than CBC-MAC (and, in particular, you don't encrypt anything with the same key).

If you are already ready to use a hash function, then you will find it simpler to rely on HMAC. HMAC uses only a hash function, not a block cipher, so it is less complex than combining a block cipher and a hash function. HMAC is already implemented in many cryptographic frameworks (as usual, the less crypto code you have to write yourself, the better you get). HMAC/MD5 is, as far as we know, secure, despite the known weaknesses of MD5. However, if only for public relations, you might want to use HMAC/SHA-1 or HMAC/SHA-256. You can also truncate the HMAC output: this is known to be safe, i.e. if you truncate the output of HMAC/SHA-256 to, say, 80 bits, then you get a good 80-bit MAC, that the attacker won't be able to bypass with probability higher than 2-80 (and that's already complete overkill for most purposes).


Izito and similar sites keeps appearing in my search results Izito and similar sites keep appearing on my search engine results. It started a few weeks ago. It has been happening on both - my Ubuntu and Windows computer, and even on a new Windows computer. It has been happening on Chrome and Microsoft Edge and on Google and Bing. I have since installed Bitdefender AV and done factory resets and it still keeps coming back after a while. I was wondering if someone could please advise on what might be causing it, what damage / impact it might (have) caused, and how I could get rid of it.

If you're sure the search results are NOT advertisement, then they might be redirecting your searches to their servers by redirecting. Normally they do these through installing browser plugins (via bundling with free software etc.). But you're saying this happens on a brand new installation which suggests network level rerouting or root kit (unlikely)
Process of elimination:
Before doing anything, just try using a live Linux (booted from CD or flash drive) for a while and see if the problem happens again. Don't install any of your usual software, just use browser. If it does happen again, your routers/wi-fi device (or your ISP) is a suspect. Try again on a different network (try a public wi-fi for example). If that solves the problem, you know it's in your network. If it still does happen on another network (very unlikely), then there could be a firmware level infection (again very unlikely - try with another laptop then).
If you figure out the problem is only within your network, try setting your DNS manually (instead of using your ISP's DNS automatically) on that live Linux. You can use CloudFlare's free DNS service 1.1.1.1. If that solves the problem, then the problem is
with your router/wi-fi devices (infected to reroute requests) or its your ISP (very unlikely - but if it is an extremely cheap service - maybe).
Try hard resetting your router & wi-fi and then update their firmware. Review their settings (enable firewall for example). If they are too old, consider replacing them. Routers are getting targeted in last few years b/c they are easy targets. They could be hijacking DNS settings or randomly serving different content on your requests.


Is this encrypted information? Why is it in a URL? There's a vendor who sends us reports full of links to articles. Some of these links, especially ones that perform what I'm guessing is an HTTP verb of some kind, look like this:

https://arbitrarynumbers.acronym.website.com/anotheracronym/click?upn=V7nLa9UXJ-2FC89NDFn1UZlmMFXDCeN8q0tH6mY545KyAUaP8HmDtN9T2S-2Bg7aCCMBlSZh11liPowfKxWPna-2FVaptFLOZxqpcD68QrcptgMI1a22Y4XTEZiAeucUWjZAD9sVgV-2Baq0xequM7VcXl-2BmOl3FWqf7MOfWK13WhAyY6ILWhLP7aq99cI0yTYqdDXyfbGSCsAH14unM0mJZPPrnkibqRXOK6AicnwpYyUYWHrrglFkTEp1NUhfexGsfqdAypWPJVWibehmCua8elVvEK3h5UWGEQ-2BcMNXEYYaHh2Mk7e6P0PrboAZkrlVqjZw81_Vf68ZJ5AeUI3LF4CqINVwnqFVd-2FKRV7eRgp7NmpHn0vrNNp-2FS8Dx205CxtKAt8ruN8Tea80o1B2D68NmTEQrbzQbGcouV7k1BM7OghNe6LlIGeA-2B0g3cElmWBAQdEdnWI2eNmj-2FBye8kH4PB-2Bvp5GZihoTPLDhFLu31kSFdBGD5teoPbI-2FY26oYvi9TEWxcsvMtu3BS8V7aM0tKWV6h5D3IUQyv0cgY4liePEMplxsByyFEgJd5mgDyGiI4fFJgxPk529v0OuvuEDbPptklLF1LBT-2F-2Bt-2FOtOcTc-2BgfNAvLEHB8Rizid3vB6a6wd-2FG1PdK8fpMergoZPBy8DG3t143bUrabzZ-2BOvKN5bfzdOO80A-3D (This particular link is one you click to tell them the article wasn't relevant.)

Is this some attempt at hashing or encrypting the contents of the URL so people can't just send them random HTTP DELETE commands, or similar? Or is it some kind of security-by-obscurity? Something else entirely?

No. The link propably contains the full url of the article that wasnt relevant, and also user details of the user that sends "this is not relevant", so only those that received the report can tell that "this is not relevant".

Its not security-by-obscurity, rather, its a link with authentication data embedded, so you don't have to type your username/password or ask the company manager to tell "this is not relevant".

The reason to encrypt the url also, is that a integrity-verifying code at the end, can ensure, that authentication data belongning to link 1 cannot be misused to link 2. Eg, when you have clicked that link, then the corresponding article is then marked as not relevant. If some unauthorized individual clicks the link again, it does not matter since the article is already marked as not relevant.

The encryption then prevents someone from changing the article url/article id inside the link so one link cannot be misused to mark another article as not relevant, or misusing the link for other things like unsubscribing or such.

Think the link as this:
http://example.org/auth?username=somebody&password=somepassw0rd&action=markasnotrelevant&url=http://www.somenewssite.com/article/article39587395837u59.html&hash=5acf768c5fcafac85afc785fc8c
and then you encrypt that with a symmetric algoritm, and then encode as urlsafe base64, before sending it out.
Since the server created the encrypted link, the server can also decrypt the information with the same symmetric key, but nobody can abuse the information stored in the link.

It has NOTHING to do with DELETE/PUT and such HTTP verbs. A browser is normally unable to send anything else than GET/HEAD/POST, so the request done is a GET in the above case.


Sending password reset links in email Nowadays, when everyone tries to be more secure then each other, when companies spend billions on information security, it seems a little bit odd that the password reset left behind, the place that, in my opinion, should be everyone's concern, still relies only on the email provider.

Sending passwords in email is a bad idea. We all know it. Who knows how secure the email provider is? Who knows whether the email account was hacked? Who knows who's listening in between (man-in-the-middle)? etc... Because of that, almost no one sends passwords in emails.

But what about password recovery? Most of the websites just send a link via email, and after clicking on it, you can change the password. So no matter how secure the website is, it's pretty easy to hack a user, isn't it?

So how can I make a secure password reset system, without trusting the email provider?

I'm looking for a solution that will apply to everyone, without using other resources like SMS (which also not that secure). I'm looking for an answer that programmers with no budget what-so-ever still would be able to use it.

Here are some things I thought about:

security questions - nowadays everyone can find anything about anyone online, so those questions are not that secure.
Recovery code - be honest with me. If a website would ask you to print and save a recovery code, would you? Almost no one would. And if they did, they'll probably lose it after a while...

Send a unique string of text, a.k.a. a token (cryptographically secure, randomly generated), to the user via some other band besides e-mail, such as SMS or even snail mail. They can change their password in your app only if they input that token in a Web form on your site.

Or use physical devices, like SmartCards, that all users must have in order to use your app.


Dealing with File Permissions from a Virtual Machine - Forensic Logical Acquisition I am currently in the middle of operating an analysis on Autopsy of a virtual machine (VMware) that has been hacked. I have mounted the VM and I am acquiring the evidence from VMware to my physical machine (Windows 10).

I am trying to do a Logical File Acquisition of certain files and folders ;

Windows Event Viewer Logs (Application, System, Security)
OpenSSH Logs
Registry Keys
NTUSER.DAT
system32/config/SAM

However, file permissions Windows have installed is making it difficult for me to get hold of any of this. I don’t want to run a full physical as I’m only after certain artefacts.

Any recommendations would be appreciated greatly

Well first and foremost, you've already screwed up by mounting the VM which will have written to it as a side affect of mounting. Hopefully this is a copy?

Second, acquiring a logical copy is always a mistake if you don't have to due to constraints that prevent a physical copy.

All of your problems go away with a physical acquisition. Even though it's a VM you can still do a physical acquisition and it's dirt simple:

1. Run Autopsy

2. Target the VM .vmdk as the acquisition.

Done!

If you're still determined to do a selected logical acquisition, it's easiest to pull the target files via Linux.


What hardware do I need to monitor mobile traffic? What kind of hardware would I need to monitor data sent between a mobile handset and a base-station?

There are at least two options, dedicated commercial hardware about which I know little (Nexus Telecom is one vendor) other than it's improbably expensive; and the CCC method: https://svn.berlin.ccc.de/projects/airprobe/wiki/hardware (site uses a CAcert.org signed cert).

It seems you can get off to a good start with GNU Radio and a USRP board (sub $1000).


Does it make sense to hash a session id before passing it to an advertisement partner? My company runs a webshop. We work with a partner that gives discount vouchers to our customers after they buy (the vouchers can be used in other online shops) and also gives vouchers for our shop to customers of other shops. For this purpose, the partner asks us to send them some data about our customers and their respective order on our payment complete page. They want us to do this by setting some javascript variables and including a javascript from their server, which will also display an advertisement banner on our payment complete page.

I already learned that including advertisements banners bears some risk. It seems that our company already made the decision to accept this risk for this partner.

Now I am worried about one particular point. The data that the partner wants us to send also includes our customer's session id, in order to "recognize double requests" as the partner states. I think we should not sent the real session id to the partner, because with this information the partner could fake the customer's identity on our site. Therefore, I would like to send a hash of the session id instead. With this, the partner should still be able to recognize double requests without being able to fake the customer's identity.

Does this make sense? Or does the partner, by the fact that we include a javascript from their server, already have ways to do more harm than they could possible do by knowing the session id? We store the session id in an HttpOnly cookie (for the connection between our server and our customer).

If it makes sense to hash the session id, what hash function would be a good choice?

Yes, what you're saying makes sense.

By setting your cookie as an HttpOnly cookie, you're mitigating the risk of your partner's JavaScript having access to the user's session ID. Since your partner insists on getting a unique identifier for your customers, I see nothing wrong with sending them a securely hashed version of the session ID.

The key point here is that you don't use the hashed version of the session ID as an identifier, so your partner won't be able to use it to impersonate your customers, but at the same time, the hashed version is unique enough for your partner to recognize your customers.

As for what to use for hashing, it doesn't matter which hashing algorithm you use, as long as its output length equals or larger than your session ID .In this case, of course, you need to use a fixed salt (a pepper) all the time because you want the same session ID to produce the same hash.


How to determine when iPhone photograph was taken? If I have a suspicion that someone changed the date on their iPhone, took photos with that back-dated date and time, can I prove this? Or is this something that you just can't track?

No, you can't. If an image file has a timestamp in its metadata, that data can be edited even after the image was taken. It is called "Exif data", and there are editors available to do that. So you don't even need to think of this when taking the photo.

Changing Exif data leaves no traces in the file. So there is no way to prove that this kind of tampering took place.

The only way to prove that a photo was taken at a specific time is by looking at what's actually depicted in the image and see if there are any clues which hint at the date and time when the photo was taken. But as you know, thanks to the power of modern image manipulation software, there are also ways to tamper with the content of images.


Is the Station-to-Station protocol secure? After I've read a lot about key exchange many sources state that the Station-to-Station is secure, since it also verifies the entity on the other side.

Well how is that true, if an active Man in the Middle can just send it's own public key and sign the concatenated shared x and y with it's own private key?

Wouldn't it be as secure as classic Diffie-Hellman?

The important premise of STS is that Alice and Bob already know each other's public keys. Possibly, this "knowledge" is acquired through certificates, as part of a PKI. See the relevant quote from the Wikipedia page on STS:

  Public key certificates may be sent in steps 2 and 3 if the keys are not known in advance.

The SSL/TLS protocol, when used with the "DHE" cipher suites and with certificate-based client authentication, is actually an incarnation of STS.


SQL injection evasion I know that filtering bad keyword is not a good approach to preventing SQL injection.  However, when I couldn't answer why this is not a good approach, here is my rule:

1) When I see ;, I make it to '' (So that no one can make another line of SQL statement).

2) when I see ', I make it to ''. (I believe This should prevent quote escape).

3) When I see *, I make it to &#42 (So that hacker won't get my table info).

4) When I see --, I make it to &#45;(So that it prevents hacker try to comment out my statement).

^ The reason I come up with these 4 rules is because of a SQLi guide in here

Let say I do the following on my server when parsing a SQL statement:
db.exc("INSERT INTO name VALUES ('{}', '{}');".format(firsname, lastname))

And when I look at the rule that I set, I think it is technically secure to prevent SQL injection on this statement. Am I correct? If not can you provide a way to break it? (I know the best practice, but I just can't figure out why it is not.) Can someone help me with an example?

One obvious way to breach this: attacks using things that aren't strings (for example, numbers) where the user is supposed to enter something like 45 (which is manipulated in code as a string because it comes out of some HTML that way, but is not apostrophe-delimited in the SQL because it's a numeric-type field) but can instead enter an entire SQL subquery (or a procedure call, or at least some additional clauses...).

You also aren't anywhere close to comprehensive about meta-characters to catch. For example, using -- to start a comment isn't the only way (I'm not sure if it's even in the general SQL standard); another way to start a single-line comment (which MySQL also supports) is #, and you aren't doing anything about those. See https://dev.mysql.com/doc/refman/5.7/en/comments.html

Other problems: Let us hypothesize that you managed to actually do this "completely" somehow. Then, some time in the future, you switch database engines (or just upgrade to a new version) and the new database server supports some new meta-character (as a start to a comment, as an end-of-line, as an end-of-string, as a subquery delimiter, as something else altogether...), and suddenly your "solution" is vulnerable again.

Stop trying to re-invent the wheel. Prepared statements / parameterized queries exist for all database drivers. Some database engines support user-defined stored procedures, which are not only parameterized but also execute faster than normal SQL strings.

If you absolutely must combine user input with raw SQL for some reason (this is rare, and can usually be avoided by being more clever with your code, but that are some places where you can't simply use parameterized queries), use a well-tested library function for it. You're basically trying to re-implement mysql_escape_string, and the first attempt at that went wrong too.


How can a server prove authenticity I am working on a secure messaging platform and am having trouble figuring out how to protect against MITM attacks.

My current setup can be summed up as follows: The server keeps a private key and makes the public key public which can then be installed into clients. When sending data to the server, it must be ciphered with the public key which will then be decrypted on the server and re-encrypted with the private key before being forwarded to the recipient.

ASCII sketch of normal situation:

Sender --Encrypted, can be intercepted but not deciphered-->Server--Encryped with the private key, if intercepted can be broken since the public key is public--> Recipient

From that information alone we should see that the Sender->Server part is secure and a man in the middle wouldn't do anything (Trying something will corrupt the protocol and the connection will be terminated). However, the Server->Recipient part is not secure against MITM attacks.. at all!

To make matters worse, when data is sent, it is also sent back to the sender to confirm that it was sent, thus compromising both clients to MITM attacks.

So here is my question, upon the initial connection, how can the server prove that it is indeed the real server?

Sample scenarios:

Evil Server must not be able to pretend to be the Real Server
Client-->Evil Server-->Real Server

Real Server must be able to prove that he is, in fact, the Real Server.
Client-->Real Server

Notes: This is done over TCP. I am looking for a solution that won't require heavy infrastructure but I can allow using a couple of external servers to check (However these too, will need a way of proving their authenticity).

Begin each session by having the client generate a symmetric encryption key, encrypt it with the public key of the server, and send it to the server. Both server and client can then encrypt all further communication during the session with that symmetric key.

An impostor server would not have the private key of the server, so it can not decrypt the session-key and thus can not communicate with the client.

By the way, you are currently reinventing TLS with certificate pinning. You should generally avoid inventing your own cryptographic systems. Use what's already there and already tested for vulnerabilities by countless people.


Why does Kaspersky anti-virus not consider this executable as malicious? I was trying to learn file I/O and related function in C, and thus tried to create a baby-version of a virus. Following is the exact code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *mod_host, *fin_host;

    mod_host = fopen("host.txt", "r+");
    fin_host = fopen("final.txt", "w+");

    if (mod_host == NULL)
    {
        printf("Lucky you!\n");
        return 0;
    }

    int c;

    while ((c = fgetc(mod_host)) != EOF)
    {
        fputc(((c^2) % 94) + 32, fin_host);
    }

    fclose(mod_host);

    remove("host.txt");

    fclose(fin_host);

    rename("final.txt", "host.infected");

    printf("Sorry, you are now infected!\n");
}

What the above code exactly does, can be understood by the following pseudo-code:
open the file "host.txt"
create and open another file "final.txt"
transfer the contents of "host.txt" to "final.txt" and modify them in the latter file
delete "host.txt"
rename "file.txt" to "host.infected"

Now the program's actions and consequences are definitely malicious, and thus I expected my anti-virus (I use Kaspersky AV) to not let me run the executable created after compiling the above code. But turns out, the executable ran completely fine, did it's job, and returned 0 without Kaspersky AV giving any warnings. So, I explicitly tried to scan the executable for viruses. Again, Kaspersky AV finished the scan and reported that no malicious objects were detected, and the executable was safe to open.
Of course, the above program is not even a proper virus, and I have hard-coded a lot of things, from file names to the character modification logic, but still, it is malicious in the sense that it removes/deletes an existing file, and creates a new one (which in this case, is just full of gibberish, but it could potentially be another virus as well). Moreover, I cannot restore that deleted file even from my "Recycle Bin", since it is not present there. This does sound enough damage to me, still why doesn't Kaspersky AV consider this executable harmful? In case it matters, I am running this code on Windows 10.

Anti-virus programs detect malware in two different ways.  First, they contain a set of patterns that match known, existing malware.  Something matching one of these patterns should be definitively a piece of malware.
Second, they contain a set of heuristics which are found in many malicious programs.  These are not foolproof, so they are usually weighted in some way and a program which contains several may be flagged as a potentially malicious program.  When antivirus vendors make a mistake with heuristics, they do things like flag many benign programs written in Go as malware, which leads to problems.  Ultimately, these are guesses and they will have both false positives and false negatives.
In your code, you are using standard C library functions that are likely to be used in a lot of reasonably portable programs.  Opening a file, transforming the data, writing it to a new file, and then deleting the original is a pattern used by lots and lots of software for non-malicious purposes.  I suspect a similar invocation is used in the Unix program sed when invoked with the -i option.  While your code is malicious, it's also commonly used by a lot of benign software, so your antivirus won't flag it.
If your program did additional things that malware commonly does, like try to evade detection or hook the message queue, those would likely be flagged.  But right now, regardless of your intent, your code doesn't look that different from benign software.


How to steal cookie on website with cors? When I make a cross origin request to example.com from anysite.com with

req.withCredentials = "true";

cookies are included in the request

The response contains

access-control-allow-origin: https://anysite.com
access-control-allow-credentials: true
access-control-expose-headers: WWW-Authenticate,Server-Authorization

In this particular case, cookies values can be used to calculate the Authorization header value that can be obtained by manipulating cookie values.

I just want to extract cookies.

Any idea how to do that?

The target site doesn't have a CRLF vulnerability.

An attacker might influence what gets sent within a cross-origin request but he is not able to read the cookies which gets added by the browser to the cross-origin request. Even a wide open CORS policy does not change this.

An attacker might also not change where the cookies get send: cookies will only be sent to the site where they belong to, no matter what CORS policy exists.


Are password generators secure? Here's a scenario that I often encounter:

Some user needs access to something on my network, but they don't have an existing account in AD.
I create an AD account for them which I then use to allow access to an SSL VPN or an SFTP account or whatever.

I typically send an email with detailed connection instructions and text them a password.  I often use a free service provided by Norton to generate a random password with >= 8 chars.

Without knowing what algorithm Norton uses to generate these random char strings, the question is, is this secure?  The site I'm using to generate the passwords is SSL and I'm texting the password to the user, thereby separating the instructions (via email) from the required password.

How could I approach this problem differently in order to make the process more secure without having the ability to have the end user set their own password?

You might consider the random.org password generator which uses randomness based on atmospheric noise. Another option is Hotbits which gets its random data from radioactive decays.

For sharing passwords, you might want to use a self-destructing message site such as cloakmy.org or privnote.com that let you create secure password-encrypted messages that self destruct after viewing once or after a set time period.

Yet another option is to use something like LastPass that both generates secure passwords and provides a way to share that password with others.


Network setup for PCI-DSS C-VT Not sure if this is best here on information security or serverfault or Network Engineering.
We have a company that takes telephone orders over the telephone using a virtual terminal.
PCI-DSS 3.2 says that for this to be allowed:

Merchant accesses the PCI DSS-compliant virtual terminal solution via
a computer that is isolated in a single location and is not connected
to other locations or systems within the merchant environment;

and then in the questionnaire:

1.2. Do firewall and router configurations restrict connections between
untrusted networks and any system in the cardholder data environment
as follows: Note: An “untrusted network” is any network that is
external to the networks belonging to the entity under review, and/or
which is out of the entity’s ability to control or manage.
(a) Is inbound and outbound traffic restricted to that which is necessary for the cardholder data environment?  Review firewall and
router configuration standards  Examine firewall and router
configurations
(b) Is all other inbound and outbound traffic
specifically denied (for example by using an explicit “deny all” or an
implicit deny after allow statement)?

Does this mean that the machine we take the credit card information is inputed on needs to be completely isolated from absolutely everything else on the network in its entirety using firewall or a vlan? This would cause a real issue as they also need to access a central machine for share files for other customer service work as well as an internal SQL server.
Am I reading too much into this, and that access to central resources would in fact be okay - but other non customer service machines would have to be blocked?
Thanks in advance

The computer needs to be separated from the rest of the environment using either a host-based firewall or a network firewall with defined rules as outlined in Requirement 1. Here are some things to consider:

Outbound rules: generally the workstation can initiate outbound connections to your file share or your SQL Server.
Inbound rules: this is where you are segmenting the workstation, which is your cardholder data environment, from non-CDE systems. You would want very tight inbound rules with a final Deny All rule.
Connected systems: any machine or device that connects to the workstation will be considered connected systems. Systems such as domain controllers, patching servers, antivirus servers, etc. that provide services to the workstation are generally considered connected systems. Connected systems must be secured to PCI standards because they can provide a path into the CDE. Connected systems should be considered in-scope for an assessment. For more information about connected systems see PCI Scoping Tool.

For more information about workstations as a CDE, see How Does PCI DSS Apply to Individual PCs or Workstations and What is SAQ C-VT. As stated in the "What is SAQ C-VT" FAQ, "merchants using virtual terminal solutions should consult with their acquirer (merchant bank)."


How are unique SSH users linked to authorized_keys file? I'm trying to get a better understanding of authorized_keys in the context of an SSH server.

So if I have a linux server and I've placed a clients public SSH key into my servers authorized_keys file, that client may now login to the server.  Presumably, this is the public key from a specific user on that client (new keys are generated for each user, right?).

If multiple users exist on my serer (root, user1, user2, etc.), then which user/profile (on the server) is the client allowed to access?

The authorized_keys file is not a per-server thing - it's a per-user-on-server thing.

If you want someone to access your server as "user1", you place their public key in ~user1/.ssh/authorized_keys. Now they can login as user1, and only user1.

If you want them to be able to login as other users, you need to copy their public key to the authorized_keys file of each target user. (Or you can user sudo to let them su to the other users.)


Are UEFI vulnerable to the same password bypass techniques as BIOS? I'm trying to understand if the old school ways of bypassing a BIOS password (flip the BIOS jumper or remove the CMOS battery) still affect (some or all) modern UEFI?

If not, what protections do modern UEFI implement that prevent it?

I can't remember the last time I worked on a system where a CMOS battery pull reset the password. Of course, password reset jumpers or manufacturer override codes are features, and you can expect UEFI to have all the features BIOS had and then some.

Remember, though, that BIOS passwords aren't that powerful. They protect against someone with physical access to the keyboard and screen, but will fail against anyone with physical access to the machine itself. If you want to keep your data safe, you need full disk encryption controlled by a TPM and measured boot.


Known vulnerabilities of GOST Are there any known vulnerabilities in the GOST block cipher (GOST 28147-89)? Spcifically, I'm thinking about i.e. "master keys" which intentionally exist and are used i.e. by the Russian government.

I understand that although there are attacks against the algorithm itself, it is not broken. Is this a correct assumption?

However, it would not help the algorithm in terms of security if there were for example master keys which would allow the Russian government (or whomever, I'm using the Russian government as an example, since GOST is a Russian algorithm, for all I know) to access files encrypted with this algorithm.

If GOST would be used in a chain of several algorithms, i.e. AES-TWOFISH-GOST, would there be a risk of weakening AES and/or TWOFISH assuming GOST had known vulnerabilities like the one described earlier?

Also, is GOST used anywhere outside Russia or is it a strictly Russian algorithm?

Thank you very much.

Spcifically, I'm thinking about i.e. "master keys" which intentionally exist and are used i.e. by the Russian government.

The standard doesn't define S-boxes (substitutions tables) and this makes hard to invent such a master key, especially if you treat the S-Boxes as long term keys and keep them secret. Besides, no one researcher has demonstrated such a "master key", though there are some subspaces of key space that are weaker than the others (but the algorithm remains unbroken).

  If GOST would be used in a chain of several algorithms, i.e. AES-TWOFISH-GOST, would there be a risk of weakening AES and/or TWOFISH assuming GOST had known vulnerabilities like the one described earlier?

It depends on the way you combine the algorithms into a chain, because some Meet-in-the-Middle attacks can be possible in this case. In addition, AES has 128-bit block, but GOST has 64-bit block and it will be tricky to combine them in secure way.

  Also, is GOST used anywhere outside Russia or is it a strictly Russian algorithm?

Yes, besides Russia the algorithm is still widely used in Ukrain, Belarus, Kazakhstan and other ex-USSR republics. However, those countries have their own sets of GOST S-Boxes and they're moving to their own crypto standards (Kalina in Ukrain, Belt in Belarus etc.). There are some open source encryption tools like GostCrypt that are based on GOST. GOST is also implemented in OpenSSL and Crypto++ frameworks.


SASL Authentication Protocol with No Cleartext passwords As you know, LDAP supports three authentication mechanisms: anonymous, simple and SASL.

The first one is only suitable for particular cases, and therefore I'm not going to talk about that. The second one sends the password in clear, and hence is not suitable if one is not willing to implement it over something like SSL (due to compatibility issues or legal reasons).

This leaves us with the third option: SASL. As listed on IANA, there are several SASL-based authentication mechanisms to pick from. Some of them are obsolete or in limited use, but others are common.

I want to pick a SASL-based authentication mechanism, with the following features:

It is password based (in contrast to, say, SecurID, which AFAIK is token based).
Its security is not based on an underlying protocol (e.g., SSL).
The protocol does not require users' passwords to be stored in clear (for instance, CRAM-MD5 may do this).
It is widely implemented.

Could you please suggest my options?

There are two mechanisms used to authenticate an LDAP session:

simple
SASL

The simple BIND mechanism takes one of four forms:

anonymous - null name, null credentials. This is the initial state of a session.
unauthenticated - non-null name, null credentials. Directory servers should be configured to reject this request because no authentication takes place.
name/password - name, credentials
undefined - null name, non-null credentials. The behavior of the server is undefined by the LDAP standards. Directory servers should be configured to reject this request because no authentication takes place.

When an LDAP client connects to directory server, that connection has an anonymous authentication state. The client can request the state be changed by using the BIND request. The BIND can also "reset" the authentication state to anonymous.

The recommended authentication method is simple BIND using either a secure connection (SSL) or a non-secure connection promoted to a secure connection using the StartTLS extended operation. Modern, professional quality directory servers support strong cryptographic hashes of salted passwords to make the construction of dictionaries difficult.

Another method is the SASL GSSAPI mechanism, which avoids transmitting the password altogether.

Another method is the SASL EXTERNAL mechanism, which uses information not provided by LDAP, for example, the client certificate presented during establishment of the secure session.

Another method is the SASL DIGEST-MD5 mechanism which avoids transmitting the password but has the disadvantage of the requirement that the server must have access to the clear-text password or be able to decrypt the user's password, which means using a reversible password storage scheme. DIGEST-MD5 should be avoided for this reason. If DIGEST-MD5 is required, AES might be the best block cipher.

CRAM-MD5 is weaker than DIGEST-MD5, and should be avoided.

see also

LDAP: Authentication Best Practices


C++ binary obfuscation: how to get around license checks being a simple if/then branches? I'm looking into binary obfuscation for an exectuable binary written in C++. I realize preventing cracks is impossible, but making it slightly harder would be nice.

No matter how complex the actual license scheme is, I can't think of a way to validate it that doesn't ultimately boil down to:

if (doVeryComplexLicenseValidationCheck())
{
    //execute code
}

...which would be trivially easy to bypass by any competent cracker. But obviously there are many copy protection systems out there that have been very difficult for people to crack...so what are they doing that I'm missing? Is there a way to obfuscate a simple branch like that, that's much more difficult to bypass?

Here are some tips that may help you, but just remember that any one with a good understanding of assembler will found it.

Lets imagine your program is like you describe:

int main() {

    if (myCheck()) {
            std::cout << "License pass\n";
    }
    ....

And here is the disassembler of the code.

00000000004006d3 <main>:
4006d3:       55                      push   %rbp
4006d4:       48 89 e5                mov    %rsp,%rbp
4006d7:       e8 da ff ff ff          callq  4006b6 <_Z7myCheckv>
4006dc:       84 c0                   test   %al,%al
4006de:       74 0f                   je     4006ef <main+0x1c>
4006e0:       be d1 07 40 00          mov    $0x4007d1,%esi
4006e5:       bf 40 10 60 00          mov    $0x601040,%edi
4006ea:       e8 b1 fe ff ff          callq  4005a0 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@plt>
4006ef:       b8 00 00 00 00          mov    $0x0,%eax
4006f4:       5d                      pop    %rbp
4006f5:       c3                      retq

So by adding asm statements in your code you can make it more difficult.

#define OPS1 "xor \%rbx,\%rbx\n"
int main() {
    __asm__ volatile (
            "push %rax\n"
            "xor %rax,%rax\n"
            "pop %rax\n"
    );

    if (myCheck()) {
            std::cout << "License pass\n";
    }
    __asm__ volatile (OPS1);

And here is the output

4006d3:       55                      push   %rbp
4006d4:       48 89 e5                mov    %rsp,%rbp
4006d7:       50                      push   %rax
4006d8:       48 31 c0                xor    %rax,%rax
4006db:       58                      pop    %rax
4006dc:       e8 d5 ff ff ff          callq  4006b6 <_Z7myCheckv>
4006e1:       84 c0                   test   %al,%al
4006e3:       74 0f                   je     4006f4 <main+0x21>
4006e5:       be e1 07 40 00          mov    $0x4007e1,%esi
4006ea:       bf 40 10 60 00          mov    $0x601040,%edi
4006ef:       e8 ac fe ff ff          callq  4005a0 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@plt>
4006f4:       48 31 db                xor    %rbx,%rbx
4006f7:       b8 00 00 00 00          mov    $0x0,%eax
4006fc:       5d                      pop    %rbp
4006fd:       c3                      retq

This case is really really easy, but if you have a good understanding of templates, assembler you complicate a bit the code generated.


Why doesn't the 802.11 standard implement TLS for wireless handshakes between clients and routers? Why aren't wireless handshakes sent using TLS?  It seems like it would be relatively simple to implement, perhaps having the vendor insert the private key into the routers.  That way WPA/WPA2/WEP encryption couldn't be cracked by capturing parts of the handshake sent in plain text.

SSL relies in TCP/IP. TCP/IP relies on the physical and data link layer to have been established.  WiFi is part of physical and data link layers.  The idea being that you need the lower level links to be established before you can carry on a conversation at the high level.

It's a little like asking why can't a distant person who's only reachable by radio communicate the frequency to listen on in english.  Because to communicate in english, you first have to have a radio link, which means knowing the frequency.


Are there other methods than fuzzing for black box? I find fuzzing a bit to basic method if it comes to black box apps. I am specifically interested how to find a vulnerability in network protocols. I have read "Attacking Network Protocols" but only fuzzing was discussed.

On a pure black box where all you have is input and output, you would have to fuzz it.

If all you had was an obscured executable file, which executed on a remote system available only by an API, that would be the closest you could really get to a pure black box test. For something like that fuzzing is the entry point.

Once you fuzzed you may find an error indicating input is being filtered for usage in a relational database. You may learn input limits, restricted words, rate limiting, etc.

It all starts with fuzzing.


Are sandboxes overrated? I've stumbled upon the following on the blog of the NoScript developer Giorgio Maone.
First, he quotes the following ArsTechnica article about an XSS bug in Adobe Flash:

As useful as sandboxes are in restricting potentially buggy code to a
small part of the operating system, they do nothing to minimize the
damage that can be done by attacks that exploit universal XSS flaws,
researchers said.

He then points out the following interesting statement:

I was already preaching this four years ago: the more our assets move “in the cloud”, the less traditional security measures, meant to protecting just your local system, suffice.
The battlefield is the web now, and there’s no coming back…

Question
Is this true? Should browser security focus more on exploits which take place "in the web" only?
By "in the web" I mean exploits which do not try to install malware on the user's computer, but try to steal data or abuse via XSS or clickjacking for example.
It's a fact that I do so much on the web now. My email account has grown to the importance of the digital wallet. Most of my internet accounts and other sensitive information are passed via the internet.
Chrome's PR successfully advertises Chrome as a very secure browser. Which is probably true when talking about protecting your computer from malware. But protecting my online activity is just as important.

No.  Sandboxes aren't overrated.  They've very useful.  They are not a silver bullet -- they don't solve every security problem -- but they do have substantial value.

Really, don't think this is especially new.  If you read the original paper describing the Chrome security architecture, it clearly explains why sandboxing is valuable while also elucidating its limitations.  For instance, the introduction says:

  Chromium's architecture is designed to mitigate the most severe vulnerabilities, namely those vulnerabilities that let an attacker execute
  arbitrary code. [...] We find that 38 of the 87 rendering engine vulnerabilities allowed an attacker to execute arbitrary code and would have
  been mitigated by Chromium's architecture. These account
  for 70.4% (38 of 54) of all disclosed vulnerabilities that allow
  arbitrary code execution.

So Chrome's architecture makes a huge contribution to mitigating the most severe vulnerabilities that one can have in a browser.

At the same time, the Chrome team never claimed that sandboxing is a silver bullet.  For instance, see "Out-of-Scope Goals" in that paper for a lucid description of some vulnerabilities that Chrome's sandboxing architecture does not attempt to mitigate.  Anyone who has been following this should already be aware of the fact that sandboxing does not claim to stop all security problems.

Read the paper here:

The Security Architecture of the Chromium Browser, Adam Barth, Collin Jackson, Charles Reis, and The Google Chrome Team.

Please remember, vulnerabilities that let an attacker run malicious code on your local system (also known as drive-by downloads) are the most severe kind of vulnerability.  An attacker who exploits such a vulnerability can also attack all of your data "in the cloud" or on servers.  The reverse is not true.  Consequently, drive-by downloads are the most severe kind of vulnerability to have in a web browser.

If you look a few years back, these "drive-by-download" vulnerabilities in browsers were very common.  Given their severity and prevalence, it is only natural that researchers and security professionals spent a lot of energy looking for ways to mitigate or eliminate those kinds of vulnerabilities.  The security community has found reasonable ways to significantly reduce the prevalence of such vulnerabilities.

So, sure, once you make good progress on eliminating the most common, most severe vulnerabilities, it is only natural to next start looking at how to address the next-most-serious problems.  But that doesn't mean sandboxing is "overrated".  And, it doesn't mean that the energy put into defeating drive-by downloads was wasted or misplaced.  It wasn't.  It was important, and remains important today.


Mixing VPN Protocols Is there any benefit to mixing vpn protocols as far as obfuscating your traffic. Would a multiple hop setup like (openvpn(server1) + wireguard(server2)) be better or is (openvpn(server1) + openvpn(server2)) just as good.

No.  Pick a VPN you trust, and stick with that.  If you don't trust it, why would you run it with another one that you do?  Just run the one you like.
Otherwise, you're going to be maintaining a rather complicated network for no added benefit.  Also, you're more likely to implement something wrong, and open vulnerabilities if you make the implementation too complex.
Forget about OpenVPN.  Just use WireGuard.


Does adding a password to BIOS prevent malware from infecting it? I'm looking into ways of hardening a computer's security.  One of the things is the BIOS.

Does adding a password to the BIOS prevent malware from infecting it?

I have seen this article: Protecting the BIOS from malware    but it doesn't mention about passwords.

Any information on this is greatly appreciated.

Absolutely not. The BIOS password is only an authentication mechanism presented when the system boots or when a manual change to the configuration is made during boot. Malware which overwrites the BIOS typically does so by writing over SPI, the interface which the BIOS resides on. If malware gets enough privileges to write to SPI, and your BIOS does not set the proper lock bits that deny access to this interface at runtime, then it is game over. The contents of your BIOS flash chip can be modified completely, including the contents which execute the password authenticating code.

The only two ways to ensure malware cannot overwrite the BIOS is either to:

Have a BIOS which properly sets all the lock bits at boot, and the only way to make sure of that is to use the chipsec framework and understand the results it gives
Use a system which supports BootGuard, an Intel feature in some newer CPUs which causes the chipset to verify the BIOS itself before loading it, ensuring that it can only boot from a BIOS signed with an OEM signing key. This should prevent malicious BIOSes from running (as well as 3rd-party, open-source BIOSes like Coreboot and Libreboot).


Is it possible to include a PHP Function while performing SQL Injection? Consider this code:

?id=' UNION SELECT 1,2;"; phpinfo();//-- -&Submit=Submit

Will this work out?

SQL Query:

if(isset( $_GET[ 'submit' ] ) ) {
  // Get input
  $id = $_GET[ 'id' ];

  // Check database
  $query  = "SELECT first_name, last_name FROM users WHERE user_id = '$id';";
  $result = mysqli_query($connection, $query);
  // Get results
  while( $row = mysqli_fetch_assoc( $result ) ) {
    // Get values
    $first = $row["first_name"];
    $last  = $row["last_name"];

    // Feedback for end user
    $html .= "
ID: {$id}
First name: {$first} & Surname: {$last}
";
  }
}

My Observation:

The same code snippet works well when I hard code it into the .php file i.e.

$query  = "SELECT first_name, last_name FROM users WHERE user_id = '' UNION SELECT 1,2;"; phpinfo();//-- -&Submit=Submit';";

BUT when I send it from a form, via GET, what I get:

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

Let me know if I need to be more Verbose.

Generally, it CAN NOT be done. SQL injection only allows you to execute SQL commands. You are not directly able to use PHP.

The only way you may be able to execute PHP using SQL inejction is if the page uses eval() on un-sanitized input from DB. Few web pages will ever do this. It may be possible even if the page uses something even more rare and weird such as generating a php file to be included from DB, but this virtually never happens.

If the page uses eval on result from DB, then you just use the SQL injection to insert the code to the appropriate place in the DB (the column that is put into eval) and then visit the page that uses the eval(). Once the PHP code from the DB is passed to eval, it is executed.


Is it acceptable to generate salts with a hash of the username? Salts are supposed to be unique and randomly generated for each user when storing passwords. Is there a reason why we can't generate these salts with a cryptographic hash function using the username as the input?

It appears to me that these hashes would give the properties we desire, and we wouldn't have to use additional storage space for the salts.

Good salts are unique over the whole range of space-time.

A user does not change his name when he changes his password: that's a failure of uniqueness over time. (Similar case: an old user account is closed, a new user is registered and reuses the same name.)

A user has the same name on several distinct servers, which may employ the same hashing strategy: that's a failure of uniqueness over space. (Think, in particular, of all these users called "Administrator".)

User names are thus rather sloppy as salts. They are much better than no salt at all, but it is highly recommended to use proper random salts instead. 16 bytes (or more) from a cryptographically strong PRNG will give you much better uniqueness.


What are the main issues and best practice security controls when exposing SIP and H.323 to the Internet? What are the main issues and recommended controls when exposing SIP and H.323 to the Internet (could be for voice, video, and instant messaging traffic or all three)?

Specifically I'm looking for best practices in firewall/DMZ architecture, and any additional recommended security controls, when deploying SIP and H.323 gateways.

Avaya's quick two-page checklist is broadly vendor neutral. Key first steps include:

H.235.5 for H.323 signaling encryption
SRTP* for H.323 / SIP media encryption (10 bytes overhead per packet)

Standalone AES encryption can also be used for H.323 media
encryption

TLS for SIP signaling encryption
SRTP for voicemail interaction
TLS for adjunct communications
AES encryption for configuration back-up
Note, network regions can be created to segment phones that don’t support
encryption from phones that are capable of encryption

In order to set it up so that Security and QoS is maintained, you will need a firewall set which is H.323/SIP-aware. From this SANS paper:

  Many of the protocols used with the H.323 suite use random ports causing problems securing through firewalls but may be able to be mitigated by using direct routed calls. Since the ports required for H.323 are not set, a filtering firewall would have to have all possibly needed ports left open. Therefore, the firewall would need to be H.323 aware allowing communication without opening up the firewall to other traffic. A stateful firewall and/or application firewall is required to ensure consistency of the characteristics of connections.

There aren't a huge number of firewalls which support SIP/H.323 well, but the usual stateful enterprise ones like Juniper, Cisco and Palo Alto seem to work.


Is it safe to use Giphy API keys in public Github repo? I am making a game of which one of the hidden features is displaying a GIF from Giphy at a fixed command. For this, I am using Giphy API, hosting the game as a website on Github Pages with a public repo, and getting the data with a get request.

But since this is my first time using an API key, I wanted to know if it is secure to use API key as such in a public repo, or what should be the ideal way to access the data using the key in this case?

Here is the official response to this question from GIPHY:

GIPHY APIs are designed to be used on the client side (and hence the API key too). You should go ahead and use it that way. Once development is complete - please apply for Production access for the key through the Developer Dashboard, this removes Rate limits associated with a beta key, so you don't have to worry about high traffic.
Lastly, and most importantly - GIPHY has monitors setup for API key abuse and we'll reach out to you if anything happens. We definitely don't want you to worry about it.

From here


Why not have an identical session cookie for different user's devices? Here is my table structure:

// users
+----+--------+------------------------+------------------+-------------------------------+
| id |  name  |          email         |     cookie       |    /* some other columns */   |
+----+--------+------------------------+------------------+-------------------------------|
| 1  | Jack   | jack0948@example.com   | ojer0f934mf2...  |                               |
| 2  | Peter  | P_2009@example.com     | ko4398f43043...  |                               |
| 3  | John   | mx_pro34@example.com   | 0243hfd348i4...  |                               |
+----+--------+------------------------+------------------+-------------------------------+

The cookie column contains a string (the cookie which keeps the user logged in) that is also set into user's devices. As you see, I have just one string (as the cookie) for each user. So all user's devices have an identical cookie.

Most professional programmers tell me:

  It would be safer if each device had its own cookie (the cookie of each device should be different than the cookie of other devices, not a constant cookie for all devices)

Well, why? What's wrong with having an identical cookie for all devices? Also as you see I have just one record for the cookie in the database. So if I update that record for a new device, then the previous device(s) will be logged out.

EDIT: Imagine the following scenario (based on different cookies for different devices):

Alice logs in to my site on her computer at home, and stays logged in. Later she logs in on a computer at school as well, and dont sign out when she is done, but she forgets to sign out. She goes home and wants to sign out from her account at school. How can she do that?

The problem

Imagine the following scenario: Alice logs in to your site on her computer at home, and stays logged in. Later she logs in on a computer at school as well, but signs out when she is done. What happends when she gets home?

To make this system work, you would need to set the cookie column to NULL on logout. But that would log her out from all devices. That would be very annoying if you for instance want to stay continously logged in on your phone. So as long as you actually invalidate sessions server side on logout (you should always do that) this is more of a usability issue than a security issue.

Solution #1

So what would your table structure look like if you allowed multiple sessions per user? First, drop the cookie column from the users table. Then create a new table called sessions like this:

+------+------------------+
| user |     cookie       |
+------+------------------+
| 1    | ojer0f934mf2...  |
| 2    | ko4398f43043...  |
| 2    | 34fjkg3j438t...  |
| 3    | 0243hfd348i4...  |
+------+------------------+

Note that the second user has two different active session.

There should be a timestamp in there somewhere also, so that you can terminate the session after X hours. Even if you have a max-age on the cookie, you should always terminate sessions server side as well to mitigate the effects of session theaft.

Solution #2

No need to store session identifiers in a database. Just use PHP's built in session handling and you will not have to worry about generating ID's, setting cookies, etc.

Signing out from different devices

Conserning your edit about how to let Alice log out from school if she forgot to do it: Include a feature that lets her log out from all devices. Facebook, for instance, has a feature like that. Or if you don't want to waste energy implementing that, just instruct users to change their password - a well implemented password reset function should terminate all the users active sessions anyway.

In the database setup, ending all sessions would be the equivalent of running this:

DELETE FROM sessions WHERE user = :id


Stopping webpage compromise by preventing frame-busting My website offers rich content to users. I often subscribe to third party vendors whose content I embed in my pages. How can I safely embed external domain's content on my webpage in an iframe without worrying that they won't be able to bust out of frame. They won't do it purposely (without risking their clientage/reputation). However, since they almost always are small shops, they become a juicy targets for an attacker who wants to deface/redirect my website.

Is there a header (something similar/opposite to X-Frame-Options) which I can use on my parent page to ensure that the iframes I embed can't bust out? Remember, I can't ask vendors to add headers/scripts to their pages. They never purposely want to do nefarious things to my page. The scenario I am trying to cover is the one when they get hacked.

You need the sandbox attribute. This is a new attribute supported by all major browsers. Sandbox attribute imposes extra restrictions on the content inside the iframe - one of those restrictions is running javascript. You can choose to remove the other restrictions that you do not want to impose.

Use the following to embed URLs from different/untrusted domains in your web pages:

<iframe src="http://example.com/external-content.htm" sandbox></iframe>

Here is the quick reference (copied from the w3schools link above):

  When the sandbox attribute is present, and it will:

  treat the content as being from a unique origin
  block form submission
  block script execution
  disable APIs
  prevent links from targeting other browsing contexts
  prevent content from using plugins (through ,
  , , or other)
  prevent the content to navigate its top-level browsing context (this is what you need)
  block automatically triggered features (such as automatically playing a video or automatically focusing a form control)


Can you serve up special content to an end-user based on IP or other identifiable data? Is it possible to serve up specific content to an end-user? For example, I know your IP address, and other device information. Can I use that to serve up certain search results on a search engine, certain videos on websites, and use that to target an individual with specific advertisements? Obviously I am not interested in carrying out such attacks, rather seeing if it is feasible.

Additionally, what information can identify a device if a VPN is in use?

Yes, this is a common practice. There are many ways to identify a user. Here's a few.

user agent string in the request
browser fingerprinting (pantoclick
IP address (country, region, ISP, known VPN ranges, blacklists, etc.)
referrer header
cookies
previous history (look through your own logs to ID return traffic)
URL history harvesting
css fingerprinting

There's an almost endless way of identifying different users/clients. Serving different content is supported in pretty much every language/server.  It's the basis of dynamic web apps (facebook, Twitter, pretty much every interactive webpage)