Arquivo

Archive for the ‘Programação’ Category

Great definitions – Callback Function

junho 21, 2010 Deixe um comentário

“A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. The special thing about a callback is that functions that appear after the “parent” can execute before the callback executes.”

Source: http://docs.jquery.com/How_jQuery_Works

A new use for the “for” loop

maio 19, 2010 Deixe um comentário

“public static void main(String args[])” is not alone!

janeiro 16, 2010 Deixe um comentário

For those who are starting to learn the Java programming language, it is very common to see people say things like “Your main function must always look like this:”


“Otherwise, it won’t compile!”

If you buy this statement you will fall for it when you go take the SCJP certification. There are many other ways in which the main method can be declared. Here are some of them:

To simplify, you can follow these rules:

  • The only access modifier allowed is public and it must be present.
  • The static keyword must always be present as well.
  • The args argument does not need to be called args. It can have any name you want (as long as that name follow the rules of a valid Java identifier, of course)
  • Once you put the method’s return type, you need to put the name of the function right on way. This is valid in any method declaration, not only main.
  • The main method must always return void. It can’t return anything else. This is specially trick for C/C++ programmers, once in those 2 languages you could write something like int main().

That’s it folks! If you have any questions or improvements to suggest, feel free to put them on the comments!!

PS: If you saw any mistake in my English, please, send me an email or a comment telling me. I’m Brazilian, therefore I’m not an English native speaker. I would really appreciate being corrected! Thank you in advance!

W3Schools

janeiro 3, 2010 1 comentário

If you are a web programmer (or a web designer) and you don’t know the website W3Schools, you have no idea what you’re missing! As the own website states:

Because time is valuable, we deliver quick and easy learning.

At W3Schools, you can study everything you need to learn, in an accessible and handy format.

The main technologies (when it comes to web programming and web designer) are covered. Among them, are: HTML, XHTML, CSS, JavaScript, JQuery, XML, ASP, PHP, SQL and AJAX. (unfortunately it doesn’t have anything about Servlets, JSP and JSF…)

What makes W3Schools so good is that it actually teaches you just what you need to know and, at the same time, with a great depth. You have to see it for yourself. Few tutorials around the Internet have the same quality as the ones in the W3Schools.

Another interesting feature present in W3Schools is an on-line editor. You can modify all the given examples and see the changes right on way, without using anything else. Very convenient 😉

In short, when talking about web programming and web designer, W3Schools is one of the best (if not the best) website of tutorials available on the Internet. Give it a try!

PS: If you detected any mistake in my English, please, send me a comment or an email telling me. I’m Brazilian, therefore I’m not an English native speaker. I would really appreciate being corrected. Thank you in advance!

Protecting your HTML forms from SQL Injections

outubro 18, 2009 Deixe um comentário

sql_injectionSQL Injection is one of the most common attacks your website can receive. Yet, there are a lot of programmers that do not give special attention to it. In this post, you will understand how SQL Injections are make (with examples) and how you can protect your applications from it.

SQL (Structured Query Language) is the most common language used to retrieve and put information into relational databases. The most famous databases all use it, like MySQL, Oracle, PostgreSQL… Also, SQL is really easy to learn. With that in mind, isn’t absurd to assume that a huge percentage of the web applications around the Internet use SQL.

Let’s start the examples with a simple login page. It will be use to exemplify all next examples:

form

And here is the database (I’m using MySQL, but you can use any DBMS you like):

sql_databases

From now on, on the server side, I’ll be using JSP and Servlets to handle the login stuff, but you could also use any other server-side language (like PHP and ASP). Here is the Java class that will handle the authentication:

java_total

Now, we can make the login into the system by using the user “User_here” and the password “password123”.

The server side authentication expects something like this:

SELECT sqlinjection.id FROM sqlinjection WHERE BINARY sqlinjection.user = ‘X’ AND sqlinjection.password = ‘Y’

Where X is the value you put into the field “User” and Y is the value you put into the field “Password”. So, when you type the correct username and the correct password, the expression above turns out into this:

SELECT sqlinjection.id FROM sqlinjection WHERE BINARY sqlinjection.user = ‘User_here’ AND sqlinjection.password = ‘password123’

But, what if the person (the attacker) just know your username and have no idea what your password is? They could use SQL Injection to make the login without knowing the password. On the user field, the attacker would type User_here and, on the password field, they could type something like: a’ or ‘1’=’1. So, your SQL would turn out into:

SELECT sqlinjection.id FROM sqlinjection WHERE BINARY sqlinjection.user = ‘User_here’ AND sqlinjection.password = ” or ‘1’=’1′

Which is the same as:

SELECT sqlinjection.id FROM sqlinjection WHERE BINARY sqlinjection.user = ‘User_here’ AND (sqlinjection.password = ‘a’ or ‘1’=’1′)

That means if the password is ‘a’ OR ‘1’ = ‘1’ than the right part of the AND will be true. Once 1 is always equals to 1, than (sqlinjection.password = ” or ‘1’=’1′) will always be true. Bingo! The attacker has successfully entered into your system just by knowing your username.

But it could be worse. The attacker could even delete your table. They could type something like this into the password field: a’; DROP TABLE sqlinjection —

So, the SQL would turn out into: SELECT sqlinjection.id FROM sqlinjection WHERE BINARY sqlinjection.user = ‘User_here’ AND sqlinjection.password = ‘a’; DROP TABLE sqlinjection — ‘

SQL Injection Webcomic

Following this idea, the attacker could also delete an entire database. They could type something like this into the password field: a’; DROP DATABASE injection

Now, I know what you’re thinking: “How does the attacker would know the name of my tables and my databases?”. That’s simple: they can find that out by making a statement syntactically incorrect. For example: if you type anything’ into the password field, that will turn out on the following SQL:

SELECT sqlinjection.id FROM sqlinjection WHERE BINARY sqlinjection.user = ‘X’ AND sqlinjection.password = ‘anything’

That SQL is syntactically incorrect (because of the double ) and, as a result, an error will be thrown. If that error is not appropriately catch, then it will be showed on the screen. That is more than enough to find the tables (and the databases) names.

The video below shows a SQL Injection attack been made:

So, how to protect your applications from SQL Injection attacks?

That’s the most simple part. You can deny all kind of strings with contains , and ;. Also, you can limit the size of the data been received. The most important thing is: make sure that all of those verifications are made on the server-side (otherwise the attacker could pass through it easily by editing your page’s source code or even by making a HTTP request from scratch).

That’s it! If you have any question, feel free to ask.

PS: If you detected some mistake in any part of my post or in my English, please, send me an email or a comment correcting me! I’m Brazilian, so I’m not an English native speaker. I would really appreciate being corrected! Thank you in advance! :)

Great Definitions – Script

junho 24, 2009 Deixe um comentário

Acho que toda pessoa que mexe bastante com a Internet, seja ela programadora ou não, já ouviu falar da palavra “Script”.

Porém, essa é uma daquelas palavras que um programador/webdesigner entende por natureza, mas que, quando vai explicar para uma outra pessoa, não consegue.

Passando pelo site da W3Schools (www.w3schools.com), encontrei esta definição para JavaScript que achei fenomenal. Acompanhe:

  • JavaScript is a scripting language
  • A scripting language is a lightweight programming language

Com isso, podemos definir “Script” como sendo “uma parte de um código escrito em uma linguagem de scripting”, onde uma “linguagem de scripting” é uma linguagem de programação mais leve (com menos recursos do que uma linguagem normal) e geralmente interpretada ao invés de compilada.

Simples, direta e elegante, como uma boa definição deve ser!

Cuidado com o operador “%” !!!

maio 20, 2009 Deixe um comentário

Todo programador, em algum momento, teve que verificar se um determinado número inteiro ‘n’ era par ou ímpar.

Podemos fazer isso facilmente através das seguintes funções (abaixo uma versão escrita em C++):

eImpar

Ótimo. Vamos testar agora as duas funções para os seguintes valores: 0, 1, 2, -2 e -1.

ePar(0) = true eImpar(0) = false
ePar(1) = false eImpar(1) = true
ePar(2) = true eImpar(2) = false
ePar(-2) = true eImpar(-2) = false
ePar(-1) = false eImpar(-1) = false !!!!!!!

A explicação é que o operador % retorna o mesmo sinal do primeiro operando. Assim:

-1 % 2 == -1 != 1

Fica a lição: da próxima vez que precisar verificar a paridade de um número, use somente a função “ePar()”. 100% garantido! 😛


PS 1: Testei essa dica nas linguagens C, C++ e Java. Em todas, o operador % se comporta como a tabela acima. Acredito que isso seja verdade para praticamente todas as linguagens, apesar de não ter confirmado.

PS 2: Essa dica foi retirada da excelente apresentação “10 coisas que eu odeio em Java”, do professor Rafael Santos. Vale a pena fazer uma visita ao seu site: http://www.lac.inpe.br/~rafael.santos/ Tem muito material interessante lá.

Categorias:Programação