The Vigilantes Who Created 'Malware' to Secure 10,000 Routers - <AUTHOR> http://www.forbes.com/sites/thomasbrewster/2015/10/06/mystery-white-team-vigilante-hackers-speak-out/ <comment><USER2> I have already considered this as an ethical hypothetical scenario. Is it acceptable to break in to someone else's system for the purposes of preventing other people with unknowable motives from breaking in, or to stop a break-in already in progress?

For a full answer, I also need to answer some other questions. Is there any way to contact the owner of the device that has a reasonable chance of success? Are there any reasons why the owner might leave the device in an unsecured state intentionally? Is the device spreading harm to others because it is insecure? Is the owner aware that the device is not secure?

I decided that the scenario was analogous not just to someone leaving their car doors unlocked in a high-crime neighborhood, but to a medical quarantine. An unlocked car doesn't really hurt anyone else, but an unaware carrier of a contagious pathogen is dangerous to himself and to others. It then becomes more acceptable to force treatment on an unwilling or unaware person, for the sake of public health.

As a result, I figured that a program like the following would be ethically acceptable, but not necessarily virtuous:

      - uses a single specific vulnerability to compromise systems
      - immediately patches the vulnerability out of an infected system
      - attempts to detect and remove any known malware
      - goes dormant for a variable amount of time
      - attempts to infect other systems at a slow rate for a fixed amount of time
      - removes itself from the infected system
      - leaves behind a human-readable log of its activity

It would also be helpful for it to be accompanied by a fix for the vulnerability in the official device update stream.

<comment><USER3> In the physical world, this type of "helpfulness" would get you shot dead, as you broke into someone's house for what you considered to be "helpful" reasons.

The medical quarantine example is interesting, but there is a critical difference: There are officially recognized medical authorities with the legal power to require you to be quarantined. Currently, no such authorities exist on the network.

So the example is more like: some people with medical knowledge _but no actual standing_ try to quarantine you. But it's not quite as bad as it sounds, because there exists no Health Department to do so officially. (For that matter, there doesn't exist much government at all, in any form.) What's more, since there is no government to enforce this, the self-appointed expert quarantines you _without your permission_.

I can see the reasoning behind it, but I'm not willing to go so far as to call it moral/ethical behavior.

<comment><USER4> Perhaps forced vaccination, as it has little interference with your everyday life.

<comment><USER5> Some vaccinations are riskier than others. While it's fairly clear they don't cause autism after that whole braindead debate, they aren't exactly risk free EITHER, though complications are vaccine specific, rare, and not very well understood because of the rarity.

It's very easy to violate someone's self determination rights with the best intentions and still hurt them. In the virus parallel the vector is an unknown quantity. It doesn't entirely seal the router, and doing it without permission may in fact increase the vulnerability of the router (or brick it, if things go wrong).

I find this really interesting, but it's very hard to back from a moral or ethical point of view.

<comment><USER2> It is hard to accept and hard to condemn. I find it to be tolerable.

The end result benefits me slightly, yet the means does not entirely justify it.

If I lived in the tropics, I'm not certain how I would feel if I returned home to find that a band of rogues had broken into my house, installed new insecticidal bed nets in all bedrooms, and locked up after themselves on their way out, without touching anything else. On the one hand, hey, free bed nets. On the other hand, no one bothered to ask my permission. Or knock.

But then maybe I hear about a terrifying disease currently spreading via the saliva of the oogeyboogeyfly, who will chew through untreated bednets, or insecticidal nets older than 6 months, to bite sleeping people, and only new ones treated with skellingtol will work to stop them.

In that case, there was

      - an overriding concern for public safety, from an actual threat
      - some urgency, such that voluntary compliance might be too slow
      - a risk that some might not take effective preventative measures
      - no malicious intent toward me, specifically

The target of the action was actually the oogeyboogeyfly, which I was unknowingly providing with a safe platform for spreading disease. So it comes down to the old Star Trek 3 dilemma: if you could save a thousand lives by letting just one person die, would it be ethical to do it? Would it still be ethical if that one person wasn't you?

<comment><USER5> Yea, but you're ignoring the fact that _people might want to get malaria_. Not everyone likes being taken care of; some want to live life the way they want to (e.g. short and fast, but without bug nets).

<comment><USER2> People might also want to walk into my living room and remove my television set from it. I can't stop them wanting it, but I can stop them doing it. If you threaten my life, liberty, or property, it is ethical for me to defend those things, regardless of whether your threat is the product of malice, ignorance, or negligence.

If you intentionally get yourself infected with a zoonotic pathogen and start cavorting with one of the carrier species, at minimum, you're going to get a severe beating when the town finds out about it. If you don't take care of yourself as a person, someone else might take care of you as their problem.

</comment></comment></comment></comment></comment></comment></comment><comment><USER6> I must admit, to me it first seemed more like someone wanted all those devices to be their own botnet without having script kiddies interfering and possibly causing a stirrup, instead preferring to keep everything for the exclusive use of the botnet owner.

</comment><comment><USER7> The worm left backdoors for future use. It booted off competition so it would have the whole device to itself, ready for instructions.

<comment><USER8> IIRC, it also instructs the user to update and secure their firmware, wiping and blocking the vigilante worm as well as other malware. That doesn't seem like a plan for building a secure criminal botnet.

</comment></comment><comment><AUTHOR> Link to the GitLab page: [https://gitlab.com/rav7teif/linux.wifatch](https://gitlab.com/rav7teif/linux.wifatch)

</comment><comment><USER9> The more clueless people pick the story the more distorted it gets.

There are VERY FEW ARM based routers. Huge majority runs MIPS. You know what runs ARM? stupid IoT devices, security systems/cameras, and custom/very specialized niche jobs.

Here is a graph from the original story: [http://www.symantec.com/connect/sites/default/files/users/us...](http://www.symantec.com/connect/sites/default/files/users/user-2598031/Fig4_10.png)

</comment><comment><USER10> Trying to think of a real world analogy - let's say your car was compromised and hackers were using it when it was idle to launch attacks, or make money. Would I be mad if someone entered my car and turned on/activated the locks?

<comment><USER11> Assuming everything went as planned, no problem. But to play devil's advocate...

The risk with these things is always the "what if?". What if during that patch it bricked my device due to some fluke? What if I had a special customization that relied on a specific behavior on the component that was just updated without my consent?

What if that patch attempt to a vehicle fails, leaving it unable to turn on? What if that vehicle was an ambulance?

<comment><USER12> I think their answer would be "the needs of the many outweigh the needs of the few"...

And to flip that argument again - would you prefer your device to be bricked by someone trying to run a webserver serving child pornography, or by someone trying to protect you from the first?

<comment><USER13> Aka the "yelling 'Fire!' in a crowded movie theater is not free speech" exception. It's good for the guy who wants to yell "Fire", but is it good for the majority?

If you patch routers and 1% get bricked by some fluke, is that not a win for society?

Also, to rebut the "How dare you change the firmware on my router without my consent?!" point, let's not forget these were essentially unprotected routers at this point in the applied_patch vs known_vulnerability cycle. If you don't want anyone patching your router without your permission... SECURE YOUR OWN PROPERTY.

If I leave something on the sidewalk, I don't get angry when people cart it off / step on it. I especially don't get angry when they glue the broken bits back together and leave it on my doorstep with a note saying "We noticed this was broken. Superglue works wonders! Here's the number for a hardware store where you can buy it."

</comment></comment></comment></comment><comment><USER14> This is basically what sent Max Vision to prison in 2001, right? I hope there's better opsec with this. Also _never_ talk to the cops...</comment>


8Chan Refugees Blow Their Anonymity - <AUTHOR> https://www.thedailybeast.com/8chan-users-migrating-to-zeronet-are-accidentally-revealing-their-locations <comment><USER2> Well, does the distributed hosting work with TOR?

What about with a VPN (like the free one included in Opera)?

<comment><USER3> Yes, it's in the article, but over half the users are not using tor and the site itself is encouraging them not to.

<comment><USER2> I know the article says they can connect using Tor. But by reading that paragraph, I couldn't be sure if that allows the distributed hosting to continue working properly, or if it just allows access but defeats the distributed hosting functionality.

</comment></comment></comment><comment><USER4> I feel like people should visit their ridiculous site and represent less hateful perspectives. The problem seems to be that they are living in an echo chamber.

I find it weird that only religious groups have missionaries, but that humanistic groups do not - certainly not on the same scale. "Hello, I am from the not-church of modern day humanists. Can we talk to you about ethics?"</comment>


PHP Commandments - <AUTHOR> http://biasedphp.com/php-commandments <comment><USER2> _> 7\. NEVER send emails directly from web page code Sending emails is slow. Incredibly slow. Don't tie up a precious web front-end process with doing so. Use a message queue instead._

Well. MTAs are message queues. Why use a third party software speaking a third-party protocol, adding more complexity only to eventually be talking SMTP anyways. As such, my message queue is a locally installed MTA listening on port 587, talking SMTP.

This is as fast or faster than any message queuing system you can come up with, but as it's managed by the OS, it's bound to work much better than third-party solutions.

I also get a lot for free in exchange. Stuff like automatic resending, queueing, queue management and so on.

As such, I would not strictly agree with point 7 in the article. Sure - don't send mail by talking to a _remote_ MTA, but if it's running inside of your local network, using any other queuing system provides nothing but overhead.

Furthermore:

 _> How do you set up Nginx so that it won't die or kill your server when you receive a big burst of traffic? You install it._

No. You are shifting the burden of correct app server configuration from apache to php-fpm or whatever other process manager you're using.

In the end it doesn't matter much whether you're down completely (misconfigured apache) or still somewhat capable of serving static files while unable to serve any dynamic pages (misconfigured php-fpm).

</comment><comment><USER3> I would add the following:

General tips:

* Understand how HTTP works (sounds trivial for a PHP developer, but at least here in Brazil, a huge portion doesn't do)

* ALWAYS keep php.ini with production settings and replicate the same into your development environment (Vagrant is a great option here)

* ALWAYS keep Apache or Nginx configs in sync among every environment

* NEVER trust $_SERVER['REMOTE_ADDR'] to get client ips when you are behind a Load Balancer (most modern frameworks already treat this, but make sure you are parsing it correctly)

* ALWAYS use `realpath` when you are symlinking folders

* Be REALLY careful when using `setlocale` for something, specially with numbers

* 2 basic things about Cookies: use `HttpOnly` flag whenever possible AND `Secure` flag when behind SSL

* Make sure the Database library uses PDO in its core

* Every service runs in UTC timezone (PHP, DB, OS etc). Offset calculations just for presentation or input (when explicitly necessary)

* Don't use $_POST and $_GET globals directly

* Support other methods (DELETE, PATCH, etc) by parsing the Request body properly

Personal tips:

* Use Composer

* Use Twig

* Use a nice Request/Response handler (Symfony2's HttpFoundation, for instance)

I am sure I forgot many things here, one day I compile a list with everything I've been through.

Hope it helps!

:)

<comment><USER4> _Don't use $_POST and $_GET globals directly_

May I ask why not?

<comment><USER5> If they aren't sanitized or validated they can generate exceptions or contain malicious data which leads to XSS or SQL injection after they've been reflected back to the user or added to a database. Since the values in these arrays come from the user, they should always be considered actively hostile and treated as such.

<comment><USER4> Ah, gotcha. So, treat them like they're "tainted", in perl parlance.

I was thinking that remark was intended more along the lines of "never use $_GET and $_POST directly, only ever access them via something like Symfony's sfWebRequest::getGetParameter/getParameterHolder/etc", which struck me as a bit overzealous as such rules go.

<comment><USER5> Yeah, just make sure _somewhere_ you're doing all the checking (type, length, character set, providing sane defaults, etc.) that other languages probably do for you.

Because users are evil and want to destroy you and PHP is only too happy to help them... :\

<comment><USER4> Yeah, I often feel like PHP is trying to destroy me.

/ used Haskell at uni, loved it

// first job in the real world is... web dev, on a sprawling legacy PHP codebase, with no documentation or tests

/// I miss my static guarantees :(

</comment></comment></comment></comment></comment></comment><comment><USER6> > NEVER hash passwords with MD5/SHA-1/Hash-of-the-day

> PHPass will make life easy for yourself and keep your users' passwords > secure.

MD5/3DES/SHA-1 are relatively broken. But saying "use this magical library" is really far from a solution. Who's to say that that library won't be broken tomorrow and then someone else won't write an article next week saying "don't use PHPass!"

Programmers just need to stay up-to-date with the latest trends and adjust their approaches accordingly.

> MD5/SHA-1/Hash-of-the-day is not, was not, and never will be acceptable.

MD5 was very much acceptable for the longest time. Back when everyone was using 3DES, MD5 was seen as the Bcrypt of the time. So saying that it "never was acceptable" is simply nonsense.

It was even what was implemented by the standard libraries and APIs of the time.

<comment><USER7> No.

>MD5 was very much acceptable for the longest time.

MD5 was never a good password hash. Neither is SHA1,256,etc. The reason is that they are crypto hashes optimized for speed. This is bad for passwords. What you should be using is the opposite: an expensive hash to compute. This is bcrypt which has been in use since 1999 (and what the PHPass is based on). This is a clear example of "Dont do your own crypto" because you dont know all the details.

>It was even what was implemented by the standard libraries and APIs of the time.

Yes, and this was a mistake. But to be fair DES used to take a full second to compute and bcrypt wasnt invented until 1999. This is why current password hashes use variable rounds so that we can increase the cost as computers get faster. When the algorithm is DESIGNED to be computed quickly it is fundamentally broken for passwords.

This is the reason that LinkedIn's passwords were vulnerable[1].

[1][http://www.itworld.com/security/280813/expert-calls- linkedin...](http://www.itworld.com/security/280813/expert-calls-linkedins- new-salted-hashes-useless)

<comment><USER6> > MD5 was never a good password hash. Neither is SHA1,256,etc. The reason is > that they are crypto hashes optimized for speed.

That's strange to hear you say that, because I remember people having huge arguments in the 1990s about how they couldn't use MD5 because it was /so/ slow and how 3DES was the only way to go!

I swear people love to re-write history.

> This is a clear example of "Dont do your own crypto" because you dont know > all the details.

That doesn't even make any sense. MD5 is a standard cryptographic function. If someone had used it they wouldn't be making their own crypto.

Hell, many of the standard libraries implemented MD5 when you asked them to protect a password by default. That's so far from rolling your own it isn't even logical to try and make the argument you're making.

Your entire post reads like someone who knows nothing about the history and is just spouting "OMG USE bcrypt IT IS THE BESTEST AND WILL BE SECURE FOREVER!"

bcrypt too will fall from grace and then you'll have someone making a post like yours saying "how could anyone use bcrypt, it is SOOO fast!"

<comment><USER8> > "OMG USE bcrypt IT IS THE BESTEST AND WILL BE SECURE FOREVER!"

5000 people in a room all shouting this repeatedly -- pretty much how I envision every Rails dev conference.

</comment></comment></comment></comment><comment><USER9> Can someone help me understand why a "helpers" or "utilities" file of functions is so bad?

Asking humbly because I do that and don't yet understand why it's bad / the alternative.

<comment><USER8> Helper files are a pain in the ass because they're usually all jumbled up and hard to maintain. In my experience with them, they come a zillion functions that are all unrelated, from input sanitization to XML processing to database initialization. Then, when you need to figure out what the hell is going on in your code, you have to wade through a forest of garbage just to figure out what the function is doing. God forbid you accidentally make a typo in ANOTHER function while editing the one you wanted -- now you've just introduced another bug without even realizing it.

Furthermore, in PHP, we devs are almost always using the same boilerplate over and over again (getting user input, etc.), so why would we use a "helpers.php" file when we instead could break out our code into more semantic, reusable chunks?

Instead, you should be creating classes (or at the very least, creating files that all have related functions, not just throwing all of your "helpers" into one file, so instead of helpers.php, you have inputSanitizer.php, htmlParser.php, et cetera).

For example, I see a lot of this kind of thing in "helper.php" files:

        function sanitizeInput($input) {
            $input = htmlentities($input);
            ...
            return $input
        }

What I personally _love_ to do because I'm OO obsessed is use a home-grown InputSanitizer class, so now when I have a new project, I don't have to copy over my "helpers.php" file and then strip out everything unrelated to my project; I just copy over InputSanitizer.php to the new project and do something like this:

        $username = InputSanitizer::getPostData('username');

MUCH cleaner and easier to maintain. Even better: if you're using classes and auto-loading, you'll never have to worry about includes again, you simply just call the class methods or instantiate.

There's a clean, wonderful side to PHP that I think a lot of people aren't taking advantage of.

<comment><USER10> I'd just like to note that that is not a particularly OO solution. You've essentially created a namespaced function. While this is still preferable to a bare function in a heterogenous helpers function file, it's certainly not a pure OO way of accomplishing the encapsulation of the InputSanitizer.

<comment><USER8>
       $username = InputSanitizer::getInstance()->getPostData('username');

There. Now it's OO ;P.

<comment><USER11> I would rather use Java in that case.

<comment><USER8> Your wish is my command.

        $username = array();
        exec('java sanitize.class ' . escapeshellarg($_POST['username']), $username);

</comment></comment></comment></comment></comment></comment><comment><USER12> > PHP version 5.5 (not yet released) will support Bcrypt natively via its > password_hash() function. Use it.

This makes it sound like PHP didn't support bcrypt before 5.5. It did. PHP always has bcrypt support in 5.3 and 5.4. In older versions it also has bcrypt support if the operating system supports it.

PHP 5.5 only added a wrapper around the low-level crypt() API, which makes password hashes more convenient to use and less prone to error.

<comment><USER13> The php 5.5 functions are really nice. Fortunately they can be shimmed into versions 5.3.7+. See:

<https://github.com/ircmaxell/password_compat>

</comment></comment><comment><USER14> As for #6, I'd go as far as "NEVER use include, period." I've seen about 1 actual use case out of the bazillions out there; almost certainly, _require()_ is the droid you're looking for.

I'd also add a #10: Use E_ALL | E_STRICT , and don't ignore it. PHP is trying to tell you of many problems, shutting it up is not the right answer.

<comment><USER15> Couldn't agree more with E_ALL|E_STRICT.

The current legacy system I am maintaining took me 2 weeks to clear up 90% of the NOTICE errors for using undefined variables etc.

Dirty code is dirty, and it is because of this that PHP has received so much negative publicity.

<comment><USER16> The completely brain dead naming conventions for function names (or rather, the lack thereof) is another. PHP has grown organically, just like the web, to fill a very irregular shaped niche and it shows that history in all the gory little details. That said it made me more money than any other programming language combined (including C, but it's a very close second).

Probably a lot of people have similar feelings towards Ruby, getting stuff done is what pays the bills.

<comment><USER17> Quick! Was it ($haystack, $needle) or ($needle, $haystack) ?

<comment><USER16> Or better still... one where it doesn't matter:

<http://www.php.net/manual/en/function.implode.php>

</comment></comment></comment></comment></comment><comment><USER18> For anyone interested in taking the next step for some of these suggestions (i.e., "OK, never put variables in SQL, what do I do instead then?"): I maintain <https://phpbestpractices.org>, which is an attempt to document the "best" solutions to common low-level tasks, like DB access, which have lots of possible dangerous approaches.

(Note I only talk about the version of PHP that ships with Ubuntu 12.04 LTS, so brand-spanking-new stuff like password_hash() isn't in there.)

</comment><comment><USER19> I have to disagree with your "Never use Ubuntu" way of doing things found here: <http://biasedphp.com/windows-linux-distribution>

Ubuntu's focus on the newest and latest is primarily on the desktop not the server. Better yet recommend user stick to LTS releases with 5 years of support.

</comment><comment><USER20> This whole thing could be replaced with the far better <http://www.phptherightway.com/>

</comment><comment><USER21>
        8. NEVER create a file of useful functions, even if it's called helpers.php
        This smacks of such a broken thinking process, it makes my teeth itch.

        If you have commonly-used functions, they should be integrated with
        the commonly-used parts of your code.

Example function used for debugging:

        function preint_r($arr) {
            echo '<pre>';
            print_r($arr);
            echo '</pre>';
        }

Where would something like this fit, if not a general helpers.php type file?

<comment><USER22> >Where would something like this fit, if not a general helpers.php type file?

In debugging.php alongside with other debugging helpers?

<comment><USER23> Maybe if it's used solely for debugging, but there are cases where simple functions aren't easy to place. Consider implementing the array_column function for pre-5.4 PHP. Or things like method pull, index grouping, or array_select_keys functions.

What helper library should a function like the following exist in?

      function array_select_keys(array $dict, array $keys)
      {
          $result = array();
          foreach ($keys as $key) {
              if (array_key_exists($key, $dict)) {
                  $result[$key] = $dict[$key];
              }
          }
          return $result;
      }

<comment><USER24> I have a similar dilemma with some of my helper functions. For example, I have starts_with(), ends_with(), and contains() for super easy string comparisons, is_between() for numerical comparisons, and custom implementations for a few built-in functions such as hex2bin() that don't exist in older versions. These are so general in scope that it would be awkward to place them in their own \Namespace\Class.

<comment><USER8> I'd probably break them all down into classes based on function (EasyString, EasyNumber, BuiltIn).

        namespace App\Library;
        class EasyString {
            public static function starts_with();
            ...
        }

and then just use them like this:

        use App\Library\EasyString as ES;

along with an autoloader.

</comment></comment></comment></comment></comment><comment><USER5> #1 oh, god yes. Variable variables and extract. I hate extract. Although i've only actually seen it in production in wordpress... Though i'd edit this to _always do the simplest thing that will work properly._ After all, the simplest way to do a SQL query in php that works is to just dump POST vars into a mysql function...

#2 I've actually gotten into an argument with someone who insists md5 is perfectly fine for password hashing if you salt it. Better, in fact, because it's faster. So yeah.

#3 Unfortunately we're also stuck with a ton of legacy code that does this, and would be all but impossible to refactor, and i'm still pointing out to people who post code like this to at the very least sanitize their stuff.

Seriously, if it's even possible, someone come up with an easy way to convert old-style linear SQL statements to parameterized queries or something in PHP.

#4 HTMLPurifier is good, but can be incredibly slow. htmlspecialchars is probably good where you don't need to sanitize data but still provide markup. I personally use htmlpurifier after a markup generator like Markdown, so I can enforce a whitelist against it. Still, YMMV but do SOMETHING.

#5 Might as well say don't use Wordpress either. I have yet to find a framework that makes me as angry as it does. Though granted, I haven't actually used cakePHP yet and I hear Zend Framework is a bit gnarly. Though "Use a framework when you can" is probably a good rule. Though eventually that ends up being "don't reinvent the wheel"

#6 WHO EVEN DOES THIS?!

#7 I don't know. Depending on how many you're sending, it's probably fine for low volume. It's probably right though.

#8 Don't really agree with this at all. In a global file, the body of helpful_function() is in one place, so if I want to change it or upgrade it, it's right there. If I integrate it into the rest of my code, I have to go look for it or else deal with multiple definitions in different files.

Though I will agree that if you're only using a helper function _once_ in your code, then clearly it needs to be integrated somewhere else. My definition for a helper function is that it gets used multiple times in no particular place.

#9 Most php developers work with whatever server their host is using, so this is of limited utility.

</comment><comment><USER25> I would recommend Doctrine DBAL[0] over Meekro.

0\. <http://www.doctrine-project.org/projects/dbal.html>

</comment><comment><USER26> Wow, this guy really hates CakePHP. If you know what you're doing and don't just presume Cake has done it for you, none of those problems should exist.

<comment><USER27> I find that to be very true. Seems a lot of amateur programmers pick up CakePHP for one reason or another without actually knowing PHP and try to drive every screw with the one hammer they have. When everything's suddenly broken they blame the hammer.

EDIT: Although I suppose the author's point of view is from the outside-in where he's tasked with cleaning up the mess that amateurs leave behind and has a bias against it.

<comment><USER28> If you know what you're doing you will not pass around huge arrays (in PHP) by value. Or pass them around (in CakePHP) at all, it's maybe a MVC warning flag that you do something in a place you shouldn't.

Related note: CakePHP 3.0 (current is 2.x) will use objects [1].

[1] [https://groups.google.com/d/msg/cake- php/-TLn6RpHt4U/EAP0lt2...](https://groups.google.com/d/msg/cake- php/-TLn6RpHt4U/EAP0lt2yjsAJ)

</comment></comment></comment><comment><USER29> The more of these posts I read, the more I believe most PHP programmers (as a majority) really aren't "clean coders" or have any intention of writing organised, maintainable. More likely they are just coders who write what they have to, whatever works and takes the least amount of time to get the job done.

A sweatshop language? Haha, no I take that back, it's not like that..

<comment><USER5> Yes, and Ruby on Rails users are just hipster kids who consider installing modules to be 'coding'.

Herp, and if I might be so bold, derp as well.

</comment></comment><comment><USER30> Few comments..

#3 assumes that the variable came from user input, it's not necessarily bad. In some cases (i.e. dynamically switching from ORDER BY ASC/DESC) it's quite acceptable. But PDO + prepared statements for sure.

#4 no need to use a library, htmlspecialchars/htmlentities are quite enough.

#5 I think many frameworks/libraries can go here - why pick on one?

#7 Mailgun, sengrid etc are becoming increasingly popular - worth mentioning.

#9 isn't PHP related

I agree with Piskvorrr - I favor require (though it isn't a function, no need for parenthesis.)

<comment><USER31> #3 should be #1, and further, it should read "If you insist on writing your own database layer, stop. You'll do it wrong in the worst possible way."

PHP has institutionalized SQL value injection. mysql_query cannot be removed soon enough.

<comment><USER30> #3 should be #3 :)

> mysql_query cannot be removed soon enough.

I agree. Bring on 5.5

</comment></comment></comment><comment><USER32> I agree with most of these except the one about helper functions but I think it was just written poorly (like the whole article). Definitely sort your functions into the files where they are most applicable, but sometimes (a lot of the time) you will have toolkit/helper functions which are globally applicable to the entire app. Where should those go? A helper or toolkit PHP file IMHO.

</comment><comment><USER13> Is sending email really that slow? In my experience, it just writes something to a local mail queue if your front ends can send email.

<comment><USER6> It can be that slow, yes. There is no assurances that will be fast, you're just hoping it will be.

Now you could argue "that's true of anything!" but in general you are forced to depend on local IO/CPU/RAM otherwise your site is struggling in general, by adding DNS/SMTP/etc you're just adding more "stuff" that your site relies upon.

Plus SMTP servers are "allowed" to go offline for short periods. The client should try to resend the email 2-4 additional times before giving up. Clearly a PHP script cannot do that.

<comment><USER13> I am totally confused. Who uses an SMTP server written in PHP? mail() just writes a bit of stuff into a mail queue by default.

<comment><USER6> People set their PHP config to connect to a remote SMTP server rather than a local queue.

It isn't something you can control in the code.

<comment><USER13> Thanks, I understand. Configuring PHP that way would be an unmitigated disaster. If you want that functionality, it makes the most sense to configure Exim or whatever to do that for you.

</comment></comment></comment></comment></comment><comment><USER30> The comments pretty much sum up how useful this blog post is... The upvotes merely show how educated a lot of the PHP community isn't

<comment><USER33> "The PHP Community" comprises massive swaths of developers, from people who have a hard time caring about things like "namespaces" and "encapsulation" to people who think and breath those concepts on a daily basis. It would be disingenuous to make such broad-sweeping and baseless statements about the entirety of a group of people.

Please don't get confused and paint everybody so broadly, it damages us all. There are many people working hard to improve the language and create a more modern environment around PHP.

</comment></comment><comment><USER34> If you want to see why you should always use prepared statements in your code, take a look at this [1]. Old and outdated, but still very much applicable.

[1]: [http://technewsgalore.com/site/04/15/sql-injection- tutorial-...](http://technewsgalore.com/site/04/15/sql-injection-tutorial-by- for3v3rforgott3n)

</comment><comment><USER35> Are people still using PHP without frameworks these days?

<comment><USER36> The "cool kids" in PHP are using Laravel 4. It's a well made framework. I'm doing a REST API in it at work and the lack of mind share and docs is probably the worst part about it (it's still in beta to be fair). Most of the time I ended up reading the framework code.

PHP leaves a lot to be desired though. It boggles my mind how developers who love what they do have the patience to stick with it. Example: Feature request for the unless control structure: <https://bugs.php.net/bug.php?id=40296>

<comment><USER5> Is anyone using Laravel 4 in production already? I thought it was still in beta.... I'm still messing with 3.

<comment><USER36> I've seen a few people doing it. The API is quite stable since the end of last year or so I've heard. I didn't start using it until recently and I haven't encountered any bugs and whenever I gear up to do a pull request someone else has already done it.

<comment><USER5> ooh, neat. I'll have to start on that then.

</comment></comment></comment></comment></comment><comment><USER37> #6 re: autoloading. PSR-0?

</comment><comment><USER38> Most of the items on that list are not specific to PHP.

Some of the stuff pointed out is up for discussion (I hate when people use the word 'NEVER' when they are writing about their point of view, especially when programming is a topic).

</comment><comment><USER8> _These_ are the "PHP Commandments"? How about we set the bar a little higher? Anyone who has had longer than 1 day's worth of training with PHP should know these things.

<comment><USER14> _Should_ is the operative word. I keep being amazed at what people _ought to_ know, yet _don't_.</comment></comment>


Fox Loses Latest Bid to Halt Dish's Place-Shifting Technology - <AUTHOR> http://www.hollywoodreporter.com/thr-esq/fox-loses-latest-bid-halt-718342

<comment><USER2> Aereo is significantly different from Dish's technology. With Dish, in the case of "Primetime Any Time", the Hopper receiver (the DVR) receives the tv signal and records the broadcasts from Fox and I think 3 other stations onto a dedicated partition on it. From there, if the customer has the Sling adapter accessory or the built in sling adapter the customer can stream any live or recorded content to just about any internet connected device. So using Prime Time Anytime where the commercials are skipped, and streaming the content over the internet is pretty awesome for the DVR owner. This is all different from Aereo which for all intents and purposes held the DVR and then streamed the output of it to the user via the internet.</comment>


Ask HN: Corporate structure for equity? - <AUTHOR>

Apologies for the long winded question. All of my experience is straight contract work. Someone comes to me with an idea, my shop builds it for them for a fee- deal done. Since this scenario is a little different, I'd like to get your collective input from past experiences before I start talking to a contract attorney.
Recently I was approached by a business man who wanted a project developed. We started working out a spec, I gave him a quote, and he gave me a counter-offer that was pretty fair and offered some equity (10%) to make up for the difference between my initial price and his counter. Normally, I'd start cutting features, take his counter offer, and tell him to keep his equity. But this guy has an _uncanny_ ability to build buzz and successful (profitable) products.
This is a SaaS type deal which will be profitable from day one. There's no way we're going to be a target for acquisition or IPO, but I think it's probably going to do 100k < net income < 250k in the first year. (At which point I'm hoping to sell my shares back to him.)
What kind of corporate structure should we choose? I know everyone says C-corp in Delaware, but we're not raising any $. Should we still go with a C-corp? How would liquidation/transfer of this stock work? If I sell my shares to my partner, is it taxed as long-term capital gains?
How would owners draw work? Am I immediately entitled to 10% of the profits the second we become profitable? Is there a buffer period before I'm able to draw? Do we agree in advance on how much money gets reinvested into the business? I'd imagine that'd be his call since he's the majority holder, but is there a way to guarantee a percentage of profits I can draw out on a regular basis? What's the convention here?
As a partner, am I entitled to inspect the books whenever I feel like it? I don't have any reason to believe he'd screw me but I'd like to cover my bases rather than have things get messy later on.
Thanks guys! :) <comment><USER2> TALK TO A CPA. Not just any CPA, but a really good one. Depending on your location I'm happy to recommend one.

The issue with equity, no matter the structure, is that it comes with a pretty difficult tax burden. That equity counts as taxable income. Be prepared for that... If this guy is forming a new entity to cover this, there is still going to be some level of initial valuation. You'll be taxed on 10% of that. If there is some sort of vesting schedule in place, it gets even more complex (in that situation you need to fill out a form electing to be taxed on the whole amount today, rather than as it vests).

The point being: You need to be concerned with more than just the structure of the entity, but how this will effect your personal income situation as well.

\</comment><comment></comment><comment></comment><comment></comment><comment></comment><comment></comment><comment>-

As for the rest, there is already some good advice here. If you go the LLC route, then you need to specifically talk to a lawyer to ensure that you are protected when the operating agreement is drawn up. With a LLC there is very little implicit protection for you, everything has to be specifically spelled out in the partnership agreement.

A C-Corp would give you more options, for things like preferred stock.

The suggestion about taking this is a revenue share is probably sage advice. If you're goal is to generate passive income, then equity is not the answer. Equity has no intrinsic value until you actually sell the business (and depending on the structure it may not have value then). I've seen partnership agreements that give x% to a partner, but provide a minimum floor for another. Meaning that when the company sold the first partner took $10M right off the top, and then the other partner only got 10% of the rest.

In other words, if you go the equity route you really need a lawyer and a CPA to help you sort through all of the implications. This is not simple stuff.

</comment><comment><USER3> IANAL/IANAA/etc.

This sounds a little messy. Draws/dividends aren't mandatory or an entitlement. As the majority holder and presumably the CEO, draws, reinvestment, and fat bonuses (to him) would be at his discretion.

If you really want to do this as an ownership thing, I'd ask for preferred shares and explicitly enumerate some rights/protections. (You have the right to inspect the books; a mandatory dividend payout; spell out his compensation in advance; etc.)

What about doing this as a partnership/royalty deal? You take 10% of all proceeds, net of hosting expenses? That sounds like it would be much cleaner. He could still buy out your share of the partnership at a later date.

</comment><comment><USER4> Ah, the Mr. Wallet and Mr. Brains scenario. :-)

Get a really good lawyer who has done this many times before. Be sure to do a shareholder's agreement -- a prenuptial agreement for the business. Things WILL go sideways. Mr. Wallet will think his money caused the venture to flourish. You'll think "Meh, my ideas were so good his money wasn't really needed." Resentment ensues. Business dies.

Oh. And say all the hard stuff now. Talk it through. All of it. "What if I decide I hate your guts? Then what?" Etc.

But yeah. As one of the commenters said, why are you getting equity when Mr. Wallet could just rent your brain? Ask him: "Why me rather than someone else?" "Why now?" "Why this arrangement?"

Hint: sometimes Mr. Wallet has less wallet than he appears to have. Maybe not your Mr. Wallet, but I've seen this happen.

EDIT: done correctly, the legal fees for setting up your business would be large. A non-amateur lawyer might go north of $20K by the time it's done. Maybe the transaction costs of setting up co-ownership aren't worth it. Maybe you follow the Hollywood approach: take a small percentage of the gross.

/Phil.

</comment><comment><USER5> If the plan is 100% to sell the shares back to him and you have a fairly certain idea of how much you want to sell them for and in what time frame, then just spell it out that way. The deal is $X up front and $X in 12-18 months.

If the business succeeds in 12-18 months then the money to pay you will be there, if it doesn't then the contract will be worth as much as your "shares" (zilch).

</comment><comment><USER6> It sounds like you want an LLC. The main reason to choose a C Corp is to support equity investment.

With an LLC you literally own a percent of the company, rather than a number of shares (which equates to a percent). This can be bought or sold just like shares. However, you may choose to put restrictions on exactly what circumstances one of you can sell, and to whom, and with what provisions. Often, the other partner gets right-of-first-refusal to buy at the price that you were about to sell it at. This would be fine in your case, since your partner is your target.

LLCs can divest their profits to shareholders at the end of each fiscal year, at which point it is taxed as personal income. With a corporation, this would be considered a dividend. Dividends are "post-income" -- they are paid from profits, not revenue. This means that the money is taxed as corporate profit (15%) before it reaches you. Then you are taxed again as an individual.

Furthermore with a C Corp you pick up a bunch of reporting requirements. For starters, you need a Board of Directors, and you are required to have an Annual Meeting, the minutes of which must be filed with the government.

I'm not sure about financials. My understanding is that as a member of an LLC you are privy to all of that, but you can do a lot with the operating agreement to change defaults, so make sure you have your own counsel if your partner is the one drawing up the docs.

</comment><comment><USER7> I'm a little confused.

 _...this guy has an _uncanny_ ability to build buzz and successful (profitable) products._

If he is that good, why would he offer you 10% of his new product just to shave a little bit off the initial development cost?

</comment><comment><USER8> short answer: dont do it unless you consult with your lawyer or 1000% trust that person. Its COMPLICATED. no matter what kind of corp you end up incorporating, what kind of shares/options you get, you can very easily end up with nothing if this guys is more experienced than you.</comment>


Linked-in: the money keeps rolling in - <AUTHOR> http://blogs.ft.com/techblog/2008/10/linkedin-the-money-keeps-rolling-in/

<comment><USER2> To me money pouring in from customers is much more noteworthy than money pouring in from investors.

</comment><comment><USER3> A better headline would be "Linked in: the equity keeps trickling out".

<comment><USER4> To make themselves feel better I think they call it a "balanced round".

They say they've been profitable since 2006, but why are they still taking money?

<comment><USER5> You can be profitable and still need to raise money to expand more rapidly.

<comment><USER4> Agreed. Which easily explains their first couple of fund raising events. But they've been profitable (according to themselves, of course) for over 2 years.

Something weird is going on. I honestly don't think they're profitable.

</comment></comment></comment></comment><comment><USER4> What's everyone think of this? At this point they pretty much have to go public right?

A $2 or $3 billion (or more) acquisition isn't very likely and anything less than that would be unacceptable to their investors. I've heard some nasty things about LinkedIN, but it was all from indirect soruces.

Did anyone on HN ever work there or know someone who did?

<comment><USER6> I agree that they basically would have to go public. Who would want to buy them for a couple of billion dollars when MySpace is looking like a bad investment at 500 million?

I thought their valuation last round sounded awful high, but I don't know very much about their business. Raising yet another round of funds seems like a sign of trouble.

<comment><USER7> What makes you think that MySpace was a bad deal at 500mil. They have $800mil in revenue, all the recent valuations have placed it's value in the 5-10 billion range. Even with the dip in the ad market it's still a very valuable property.</comment></comment></comment>


Drawbridge - <AUTHOR> http://research.microsoft.com/en-us/projects/drawbridge/ <comment><USER3> This is very exciting research. There's doesn't seem to be much new information on the page (it's been posted a few times before). In this recent presentation[1] (PDF) MSR's Galen Hunt gives a nice high-level overview of Drawbridge, possible applications and some more details about their current progress.

The Graphene Library OS[2] is a similar implementation for Linux and was released a few months ago. In particular the Graphene Host ABI[3] is adapted mostly from Drawbridge.

[1][http://vee2014.cs.technion.ac.il/docs/VEE14-present601.pdf](http://vee2014.cs.technion.ac.il/docs/VEE14-present601.pdf)

[2][https://github.com/oscarlab/graphene](https://github.com/oscarlab/graphene)

[3][https://github.com/oscarlab/graphene/wiki/Graphene-Host- ABI](https://github.com/oscarlab/graphene/wiki/Graphene-Host-ABI)

</comment><comment><USER4> The "picoprocess" here seems very similar to Linux's "seccomp" mechanism for restricting the kernel API surface. Current sandboxing mechanisms on Linux (such as Chrome's various sandboxes) use seccomp to restrict almost all syscalls, and their APIs come from IPC to more privileged processes.

Two notable differences:

On the one hand, seccomp provides much more flexibility about the subset of kernel API offered to the process, rather than just saying "here's 45 syscalls".

On the other hand, Drawbridge claims to run unmodified Windows applications; they may have an efficient mechanism for trapping NT "syscalls" and redirecting them to their "user-mode NT kernel" ntoskrnl.dll. However, this might just mean that they run unmodified applications making Win32 library calls, and the libraries have been modified, in which case programs making NT kernel syscalls would not run unmodified.

I'd really like to see a standard mechanism on Linux, similar to the "personality" mechanism, that augments seccomp with an efficient process for defining a new "syscall" layer. That would make sandboxing much simpler and more efficient.

<comment><USER5> This looks like they're actually bundling the kernel and all appropriate libraries into the package.

"Persistent Compatibility: allowing host and application to evolve separately. Changes in the host don't break applications."

"A library OS is an operating system refactored to run as a set of libraries within the context of an application.

While Drawbridge can run many possible library OSes..."

This implies to me at least that the app and the "OS" the application sees is a complete isolation from the host OS.

But I might be misinterpreting things here, the video seems to go into a better explanation

[http://channel9.msdn.com/Shows/Going+Deep/Drawbridge-An- Expe...](http://channel9.msdn.com/Shows/Going+Deep/Drawbridge-An-Experimental- Library-Operating-System)

Strategically this could allow Microsoft to drop lots of backwards compatibility cruft in their mainstream host OS and vastly reduce development cost and complexity.

See my previous comment here [https://news.ycombinator.com/item?id=8245682](https://news.ycombinator.com/item?id=8245682)

</comment></comment><comment><USER6> This seems to map more to Chrome's Native Client/PPAPI than to anything like container virtualization: a reduced set of pretend syscalls that actually go to an interop library that talks to the host OS. It's just missing the "static analysis to ensure it only uses those syscalls" step.

</comment><comment><USER7> Seems like Microsoft's response to docker, although I have no idea if it actually is, in terms of precedence. But certainly aimed at the same idea.

<comment><USER8> Not really. It is a research project, and predates Docker.

<comment><USER7> LXC containers predate Docker, too. In any case, it doesn't really matter whether it's an actual response, or not.

<comment><USER9> Docker is not anything, Docker is a wrapper for cgroups and namespaces - <USER2> utilized by LXC.

Infact, Docker started as a wrapper around LXC. It literally configured and shelled out to lxc-start in order to orchestrate containers.

This however, is much much different to cgroups/namespaces.

What the Drawbridge paper describes is a full user-mode kernel . If you want the analagous implementation on Linux look at User Mode Linux, or the Graphene stuff that has already been linked to.

<comment><USER8> Or look at the netbsd rump kernel ([http://rumpkernel.org](http://rumpkernel.org)) which also runs under Linux or standalone.

<comment><USER7> Thanks for this comment. I had some time to read through this pdf ([http://lib.tkk.fi/Diss/2012/isbn9789526049175/isbn9789526049...](http://lib.tkk.fi/Diss/2012/isbn9789526049175/isbn9789526049175.pdf)) and I have a much better understanding of the differences between a user-space kernel and containers now.

</comment></comment></comment></comment></comment></comment><comment><USER10> _> it consists of a closed set of 45 downcalls with fixed semantics that provide a stateless interface._

If the features 800+ syscalls can be put into 45 syscalls, why not make an operating system that has only 45 syscalls?

Then make the kernel modular.... and we've made a full circle in the OS design :)

<comment><USER11> > _" why not make an operating system that has only 45 syscalls?"_

Because much of Microsoft's licensing revenue is contingent upon continuing to support the edge cases that are inevitably not part of the set of programs that can be dropped into such a sandbox without problems.

<comment><USER12> You missed the joke. NT was originally a pretty hardcore microkernel, with even things like graphics drivers being in userspace. However, in the name of performance, more and more stuff was brought into kernel space.

<comment><USER13> NT was never a true microkernel (much less a hardcore one), and was never intended to be. It was never designed to have any protection between its internal "subsystems" (file system I/O, security, HAL, drivers, etc.) — everything runs in kernel mode, in the same address space, and communicates using direct calls, not IPC.

NT is sometimes mistaken for a microkernel partly because of the graphics driver problem, and partly because it contains a module which Microsoft actually refers to as "the microkernel". This part consists mostly of the scheduler.

What is true about the NT kernel is that it's modular, with strict internal API separation between each subsystem, and that kind of design was (as far as I know) inspired by actual microkernels, as was the idea of hiding the kernel behind "OS personalities" such as Win32.

<comment><USER14> IRPs are the kernel "IPC" mechanism used by NT... And for whole classes of drivers/subsystems IRPs are the core processing mechanism. The IO manager calls to process IRPs could very well be traditional microkernel message passing API's complete with task switching and message copies.

While NT is not a microkernel, from a kernel API level it appears to basically be one, only missing the fact that everything is not actually isolated.

</comment></comment></comment></comment></comment><comment><USER15> It is important to note how this will shake the current state of the application virtualization market.

There is no docker like solution for Windows. All the big players (VMware, Microsoft, Symantec, etc) do tricks to isolate the applications. The tricks are instrumenting API calls and adding filtering drivers. With these solutions only less than 70% can be virtualized and the process can be really difficult.

<comment><USER14> Hu? Can you elaborate on what you mean by this (app-v, and other windows sandbox/package tools) not being as complete as docker?

Because from what I've seen of the current state of docker, non trivial linux applications seem to have issues in docker as well because they depend on specific things which are not being namespaced well (say /sys manipulations for example, ioctls, or even use filesystem specific APIs).

Docker seems to work well as long as one stays close to web server functionality. (aka LAMP like stacks which tend to only manipulate network sockets and traditional files).

<comment><USER15> Yes, it is very simple. Docker.io uses LXC where the virtualization layer occurs at the kernel space while applications such as VMware ThinApp and others occur at the user level intercepting Windows APIs which are at a higher level than the kernel. App-V and SWV adds a filtering driver as a way to sandbox registry and filesystem.

One difference in the approach is that, for example, with Docker.io you can have your own isolate network interface while with the current Windows approach this is not possible.

</comment></comment></comment><comment><USER16> "a version of Windows enlightened to run efficiently" is just begging to be quoted out of context.

<comment><USER17> That usage of the word 'enlightened' is giving me the howling fantods.

</comment></comment><comment><USER18> This seems like Microsoft's response to Bromium vSentry which is a very impressive product. [http://www.bromium.com/products/vsentry.html](http://www.bromium.com/products/vsentry.html)

<comment><USER9> Not quite. Bromiums solutions make use of VT-x/VT-d/EPT. This is pure para- virtualised approach. Atleast from what I can see, it's possible it uses VT-x/VT-d/EPT to implement the process isolation - just somewhat unlikely given how it's presented.

</comment></comment><comment><USER19> So, this is this a means to bridge the gap between Hyper-V, Hyper-V app streaming and Docker on the windows side? I'm kinda confused what the use case is compared to other existing product offerings.

<comment><USER20> "Docker for Windows" is what hit my mind while reading it. Worth noting it's from MS research, so it doesn't mean you'll see it as is (if at all).

</comment></comment><comment><USER21> I'm wondering if the Library OS could be used in the Wine project or in a new Wine-like project to run Windows programs under other operating systems.

<comment><USER22> I suspect that would run into copyright problems as the Win32 replacement is still owned by Microsoft. You could re-make the 40 some odd kernel calls, but the real magic here is the Win32 full replacement with the 800+ calls.

At this point I doubt Wine would be interested, unless somehow Microsoft released most of it as OSS.

</comment></comment><comment><USER23> Would this be comparable to Sandboxie? ([http://www.sandboxie.com/](http://www.sandboxie.com/))

</comment><comment><USER24> Not sure I get it... Basically you would get rid of IIS, and run vNext apps in a drawbridge pico process ?

<comment><USER7> I don't think so. The idea is to provide for Windows the same kind of lightweight containerization as docker/LXC provides on linux. So if it were to work the same way, you'd install IIS into your container, and run the container on a host. Having read through the post now, which doesn't have a lot of detail, it seems to me that the picoprocess and library OS concepts are a consequence of not having true kernel-level support for namespaces and something like cgroups. Docker and LXC containers don't host a minimal OS, they share the existing kernel in well-defined ways.

</comment></comment><comment><USER25> This sounds a lot like Docker for Windows, am I right ?

I might have to try it to understand it, but it is exciting.

<comment><USER9> It's more like User Mode Linux for Windows.. except ofcourse it's User Mode Windows...

</comment></comment><comment><USER26> Is this similar to User-mode Linux?</comment>


Facebook still won't let you "friend" Christopher Wylie - <AUTHOR> https://www.cbsnews.com/news/facebook-still-wont-let-you-friend-christopher-wylie/ <comment><USER2> It does bother me that a money-prioritised private entity currently controls so much of society and in such a deep way. If Fb doesn't agree with your culture, your minority group, or your opinions, you are arguably, in effect, censored from 'society'. They need to be regulated by more democratic and neutral entities, i.e. governments.

Democratic governments are not allowed to shut down free speech which directly criticises them. Facebook now has more power - in effect - than most democratic governments.

<comment><AUTHOR> It bothers me more how they'll put on a smile and declare themselves kings of transparency... and then do this anyway

Like do you not directly see your own hypocrisy?

</comment></comment><comment><USER3> I suspect Facebook bans accounts of people they dislike fairly regularly. A friend of mine was banned recently due to FB having a spat with a company he once cofounded. At the time of the conflict said friend had had nothing to do with the company in question for several years. They banned him anyway, without warning or explanation, and all his connections, as well as messages and so on dating back at least 10 years were lost. The account has not been restored since. Tells you everything about what kind of company FB really is.</comment>


Ode to the use-after-free: one vulnerable function, a thousand possibilities - <AUTHOR> https://scarybeastsecurity.blogspot.com/2017/05/ode-to-use-after-free-one-vulnerable.html <comment><USER2> I think the generalization of "use-after-free" to "use-after-invalidation" is the most important part of this article, showing that it's more about object "lifetimes" than simply a memory management flaw. This is one reason why we can't consider "modern C++" to be memory-safe.

I wonder if this sort of vulnerability is possible in Rust, and if it is, is there a way to use Rust's borrow checker to make it impossible?

<comment><USER3> > I think the generalization of "use-after-free" to "use-after-invalidation" > is the most important

> I wonder if this sort of vulnerability is possible in Rust

Rusts borrow checker is designed for the more general case of "use-after- invalidation" and `free` is treated as a simple invalidation of what happens to be a heap allocated structure.

Interestingly, the borrow checker also prevents invalidations that are still common in memory-safe languages such as iterator invalidation.

<comment><USER4> What? It's very easy to get use-after-invalidation in Rust. Destructors called during unwinding see stuff in an invalid state. You can probably make a language that prevents use-after-invalidation in safe code (e.g. mark all accessible mutable references as "dirty" during unwinding, and require unsafe code to "clean" them) but Rust isn't trying to do that AFAIK.

<comment><USER5> Could you provide an example of such code? I was under the impression that certain things were disallowed _because_ destructors aren't allowed to see the struct in an invalid state.

A common case where I see people trying to do this is when you have a struct where you are trying to replace a member variable:

        struct Foo {
            thing: Vec<i32>,
        }

        impl Foo {
            fn something(&mut self) -> Vec<i32> {
                let temp = self.thing;
                // If we panicked between these two lines, then the struct would be in an undefined state
                self.thing = vec![1];
                temp
            }
        }

This code produces the error `cannot move out of borrowed content`. For those curious, you normally would write this as

        use std::mem;

        impl Foo {
            fn something(&mut self) -> Vec<i32> {
                mem::replace(&mut self.thing, vec![1])
            }
        }

<comment><USER4> How about this?

        struct Foo { bar: Bar }
        struct Bar { message: &'static str }

        fn change_foo(foo: &mut Foo) {
            change_bar(&mut foo.bar);
        }

        fn change_bar(bar: &mut Bar) {
            bar.message = "Invalid";
            if true {
                panic!();
            }
            bar.message = "Valid";
        }

        impl Drop for Foo {
            fn drop(&mut self) {
                println!("{}", self.bar.message);
            }
        }

        fn main() {
            let mut foo = Foo { bar: Bar { message: "" } };
            change_foo(&mut foo);
        }

The destructor of a struct sees a broken invariant of a nested struct.

<comment><USER5> I see, I think you are using a different definition of "invalid" than I and the grandparent are. Rust will not allow you to access _memory_ that is invalid, but your own invariants can certainly be broken.

For what it's worth, the solution I've seen for this type of case is another struct that is used to restore to an acceptable state:

        fn change_bar(bar: &mut Bar) {
            let mut restore = Restore(bar);
            restore.message = "Invalid";
            if true {
                panic!();
            }
            restore.message = "Valid";
            // Don't rollback on success
            std::mem::forget(restore);
        }

        struct Restore<'a>(&'a mut Bar);

        // Put back to an acceptable state
        impl<'a> Drop for Restore<'a> {
            fn drop(&mut self) {
                self.0.message = "Restored to some state";
            }
        }

        // Sugar so we don't have to know about the wrapper
        impl<'a> std::ops::Deref for Restore<'a> {
            type Target = Bar;
            fn deref(&self) -> &Bar { self.0 }
        }

        // Sugar so we don't have to know about the wrapper
        impl<'a> std::ops::DerefMut for Restore<'a> {
            fn deref_mut(&mut self) -> &mut Bar { self.0 }
        }

</comment></comment></comment></comment></comment></comment><comment><USER6> A simple way to approach this problem in C, that will work in most cases, is something like this:

       void safer_free(void **x) {
          if(x!=NULL && *x!=NULL) {
             free(*x);
          }
          *x = NULL;
       }

the key part being to set the original pointer to NULL so a future use will cause an exception, not a vulnerability.

<comment><USER7> Except this won't work when multiple pointers exist to the same data.. which is arguably when this kind of stuff is most difficult

<comment><USER8> If you have multiple pointers to the same data with different lifetimes you already need some kind of reference counting or garbage collection.

<comment><USER9> Not necessarily. It's safe if lifetimes of the other pointers are guaranteed to be shorter than the lifetime of the object.

<comment><USER8> That's why I wrote "with different lifetimes".</comment></comment></comment></comment></comment>


TechCrunch gets a new design.. again - <AUTHOR> http://www.techcrunch.com/?

<comment><AUTHOR> For some reason I'm intrigued by the different TechCrunch redesigns. For a site as big as TC, I'm sure their design decisions are based primarily on ways to increase revenue and attract users, yet I always end up feeling like their designs are still lacking. Maybe it's the fact that ads take up at least 1/3 of the layout..

</comment><comment><USER2> I'm surprised there's been no post about it. They had a nice write up about the last one (which I really liked).

</comment><comment><USER3> Oh look, more ads.</comment>


Enter Darth Vader's Tie Fighter - <AUTHOR> https://sketchfab.com/show/eIFt03aD0BrZPcTVU4F9jfw9duj <comment><USER2> <James Earl Jones voice>I find you lack of interior ... disturbing</James Earl Jones voice)

Admittedly, you would be making stuff up since not much of the interior is visible in the movies but...

</comment><comment><USER3> Would someone please build a 'don't distract freelancers on Hacker News' app? My morning started off so strong, now I want to watch the original trilogy.....

(Great model!!)

<comment><USER4> > now I want to watch the original trilogy.....

The original original trilogy or that "Special Edition" crap?

Edit: Despite the down-votes, I stand by both my opinion __and__ phrasing. The 1997 Special Edition, 2004 DVD, and 2011 Blu-ray releases were done poorly (a.k.a., half-assed). They suffer from numerous issues that suggest an inexperienced team was used for the "restoration". See: <http://savestarwars.com/specialeditionfail.html>

<comment><USER5> How about the despecialized edition?

[http://originaltrilogy.com/forum/topic.cfm/Harmys-STAR- WARS-...](http://originaltrilogy.com/forum/topic.cfm/Harmys-STAR-WARS- Despecialized-Edition-HD-REMASTERED-is-now-released/topic/12713/)

<comment><USER4> > How about the despecialized edition?

I'm a fan and an active user at originaltrilogy.com :-)

<comment><USER6> Is there still a version out there where Han shoots first?

<comment><USER4> Are you asking this question seriously?

</comment></comment></comment></comment></comment></comment><comment><USER7> <nit>It's a TIE Interceptor.</nit>

And, it's nice work.

<edit>Doh. I stand corrected. Vader _did_ fly a TIE Fighter - technically the "TIE Advanced x1".

Looks like I'm overdue to rewatch SW:ANH. _smile_ </edit>

<comment><USER8> It's a TIE Advanced x1. Although features developed for it were incorporated into the later TIE/IN Interceptor, the x1 had substantial differences, such as shielding and FTL capabilities. The mass-production craft resulting directly from the x series was the TIE/D Defender.

<http://starwars.wikia.com/wiki/TIE_Advanced_x1>

<comment><USER9> That brings back memories of playing the MS-DOS "Tie fighter" game from the mid 90s where you could pilot the Tie Advanced later in the game, IIRC it was also slightly faster than a standard Tie Fighter.

However from what I remember of the original movies though there was no reference to Vaders craft having shields or hyperdrive (maybe I'm wrong?).

So I wonder if the technical details of the craft were invented specifically for the game and then retrofitted into the overall mythos?

One thing that always amused me about star wars was that the Imperial forces must have had a military budget that would make global GDP look like pocket change but had such clearly flawed designs for all of it's equipment (crap fighters, walkers, death star etc) while the Rebels had stuff that worked much better. Was Lucas trying to say something about the inevitable result of the military industrial complex?

<comment><USER10> No, the idea was that the Empire was using clones for their pilots so they didn't give a crap whether they lived or died. Therefore they received the cheapest equipment possible. That way they could often win by sheer numbers. Only important people got nice equipment that would keep them alive.

On the other hand the rebels considered every pilot they had as rather important since they had so few. That, plus the fact they had so few in the first place, warranted more expensive yet more robust equipment.

So, as the rebellion continued, the rebels were winning more often than losing and were swaying more and more to their side. Which made it easier to obtain the same equipment. The Empire had to respond in kind because pilots started becoming important, especially the pilots that had learned how to win against superior equipment. Kind of sucks to lose your best pilots because you were too cheap to get them cheap shields. This led to the development of later TIE fighters that had shields and other "rebel" equipment. You didn't really see things like the TIE Interceptor's until Return of the Jedi time, which by then the rebels had the A-Wing to counter that as well.

This is the reason that TIE Fighter is one of the greatest games ever made. You don't know how much it sucks to face a highly trained opponent with superior equipment until you fly the TIE fighter into combat. It's like being the pilot of a flying trash can with two lasers attached to it. Also keep in mind that a common tactic of an X-Wing or Y-Wing pilot was to fully charge forward shields and just ram the poor guy in the TIE fighter. No need to debate who survived.

</comment></comment></comment></comment><comment><USER11> Is it possible to download the 3d model in a format that could be used with a 3d printer?

<comment><AUTHOR> Soon! We are working on it.

<comment><USER12> What's the licensing situation with such models? I seem to remember Lucasfilm (<http://www.lucasfilm.com/divisions/licensing/>) being pretty active ($3 billion in licensing revenue in 2011), but presumably they're not interested if there's no money involved?

<comment><AUTHOR> Today, without download option, we are just considered like YouTube: a service hosting files uploaded by users, on which we have no control. When we launch download & commercialization of models, we will indeed have to find a licensing deal for copyright content.

</comment></comment></comment></comment><comment><USER13> All I get is a "100%" loading indicator, then the spinning pizza of death and repeated "unresponsive script" warnings for several minutes until I gave up.

</comment><comment><USER14> Very nice.

I thought the 4 stripes on top were actually windows, though (since you can see through them in the movie, such as in this photo I found: [http://media.photobucket.com/image/recent/ThePropDen/cee7e16...](http://media.photobucket.com/image/recent/ThePropDen/cee7e16f.jpg))

</comment><comment><USER15> Amazing work, great model. really clean. Reinforces that IE is really messing up by not supporting webGL. Works smooth as butter in chrome for me.

</comment><comment><USER16> How large is the file? It's taking a VERY long time to load.

<comment><AUTHOR> It's not that big, 2.8 mb, but keep in mind that more than 300 people are browsing it right now :)

</comment></comment><comment><USER17> WebGL doesn't work for me, guess i'm screwed

<comment><AUTHOR> Which browser? You should ideally use chrome or firefox, or activate WebGL from developer mode in safari.

<comment><USER17> I'm using Firefox (latest) and at one point tried to enable WebGL. I'm not one to keep trying to fix something just to make a web page work, though.

Does WebGL even work in software rendering mode, or do you need to have hardware rendering enabled? I have no idea if it is or if my drivers support it (Windows) but I would hope we're not forcing everyone on the web to have direct rendering now.

<comment><USER18> IIRC Firefox disable WebGL if you are on certain, known buggy, versions of your GPU driver.

</comment></comment></comment></comment><comment><USER19> Awesome model !

</comment><comment><USER20> This is useful how? This is no better than a read-only image, with right click 'disabled'. It does look pretty.

I'll just head to thingiverse or clones. Those sites let you <gasp> download the models.

<comment><USER21> The model actually comes from here

<http://www.blendswap.com/blends/vehicles/vader-tie-fighter/>

where it is download-able</comment></comment>


Chart shows cause of the gender wage gap - <AUTHOR> https://www.vox.com/2018/2/19/17018380/gender-wage-gap-childcare-penalty <comment><USER3> From the methodology of the cited Danish study where the data comes from it includes those who left work outright and this represents a wage of 0. That is going to be quite the reduction in wages no matter where you start, to drop to 0. The charts don't seem so dramatic considering that. And the conclusion is no surprise either if you factor that in, of course wages drop when you are not working. No mention of that in the article though, doesn't fit the narrative I guess.

<comment><USER4> You're only reading at surface level. It's described in the text, but for a quick sense of it look at the graphs on page 39 and the footnote - <USER2> earnings the participation is not considered but for hours worked and wages it only considers those in the labour force. You can see that the effect is less pronounced but it's still there. If I read this right women earn 10-15% less after having at least one child. Noticeably the dip in year 1 is much weaker, so in the overall earnings graph this dip might be due to women not working (much) in the first year and then going back to work - but on average with a comparably lower salary.

What you should also consider here is that this article is not looking at wage comparison within one company. It's looking at overall earnings in the population with a very thorough and deep analysis. It's an analysis for policy making, not for grandstanding. And for this whether women continue to work is also relevant - as the authors note this is quite a significant consideration even for labour force planning/statistics. Moreover thinking of e.g. pensions this is a very important point - as women will have lower pensions due to lower lifetime earnings.

Please do look at the whole picture, rather than just try to validate your viewpoint. There are many interesting tidbits here, for example that earnings fall 10% for each following child. The graph on p42 comparing childless women and mothers is also particularly impressive.

</comment></comment><comment><USER5> > The gender wage gap is mostly a penalty for bearing children.

> Men also worked, on average, a few more weekly hours and had a bit more > prior experience as they entered the workforce.

> Childless women have earnings that are quite similar to men's salaries, > while mothers experience a significant wage gap.

Hard-hitting stuff Vox. I've got some ideas for the next article in this series, feel free to use any of them:

\- Shocking study shows micro-transactions prey on children

\- Groundbreaking research shows businesses don't trust ex-convicts

\- Scientists prove that Captain Crunch damages the roof of your mouth

</comment><comment><USER6> So, the subtitle of this article is "The gender wage gap is really a child care penalty." But why is it seemed a "penalty"? People choose to do different things, and it seems quite normal to me that people who choose to take focus off of their work to focus on their family would end up in lower positions than people who stayed focused on their careers.

<comment><USER7> Yes — but as you can very clearly see from the chart, only women's earning drop significantly after a child. Men's do not.

<comment><USER8> Only women, generally, go through pregnancy and take significant time off of work to raise children.

<comment><USER9> It's amazing that such an obvious statement has to be said!

The title of the article is like something out of a comedy: it's "stunning" that people who drop out of work for a while earn less, and that more women than men drop out of work because of childcare? How many people on the street would really be stunned to "learn" that? It's the basics of how the species has always reproduced itself.

</comment></comment></comment></comment><comment><USER10> Nice article, the title is a bit clickbaity though.

Ideally it should contain the thesis since it's pretty succinct. Something like "The gender wage gap is mostly a child care gap"

</comment><comment><USER11> _He finds that women start to gravitate toward different jobs after the birth of a child, ones with fewer hours and lower wages._

The concepts of "the second shift" and "pink collar ghettos" are related to this. Women need to be able to give time and energy to the child when they are at home. They can't afford to work so hard that they are too exhausted to wake up if a child comes into their room in the middle of the night.

Men with well-paid jobs tend to be exhausted after work, too exhausted to do things like that. If both parents get that exhausted, then no one is able to provided the care the child needs.

Even if you are a heartless monster, society puts pressure on parents to actually take care of their own kids. Someone has to do it.

For various reasons, this tends to fall more to the mother than the father.

I'm actually kind of weirded out seeing this piece. I thought this was incredibly well established and fairly obvious on the face of it to boot.

I will add that all the reading I have done over the years suggests that countries that primarily address the gender gap by trying to lighten the child-bearing and child-rearing burden for women are the ones that have generally been more successful in reducing the gap. Simply decrying the gap as sexism or whatever tends to not be particularly helpful.

This can be addressed in part via cultural practices. It isn't just about laws or official policies. From what I have read, a lower divorce rate and a general expectation that the extended family helps out with the kids tends to be helpful. When a woman stays married and her mother or aunt is the primary babysitter while she is at work, you see women do better at advancing their careers.

</comment><comment><USER8> Saw chart. Not stunned.

</comment><comment><USER12> Interesting that men who eventually will have kids earn less than men who eventually won't have kids (4 years prior to the first child birth, fathers- to-be still earn less). That is not the case for women.

Difficult to tell how pronounced that is without the raw data though.

<comment><USER13> It's an interesting observation.

Maybe "~all" women expect to have kids?</comment></comment>


IP question is 192.168.255.x a Valid Ip scheme? - <AUTHOR> http://arstechnica.com/civis/viewtopic.php?t=631325 <comment><USER2> Some web host assigned a client an x.x.x.255 address. It took me a week to convince them that the .255 assignment was the reason that certain people couldn't get to the web site.</comment>


Who Gets to Graduate? - <AUTHOR> http://www.nytimes.com/2014/05/18/magazine/who-gets-to-graduate.html

<comment><USER2> I'm going to be the unpopular voice in the room here, but as someone who has worked my ass off my entire life, a 1030 SAT and 3.5 in high school hardly seems like "acing" anything. In fact, that barely seems mediocre. College is a whole different ball game and it's much harder. I've seen kids with 800 math SATs and 4.0s in hs fail intro math in college. Why can't people accept that sometimes things are just hard?

<comment><USER3> You're right and the article eventually gets to that but not before using some socioeconomic sizzle.

To recap, the article opens with a URM female getting shell-shocked in her first semester. She's overwhelmed and sinking. The author then jumps into broad socioeconomic analysis of outcomes. Fast forward 23 pages (!!!) in the article, and a re-direction to the actual success factors (Grit™)...you learn that she made it through the fall with a B+ in Stat and a reasonable 3.0 freshman GPA. I'm happy she turned the corner, but I...felt misled >_<.

Though I really enjoyed Paul Tough's book _How Children Succeed_ , I take issue with his claim:

 _It is only students facing the particular fears and anxieties and experiences of exclusion that come with being a minority — whether by race or by class — who are susceptible to this problem. Those students often misinterpret temporary setbacks as a permanent indication that they can't succeed or don't belong at U.T._

It's not limited to minorities and women...UT's no joke -- like many colleges. The honors programs (there are many at UT) are lights out. It's a humbling experience, and it's not surprising to hear that the article's poster-child, who "never had to study for math tests [in high school and] aced them all without really trying" got pooped on freshman year. I don't have the numbers but plenty of kids, regardless of URM status, got/get their bell rung in UT freshman courses.

</comment></comment><comment><USER4> Pretty sure I've seen this on HN before. Can't find the link, unfortunately.</comment>


Show HN: CadenceBot – Help your team move faster by organizing code reviews - <AUTHOR> https://cadencebot.com <comment><AUTHOR> Hey HN!

This is our first public release. We're looking for any feedback y'all might have. This is just the first step in the sequence of automating all of those annoying things that software developers deal with every day.

We'll be listening to this HN thread, but if you want to get further involved head on over to [https://cadencebot.com/beta- feedback](https://cadencebot.com/beta-feedback) and chat with us directly!

Thanks!

</comment><comment><USER2> Nifty. Just signed up. This looks like it's really going to help. And free during beta? #nobrainer Thanks!

</comment><comment><USER3> Very cool. Does this work for open-source too?

<comment><AUTHOR> Absolutely! Open source or closed source :)</comment></comment>


Why aren't Japanese-style toilets more popular outside of Japan? - <AUTHOR> https://mobile.twitter.com/patio11/status/1219442071519387648 <comment><USER2> Same could be said about the whole "smart toilet" craze.</comment>


Children Beating Up Robot Inspires New Escape Maneuver System - <AUTHOR> http://spectrum.ieee.org/automaton/robotics/artificial-intelligence/children-beating-up-robot

<comment><USER2> > And as for grown ups? It looks like adults are reluctant to abuse robots > that respond in a lifelike way, and empathic adults even more so.

Recognizing it as a machine, no matter how cute, I'd be reluctant to damage property.

I wonder if I'd take better care of my car if it had an AI in it that got to know me.</comment>


Why does Google prepend while(1); to their JSON responses? - <AUTHOR> http://stackoverflow.com/questions/2669690

<comment> Stealth- I think it's important to note that this is a bug that effects older browsers only. Modern IE, Chrome, and Firefox have security measures that do not allow scripts to capture values passed to constructors of a literal. That way, this hack is only needed for older browsers and will hopefully not be needed at all in the future. For more info: [http://stackoverflow.com/a/16880162/372767](http://stackoverflow.com/a/16880162/372767)

Also note that this attack, JSON Hijacking, is _different_ than a CSRF (Cross Site Request Forgery) and has little to do with CSRF tokens.

<comment><USER2> Actually, ie is still vulnerable to a very similar attack in some cases, specifically you can leak responses containing small json array by inlining the json as a script[src=vbscript] tag. Disclosed here: [http://en.wooyun.org/bugs/wooyun-2013-023](http://en.wooyun.org/bugs/wooyun-2013-023)

with the status "unable to contact the vendor or actively neglected by the vendor" :-/

Edit: I meant "injecting" not inlining. Thanks chc for pointing that out.

<comment><USER3> If it has to be inlined, how is that the same vulnerability? I thought the vulnerability was that script tags can fetch external scripts and a local script intercept the results. If you have to inline both scripts, you can only attack yourself.

<comment><USER2> Sorry, used the wrong term. I mean it can be injected as a script tag into an xdomain site.

</comment></comment></comment></comment><comment><USER4> There is a long discussion about this at

[https://news.ycombinator.com/item?id=5168121](https://news.ycombinator.com/item?id=5168121)

(from about a year ago)

</comment><comment><USER5> Chrome DevTools recognice while(1) and for(;;) in the network tab (JSON preview). Sadly, Firebug still doesn't know how to handle this and shows no JSON preview :(

</comment><comment><USER6> Does anyone know what browsers allow you to override the Array constructor? I was under the impression that modern browsers don't.

<comment><USER7> If the attacker knows the structure of the reply, `__defineSetter__` can be used to extract the JSON content as well. From [0]:

            <script type="text/javascript">
                Object.prototype.__defineSetter__('Id', function(obj){alert(obj);});
            </script>
            <script src="http://example.com/Home/AdminBalances">/*Boom*/</script>

[0]: [http://haacked.com/archive/2009/06/25/json- hijacking.aspx/](http://haacked.com/archive/2009/06/25/json-hijacking.aspx/)

<comment><USER8> That's interesting. Apparently, the __defineSetter__ call is still valid in Chrome.

Example [http://jsfiddle.net/V53BL](http://jsfiddle.net/V53BL)

<comment><USER9> I can't get this to work with an actual API call.

        <script>
              Object.prototype.__defineSetter__('user', function(obj){alert('Hijacked!');console.log('Hijacked!', obj)});
              var trigger = [{"user":{}}];
         </script>
         <script id='current-user' src="http://my.secretapi.com/users/current"></script>

Where the API returns something like

        [{'user':{'name':'Joe Bloggs'}}]

(Un)Fortunately (depending on which side of this you're on...) they've plugged the holes?

<comment><USER8> It works on an explicit set, but not on initialization of the object. So:

var x = [{"user":"dude"}]; This won't trigger, and this is what the script include tag executes via the response.

x.user = "wow"; This will trigger, however.

<comment><USER10> And that's by design. That's how setters work. There's no security risk from this, given cross-domain JSON loads.

</comment></comment></comment></comment></comment></comment><comment><USER11> A good description: [http://stackoverflow.com/questions/6339790/what-does-a- ajax-...](http://stackoverflow.com/questions/6339790/what-does-a-ajax-call- response-like-for-json-data-mean)

The idea: you need such workaround only if you return JSON Array.

Most of the API returns JSON Object in which case the attack does not work, it will result in syntax error.

</comment><comment><USER12> After seeing this I went to see if AngularJS had anything built in to mitigate JSON hijacking and they do. It will strip ")]}',\n" off of json responses if included from the server.

[http://docs.angularjs.org/api/ng.$http#description_security-...](http://docs.angularjs.org/api/ng.$http#description_security- considerations)

</comment><comment><USER13> So does this solve the problem with using remote JS templates (advocated by DHH and 37s), what was outlined here [1]?

[1]: [https://github.com/jcoglan/unsafe_sjr/blob/master/README.md](https://github.com/jcoglan/unsafe_sjr/blob/master/README.md)

<comment><USER14> it does, but it's worst workaround. we chose request.xhr? check

</comment></comment><comment><USER15> Would introducing a syntax error into my JSON help prevent CSRF attacks? We don't use JSONP.

<comment><USER14> bug doesn't exist anymore

</comment></comment><comment><USER16> Is it correct to use the Content-Type application/json on this? IMO: not.

(I've just tested Firefox network view and it breaks the response display with syntax error -- there should be an option to select the format).

</comment><comment><USER17> It looks like modern Chrome doesn't trigger setters when constructing from literals, so that's encouraging. [http://jsfiddle.net/KY4Sa/](http://jsfiddle.net/KY4Sa/)

</comment><comment><USER14> Google is wrong IMO: there is no need to have such workaround. In rails we had similar problem [https://community.rapid7.com/community/metasploit/blog/2013/...](https://community.rapid7.com/community/metasploit/blog/2013/12/29/remote- js--an-insecure-pattern-in-rails-code) and fixed it by adding request.xhr? check on server side.

while(1) is ugly solution to currently non-existing problem.

<comment><USER4> Does your solution assumes referrer will not be manipulated on the client side?

<comment><USER14> my solution is request.xhr? check. the link above is only to explain what rails-bug was. I don't think checking referrer is a good idea there.

<comment><USER2> Hey Egor, article author here. How come you are not such a fan of checking referer? It cannot be a global fix (some sites depend on serving xdomain scripts, have lots of users with proxies that alter headers etc), but it should work well for many cases no?

<comment><USER14> it works of course, but to be compatible with many environments we need something more reliable than Referrer.

</comment></comment></comment></comment></comment><comment><USER18> What happens when you visit a malicious website and your computer gets stuck on `while(1)`? Syntax error would be better?

<comment><USER17> Because the script is useless, malicious websites won't bother including it, so the folks at Google don't really care what it actually _does_. Or, if the site wants to be malicious by just giving you a while(1), they can do that without Google's help.

</comment></comment><comment><USER19> Why doesn't this prevent CSRF?

<comment><USER20> CSRF is different from JSON hijacking, but they're closely related.

This only prevents attacks that uses a script to execute a get method and returns a JSON array.

JSON arrays can be "executed" as if it was javascript. The attack relies on modifying what javascipt does when this faux script is ran.

So if you put a "while(1);" in there, it prevents it from finishing. Thus preventing the exposure of the sensitive data.

It's similar to CSRF since that attack relies on the user to have an active session to be able to access sensitive data, but they differ in MO.

</comment></comment><comment><USER5> Facebook uses "for(;;);" as it's one char shorter.

</comment><comment><USER21> It's the bot.

</comment><comment><USER22> Smart!

<comment><USER23> What?

<comment><USER22> The while(1) to defeat hot-linking.</comment></comment></comment>