Jeffrey van Binsbergen.nl

C and C++ are not dead

Recently I’ve picked up C++ development again and it is great. As most people know, I love fast applications and I love making them. With C#, Python, Node.JS and many more higher level languages gaining in popularity and performance getting pretty cheap, low level languages like C are often forgotten. Hopefully this article will encourage more people to give it a try.

Efficiency matters

A big reason to choose for a low level language is of course: Efficiency. You’re working close to the hardware and you suddenly gain flexibility to do all kinds of fun things, especially with memory access. And it still matters for any application which needs to do some actual work. Conversions, Machine Learning, Image processing or what I’m using it for at this moment: IoT data processing and aggregation. It all runs incredibly fast. To make it more fun for myself I’m testing it on a Raspberry PI zero (5 dollar Linux computer) and it can still handle thousands of clients at the same time. It is great!

Another reason why to think of efficiency: Running it in the cloud. Running things in cloud is actually not that cheap, especially if you need a bit more performance than the budget option. Most problems in the cloud can be solved by throwing a credit card towards it but all the costs add up. By making a small efficient application for any important processing, you can really get the required specs down.

Making something very efficient allows people to do more with your application. If data from a chart takes half a second to get generated, you can only put 1 or 2 on a web page before it feels ‘too slow’. When putting some effort in making a small efficient application. You can display your charts with a lot of additional information instantly and extract information from it the user actually wants to see.

Portability

It is incredibly portable if you are careful with platform specific features and libraries. The same code can run on Windows, Linux, FreeBSD, etc. with just some small modifications to the platform specific functions. You can even try to run your code on an embedded system like an ESP8266. This is especially useful when making a library which can be integrated into a wide selection of other projects on different platforms.

Downside

Making your application takes more time. You will have to worry about things you otherwise never see. Clean up your used data from the memory. A lot of the handy flexible features of your favorite high level language won’t be available. Also some other people will probably think you’re insane. I can definitely recommend taking a look and experimenting with it.

Developers can do more than just typing code

A good programmer is an artist. Making sense of an difficult idea and actually implement it in a way which makes customers happy is an art. A good developer will find solutions and make things possible on a smart and efficient way. Typing code is just one of the things a developer has to do, and it is the boring part.

Unleash the creativity

Creativity is an important part of making a good application or website. There are some challenges and there are literally thousands of ways to deal with them. Often someone has to think outside of the box and that is alright. Most developers actually became a developer just to deal with those challenges! It is like a complicated puzzle and you can actually feel proud solving it and often together with other developers.

Layers, Layers, Layers

Nowadays a lot of software development is done in a very guideline-followed style. People make abstractions of everything, adding more and more layers to any application. Maybe throw in some dependency injection and other fancy stuff which suddenly seems to be a requirement for everything. This style is forcing developers to think in a very similar and limited style. Every feature you add is like walking the same road. Surely it looks nice on the progress charts but there is no room for creativity at all. Often new technologies are introduced to the system to keep things interesting, even while some “old methods” would’ve been even better.

It can make a big difference

Most applications can be ‘dumbed down’ to a level where creativity during developing isn’t needed. Code will be made. Resources will be thrown and in the end an application will work. But the code will probably not be very efficient. There are no smart tricks being done and people will just hope the used libraries and framework is efficient enough to deal with the difficult problems. Also the application will do just what the requirements were and nothing more. Boxes are ticked, money is earned. Done.

Give some freedom to the developer, let them get a feel for the application and what people want to do with it. They’ll get motivated and enjoy working on it, and they actually want it to turn into a good application. Let them see how the customer is responding to it. The application will turn out better, faster and actually something which will make a customer happy.

Stay careful

Of course there are many reasons people started programming like we do now. Just letting everyone do whatever will sometimes result in messy code which are difficult to integrate together. Also progress is harder to track as a creative moment isn’t always guaranteed and sometimes ideas just don’t work out for various reasons. Let developers work together on things and make clear requirements about what the application should do for a customer and also what future plans are with said application. Also make sure developers get enough time to really focus on this application, including some time to refactor their code.

The Big Security Checklist

Is your website or application secure or will your company be the next one leaking all customer details? The internet is filled with people looking for flaws on every website they can find and some don't have good intentions. In the past I was also one of the people crawling the internet for anything interesting. During my research I discovered that there were security flaws everywhere. Now it is time for me to help you and your company to prevent (most) of those flaws.

Never trust external data

Any data coming in your (web)application can contain something you didn't expect. The values can be changed or the format can be different than what you expected. For websites that will be everything in a web request (url, get/post parameters, Other posted content, Cookies, Referer, User-agent, etc.). For other applications this can be everything it reads from a file, url, socket or even UI input.

A few examples of results when not checking your received data are: SQL Injections (you get a query instead of just a number), Buffer overflows (Usually able to run own code), Errors which give some more info about your environment, Uploaded scripts instead of uploaded images. Accessing admin features (missing authentication checks), XSS attacks (User submitted HTML/JavaScript on your site). It can also be something as stupid as ordering non-existent product plans: When your website gives the user to choose between 1 and 2, and the attacker changes the form so it submits 3 or -1 or the famous JGDGDSKJGDSJSDG.

The big amount of glitches/hacks in games is purely possible because the client is allowed to send his own (modified) location and inventory. Note that for games this is usually done because of performance and latency reasons (You don't really want to have your server check every collision of every player movement). Games can encounter this by doing simple checks (Is the player moving faster than allowed?) and having report systems.

This also applies on anything encrypted! Encryption only prevents people in between to see the data (and usually tampering with it). The data is still encrypted on the machine of a user. A user can just attach a debugger to every process and see/change the real data. SSL connections are usually even easier: You can just create a self signed certificate, trust that certificate, redirect a connection to go to your own tunnel software which tunnels the connection to the real server. This allows you to see and change any data being sent to the server and back.

Don't just trust data coming from another server in your network either as someone can gain access to that machine and start doing the same tricks.

Give your application only access to the resources it needs

This is the point I've seen most companies fail at. Usually an attacker will come in using a leak in your web application. Web applications can be quite big and they are facing the internet. It just takes one small bug/undocumented feature in your (or your framework/server) code and Mr. Anderson will be able to do more than he is supposed to.

First your database connection. Is this done under a user which only can access the website database and not anything else? Good! SQL injections can still happen and database servers allow some nasty queries, like executing commands or reading files. Sometimes I saw that the old 'mysql.user' table was accessible with all the bruteforce-able password hashes of all users. Most of the times they even had a /phpmyadmin ready to use with the just gained credential information. Easy-mode! Even with just access read access to the right table you can find out the Admin-user password hashes and brute force them, giving your thankful hacker a new area to find even more and bigger security holes.

File access is also something you should pay attention to. Often a website is hosted on a web server with multiple other websites. Think about what a security researcher can see when looking in your inetpub/wwwroot folder: (Decompilable) source codes, config files, log files. Always run a website under a limited user account with only (read) access to the folders it needs to access. You wouldn't be the first to get broken into because of an old forgotten promotion site. This is also why you should be aware to host your website on a shared web host: One flaw in their configuration, and all websites are compromised. You would be surprised how often those big web hosts make mistakes on this area.

Network access to any other resources: What servers are accessible from your web or application server? Are there any file shares or internal web services which doesn't require any authentication? Is the data between servers encrypted?

Remember: Gaining administrator-access to everything is not the goal of a security specialist. It is to gain access to interesting data, or giving him any advantages normally not possible (For example with a web shop: Marking an order as paid or changing prices).

Stay up-to-date

Software bugs happen a lot. Even a small piece of software written by the best group of programmers is bound to have a few bugs. Luckily new versions with bug fixes are released to counter those bugs (often even before they are known to the public). A down side with releasing those new versions: People can compare the versions and find out what bugs were fixed.

Always make sure applications on your environment are on the latest stable version, including your Operation System. Any flaw in any application on a server can be helpful when trying to access even more resources. A flaw in your server application may allow a user to run code under a very limited user account, but by also using a flaw in an unpatched Windows installation the code can suddenly be run evaluated and do everything.

Limit access of people

You may have the world most secure system but you also still have people in your company with access to resources to be able to do their jobs. Those people are a common attack point for security specialists. It is probably the most difficult one to deal with when protecting yourself from nasty security incidents.

Educate people to recognize phishing attempts and test them often. Teach people that an attack may come from anywhere (mail, phone, in real life or even in their personal life) from anyone (customers, friends, co-workers with less access). Never leave your computer unlocked and don't just run anything. Maybe that program a friend downloaded for you is infected with a trojan because he used an untrustworthy source. That program can log your keystrokes and screen when you log in when working at home a month later.

Also update the software on all workstations. Keep track what people are running and on which version it is. Disable applications and plugins an employee doesn't need (like the Flash or Java browser plugin). A common way of attacking nowadays is by putting some malicious advertisement on big popular websites which get probably visited by half of your company's employees. Those advertisements can use exploits (Browser, Java, Flash, etc.) to run code on the machine without the user even noticing. Of course run a decent virus scanner, but be aware that it won't stop everything.

An attack can even be from the person itself. Audit and monitor everything and don't give the person access to more resources than he/she needs. Do remember that you're dealing with people, please be thoughtful of what limitations you apply and how users will experience them. When people need access to something for an assigned task, don't make them fill in 3 forms and wait 8 weeks.

Make logging in a bit more secure by adding two-factor authentication whenever possible (Not just your employees, your website users as well). Give instructions on how to choose a safe password and enforce it by applying password restrictions. Do not use easy guessable default passwords for new employees and do force them to change it at the first time they log in.

Monitor any suspicious behavior

Watch any errors happening on your websites. When poking around your overly interested visitor will usually trigger some errors before finding anything useful. Pay attention to requests after that: If the errors stop he may have given up, or he have found something. For a security researcher errors are usually a sign that input is badly/not checked. Just hiding the errors is not enough, there are more ways to notice that you are able to do more than you're supposed to.

Suspicious behavior can also happen from within a company. Is a person trying to access a lot of resources? Pay attention to it and find out if it was for a valid reason.

Be thankful to those reporting a flaw

If you're very lucky, someone found a flaw on your website and actually reported it to you instead of abusing it. Of course it goes without saying that dealing with this flaw must be your number one priority. But also reward the person for reporting it. For you it is just a small gift, for them it is a reason to stay nice and keep reporting bugs to companies. Most places I've reported serious security flaws to didn't respond or started threatening me directly. As you would probably understand, the choice of 'Reporting the bug' will be less obvious after that.

Conclusion

Breaking in a system is like puzzling, and with most puzzles: People who do it often get quite good at it. It is not uncommon for a security researcher to use multiple holes in different systems to get to the interesting data. Always expect to get weird data in your applications and add checks for it. Make sure your software is on the latest stable version and limit what is possible when having access to a part of the environment.

Review your security often for your current environment but also review your new software designs for security flaws. When in doubt: Let a professional security specialist check your security.

Awesome JavaScript Tricks

Just like C-Sharp, JavaScript has some unique tricks not known to everyone. In this article I'll share some of the tricks I know about JavaScript. Like everything with JavaScript, some tricks will require a recent version of your web browser but all tricks should work in all major browsers.

Object.defineProperty

This is a method available in all recent browsers (Firefox 4+, Chrome 5+, Safari 5.1+, Opera 11.6+, IE 9+) which allows you to do unique and awesome stuff with properties. For example you can use Getters and Setters:

var obj = {};

Object.defineProperty(obj, 'myprop', {
get: function() {
return myprop * 2;
},
set: function(value) {
alert('Setting value to '+value);
myprop = value;
}
});

obj.myprop = 5;
alert(obj.myprop); // 10

Another use is making a property read only and unchangeable (not even by another defineProperty call).

var obj = {};
obj.theAnswer = 42;

Object.defineProperty(obj, 'theAnswer', {
writable: false, // This makes the value read only
configurable: false // This makes this property undeletable
});

obj.theAnswer = 5;
alert(obj.theAnswer); // 42

The defineProperty method can be useful when making a custom elements, which can act just like a native element does (for example, directly updating the UI after you do: customElement.value = "123";).

Arguments as array

You can use the arguments keyword to get all parameters. Use this to make functions which accepts a unspecified range of arguments.

function printf(text) {
var i = 0, args = Array.prototype.slice.call(arguments); // Turn the arguments-object into a normal array

text = text.replace(/\%s/g, function(a) {
return args[++i];
});

return text;
}

alert(printf("Hello %s! Your score is %s", "Mr Anderson", 1337));
// Hello Mr Anderson! Your score is 1337

edit: Changed [].slice to Array.prototype.slice.call after someone pointed out it had some issues with Chrome

Override default methods

Like in every programming language, Objects in JavaScript have a few default methods you can override.

var TestObject =  function() {
this.valueOf = function() {
return 42;
};
this.toString = function() {
return "I am a test object";
};
};

var obj = new TestObject();
alert(obj == 42); // true
alert(obj); // I am a test object

This can be useful when making objects comparable to each other or making your code easier to debug (You can get a nice textual representation of your object instead of just a [object] text).

Function methods

In JavaScript, there are quite a few ways of working with functions. A more unknown feature are the methods available at functions. For example: By using the method apply you can call a function and give the parameters as an array, you can also change the 'this' scope of that function.

alert.apply(this, ["I am a message"]); // Shows 'I am a message'

The bind method can also be quite useful, especially when working with timeouts and intervals.

var TestObject = function() {
this.someValue = 100;
this.doSomething = function() {
alert(this.someValue);
};

setTimeout(this.doSomething, 1000); // undefined
setTimeout(this.doSomething.bind(this), 2000); // 100
}

new TestObject();

In Firefox, you can also retrieve the source code of a function:

function myFunction() {
return 1337;
}
alert(myFunction.toSource()); // Shows the function defined above including source

With keyword

Supported by pretty much every browser, but not recommended for use as it can causes a lot of confusion. Still for the sake of informing I'll include it in this overview. The With keyword allows you to use properties and functions from an object, without putting the object name in the front (As if all properties and functions are global).

with(document) {    
with(body) { // document.body
var textNode = createTextNode("Bla"); // document.createTextNode
appendChild(textNode); // document.body.appendChild
}
}

It also works when eval-ing code, Which can be useful if you want to support scripts with short function names. Note that it does not limit the script! Every other function will still be available. It can also be used to temporarily override global functions and properties:

var obj = {
alert: function() {}
};
with (obj) {
alert('This alert is not visible');
}

Comma operator

Next to all the more common operators, JavaScript has another operator: The Comma operator. The comma operator allows you to do some actions before returning a value. This can be useful in places where JavaScript only expects a single value. It can be compared to the && and || operators, but with the comma-operator all expresssions are always executed. Example:

function IsAlwaysFalse() {
return false;
}

function IsAlwaysTrue() {
return true;
}

// Continues when the value is not False/Null/0/Undefined
alert(IsAlwaysFalse() && 42); // False
alert(IsAlwaysTrue() && 42); // 42

// Continues when the value is False/Null/0/Undefined
alert(IsAlwaysFalse() || 42); // 42
alert(IsAlwaysTrue() || 42); // True

// Always continues
alert((IsAlwaysFalse(), 42)); // 42
alert((IsAlwaysTrue(), 42)); // 42

Scope labels

It is possible to put code in a specific scope and name the scope. By doing so it allows breaking out of a specific scope using the 'break' keyword.

myLabel: {
alert('I am shown :)');
break myLabel;
alert('I'm not :(');
}

Multiple lines

And a small trick to end this article with: Use the \ character to allow using multiple lines in your string definitions. Just put them on the end of the line like this:

var x = "abc\
def";

Note that it doesn't actually add a linebreak in the string. You still have to use \r\n for that to happen.

Conclusion

Like C-Sharp, JavaScript has a lot of hidden gems. This is just a small selection of the lesser known things I know about. Do you have some awesome tricks in JavaScript worth a mention? Let me know!