Never, ever, swallow your stack trace.

I came across this kind of exception handling code.

import java.util.Observable;
import java.util.Observer;

public class Framework extends Observable {

  public void SendMessage(String msg) {
    setChanged();
    try {
      notifyObservers(msg);
    } catch (RuntimeException re) {
      throw new RuntimeException("Something bad happend.");
    }
  }

  public static void main(String[] args) {
    Framework f = new Framework();
    f.addObserver(new Observer() {
      @Override
      public void update(Observable o, Object arg) {
        System.out.println("I am fine: " + arg.toString());
      }
    });
    f.SendMessage("hello world");
  }
}

This is pretty common pattern. Right? You create a list of several instances and iterate over them to do something. Actually, that’s the beautiful pattern commonly used.

But, the code actually has a pitfall. Look at the error handling part. Can you identify it?

try {
  notifyObservers(msg);
} catch(RuntimeException re) {
  throw new RuntimeException("Something bad happend.");
}

At first glance, this looks fine. It’s trying to tell something to the user. It’s not even swallowing the exception. But that’s not all for the framework developer. What happens if I add an innocent observer but got some error?

  public static void main(String[] args) {
    Framework f = new Framework();
    f.addObserver(new Observer() {
      @Override
      public void update(Observable o, Object arg) {
        System.out.println("I am fine: " + arg.toString());
      }
    });
    f.addObserver(new Observer() {
      @Override
      public void update(Observable o, Object arg) {
        throw new RuntimeException("I got an error: " + arg.toString());
      }
    });
    f.SendMessage("hello world");
  }

Now the code spits out this:

Exception in thread “main” java.lang.RuntimeException: Something bad happend.
at Framework.SendMessage(Framework.java:11)
at Framework.main(Framework.java:29)

Seriously, that’s all I get. If this happens, I’m left with no clue but something went wrong.

Please do not swallow not just your exception but also your stack trace. How can I believe that all other observers are fine but it’s just my fault without any proof?

Keep the stack trace:

try {
    notifyObservers(msg);
} catch (RuntimeException re) {
    throw new RuntimeException("Something bad happend.", re);
}

Now I get this awesome trace:

Exception in thread “main” java.lang.RuntimeException: Something bad happend.
at Framework.SendMessage(Framework.java:11)
at Framework.main(Framework.java:29)
Caused by: java.lang.RuntimeException: I got an error: hello world
at Framework$2.update(Framework.java:26)
at java.util.Observable.notifyObservers(Unknown Source)
at Framework.SendMessage(Framework.java:9)
… 1 more

Simlar Posts:

Broken javascript word counting code that irritates me

Based on the Javascript: The Good Parts by Douglas Crockford.
(I highly recommend this book to everyone.)

<script type='text/javascript'>
var s = "Constructor is a Constructor";
var word_cnt = {};
var words = s.toLowerCase().split(/ /);
var i;
for (i = 0; i < words.length; i++) {
  if (word_cnt[words[i]]) {
    word_cnt[words[i]] += 1;
  } else {
    word_cnt[words[i]] = 1;
  }
}

for (w in word_cnt) {
  document.write(w + ": " + word_cnt[w] + "<br>");
}
</script>

Output:
constructor: function Object() { [native code] }11
is: 1
a: 1

Reason:
Because you have ‘Constructor’ in your parent class (or prototype) of word_cnt!!!!!!
And that’s a string! So you add 1 to that string! and 1 is coerced to a string, thus the result is a string!
Sigh… Given that javascript is now really the future, this makes me want to cry.

Simlar Posts:

Bind function for binding parameters in javascript

I’ve written a bind function that binds the given parameters to the designated function as a practice.

<script type='text/javascript'>
// 'method' is taken from Douglas Crockford's Javascript: The Good Parts, Oreilly.
// This is a good to have shorthand for adding a method to Object.
Object.prototype.method = function(method_name, func) {
  Object.prototype[method_name] = func;
}

Object.method('bind', function() {
  // Here, 'this' is the context where 'bind' is called. So, it is 'add' in the examples below.
  var target_func = this;
  // Parameters passed to bind.
  // 'arguments' is not Array thought it's arraylike object, so we convert it to Array.
  var partial_args = Array.prototype.slice.call(arguments);
  // A function that will accept the remained parameters.
  return function(remained_params) {
    // Call target function with partial and the remained parameters combined.
    return target_func.apply(null,
        partial_args.concat(Array.prototype.slice.call(arguments)));
  }
});

var add = function(a, b) {
  return a + b;
}

var addToOne = add.bind(1);
document.write('addToOne: ' + addToOne(2) + '<br>');  // 3

var add3 = function(a, b, c) {
  return a + b + c;
}
var addToOne3 = add3.bind(3);
document.write('addToOne3: ' + addToOne3(4, 5) + '<br>');  // 12

var addToOneTwo3 = add3.bind(6, 7);
document.write('addToOneTwo3: ' + addToOneTwo3(8) + '<br>');  // 21
</script>
Simlar Posts:

How to Design a Good API & Why it Matters

http://www.infoq.com/presentations/effective-api-design

Presentation by Joshua Bloch. I reached this presentation while reading coders at work. Joshua discusses design process and the details like prefer to immutability, fail early, how/when to inherit and so on.

Simlar Posts:

Inheritance and objects in javascript

Based on Javascript: the good parts by Douglas Crockford from Oreilly and his presentation.

I felt it’s hard to fully understand his point on prototypal inheritance, so I tried to explain it in my way with code.

// * Classical way of object creation
//
// Constructor:
var Quo = function() {
}

// Method:
Quo.prototype.breathe = function() {
  return "Quo";
}

// Don't forget new. That's a terrible disaster and won't raise any error.
q = new Quo();
alert(q.breathe());  // Quo

// Question is.. do we need that prototype hassele?
Quo.bark = function() {
  return "Bark";
}

// Yes. Without prototype, this is an error:
// alert(q.bark());
//
// The thing is, bark is Quo's function and not that of q. Why? Because
// when 'new' is called, a new instance is created and it derives from
// the prototype of Quo. (It doesn't derive Quo directly.)

// As I said, Quo has bark.
alert(Quo.bark());  // Bark

// Inheritance via prototype
var QuoChild = function() {
}
QuoChild.prototype = new Quo();
var quoChild = new QuoChild();
alert(quoChild.breathe());  // Quo
alert(quoChild.bark());  // Bark

// prototype must be an instance. This is an error:
// QuoChild.prototype = Quo;

// * Prototypal way
//
// Object.create will be added in the next version of javascript,
// but we can create one now.
if (typeof Object.create != 'function') {
  Object.create = function(o) {
    function F() { }
    F.prototype = o;
    return new F();
  }
}

// This is an object literal. It's not a class. It's an instance itself.
var Mammal = {
  name: 'Mammal',
  breathe: function() {
    return "I'm breathing";
  }
};

var cat = Object.create(Mammal);
// This is a property of the cat instance.
cat.breathe = function() {
  return "I'm meow";
}

// cat is an instance who does not have prototype of it. So, this is an error:
// cat.prototype.breathe = function() {
//   return "I'm barking."
// }
//
// As an example, this is an error, too:
//
// var o = new Object();
// o.prototype.breathe = function() {
//   return "ooo";
// }
//
// So, it's simple that cat should have a function as the property of itself,
// if it wants to.

alert(cat.breathe());  // I'm meow

var dog = Object.create(Mammal);
alert(dog.breathe());  // I'm breathing.

// Prototyping from smallCat is okay. An object created by new F()'s prototype
// is cat.
var smallCat = Object.create(cat);
alert(smallCat.breathe());

// It is not still obvious why Prototypal way is worth trying. It's because
// of private members.
var parent = function() {
  var F = function () { }
  function F() { }
  function private_func() {
    return "private";
  }
  F.prototype.public_func = function() {
    return private_func() + " called by public";
  }
  return new F();
}();

alert(parent.public_func());  // private called by public
// This is a private function. So, error:
// alert(parent.private_func());  // private

var child = Object.create(parent);
alert(child.public_func());   // private called by public

// There's no way to add a function to call private_func like this:
// child.child_public_func = function() {
//   // No.. private_func is not here.
//   return private_func();
// }

So, here’s the status of inheritance in javascript that I feel:
1) It’s bad that there’s no warning when there’s no new.
2) Writing ‘prototype’ keyword again and again in classical way is terrible.
3) Prototypal way is pretty neat, but
4) Grammar becomes terribly complex when I try to add a private member. If a language is going to be that much complex, not everyone will use it, and the feature will be forgotten.

Simlar Posts:

sslstrip

MITM(Man in the middle)을 사용하여 SSL을 중간에 엿들을 경우, 아이디와 패스워드 같은 중요한 정보가 attacker에게 알려지게 됩니다. 단 이때 문제는 ‘보안 certificate이 이상하다’라는 경고가 victim에게 띄워지게 된다는 점입니다. 대부분의 경우 사용자는 별 생각없이 무시하기를 누르던가 ok를 누르던가 하기 때문에 공격 자체는 문제가 없게되죠.

하지만 깔끔한 방법(해킹기법을 이렇게 불러도 되는건지;;)이 한가지 있는데,

victim <---http---> MITM <---- https ----> target

이렇게 통신채널을 구성하는 것입니다. SSL을 없애기때문에 sslstrip입니다.

그러면 victim은 https가 아니므로 보안경고를 보지 않고, MITM과 target은 https로 통신하는거죠. 이걸 위해서는 target에서 victim쪽으로 ‘https://….’ 을 form등에 url로 넣어서 보낼경우 MITM은 이걸 캐치해서 ‘http://…’ 로 고쳐주기만 하면 됩니다.

Simlar Posts:

Return oriented programming

Return oriented programming 들어보셨나요? 아마 최근 아이폰 SMS DB 해킹기법이 Return oriented programming의 잘된 예라고 했던 듯 합니다. (기사가 기억이 잘..)

일단 이것인가 아시는 분들을 읽을 필요없는 글이고, 이것이 무엇인지 전혀 모르는 분을 위한 초간단 개요를 하나 적을까 합니다.

일단 Return oriented programming을 알려면 return to libc를 아는 것이 필요합니다. return to libc란 해킹 테크닉중의 하나로 library로 리턴하는 방법을 말하며, 상세한 내용은 pharack, smashing the stack for fun and profit이란 글에 자세히 나와 있습니다. 하지만 여기서는 간단하게만 알아보겠습니다.

다음과 같은 잘못된 코드가 있다고 해보죠.

int main(int argc, char** argv) {
  char buf[255];
  strcpy(buf, argv[1]);
}

이 코드가 잘못된 이유는 사용자의 입력을 지나치게 신뢰한나머지 buffer overflow가 가능하다는 점입니다. 그냥 buffer overflow만 되면 모르겠는데, 만약 이 코드를 root사용자의 권한으로 실행할 수 있도록 setuid 가 되어있다고 하면, 공격자 X는 다음과 같이 이 코드를 공격할 수 있습니다.

1. 일단 “/bin/sh”를 실행하는 C코드를 하나 짭니다. (system 함수 호출)
2. 걔를 disassemble합니다. 그럼 16진수 코드가 나오죠.
3. 위 프로그램의 인자로 약간의 패딩(최소한 오버플로우시키고 싶으니까 255글자 이상이겠죠)과 함께 아까 disassemble한 16진수 코드를 넣습니다.
4. 그러면 위 프로그램은 root의 권한으로 돌다가 /bin/sh를 실행.
5. 결국 공격자는 쉘을 따내게 됩니다.

이게 가능한 이유는 buf라는 데이터가 저장되는 주소에서 계속 오버플로우해서 가다 보면 main이라는 함수가 종료되는 스택 반환 주소가 나오기 때문입니다. 다시 말해, 공격자는 이렇게 메모리 레이아웃을 고칩니다.

buf[255] | /bin/sh/ | system 주소

그러면 프로그램은 종료하려고 하다가 system 주소로 RET하는데, 이 때 인자로 /bin/sh를 넘기게 됩니다. (아시다시피 function call의 인자는 스택을 통해 넘깁니다.) 결국 root권한으로 쉘을 내주게 되는 것이죠.

그러나 이것이 최근에는 다양한 방법으로 막히게 되는데, 그 중 하나는 변수의 전달을 어렵게 하는 보호 방법입니다. 앞서 보시면 system에 제가 ‘/bin/sh’를 넘겨야하는데, 이처럼 넘겨주는 변수가 메모리에 써있으면 안되고 레지스터에 들어있어야 하도록 강제하는 것입니다.

두번째는 데이터 영역과 코드 영역을 명확히 구분해버리는 것입니다. 기존에는 메모리를 overflow하면서 쓰고(write), 그 영역이 동시에 실행(execute)될 수 있었습니다만, 이제는 쓸수도 있으면서 실행도 가능한 메모리를 없애버린것입니다.

세번째는 코드 사이닝으로, 못믿을 놈이 넣은 코드는 실행안한다는 것입니다.

그외에도 여러가지 방어 기법이 있습니다. 예를들어 스택의 반환 주소를 랜덤화한다던가, 내가 호출할 system이란 펑션을 아예 라이브러리에서 지워버린다던가, 아니면 system이란 함수의 라이브러리내 위치 주소를 랜덤화한다던가, 스택을 overwrite하게 되면 곧바로 프로그램이 죽어버리게 막아놓는다던가.

Return oriented programming은 공격자가 인자와 함수를 정해서 호출하는 것이 아니라, 그냥 시스템에 존재하는, 이미 코드 사이닝이 된 코드를 호출해버리겠다는 것입니다. 예를들어 가상의 시스템내 라이브러리가 이렇게 이미 생겨있다고 해보겠습니다.

funcA()
….
copy ‘/bin/sh’ to argument. // (1)
RET

funcB()
copy ‘ls’ to argument.
system 호출 // (2)
RET

그럼 공격자는 funcA()와 funcB()를 조합합니다. 그래서 앞에서처럼 직접적으로 system을 호출하지 않고 코드를 1로 점프시킵니다. 그게 반환되어 오겠죠? 이미 copy다음엔 RET가 있으니까. 그러면 곧바로 2를 호출합니다. 이렇게 되면 결국 쉘을 따냅니다.

물론 시스템 라이브러리에서 이렇게 필요한 코드를 찾는다는 것은 고역이 아닐 수 없겠죠. 그래서 연구자들은 아예 라이브러리에서 유용한 code fragment를 뽑아내서 또다시 2차 라이브러리화하고 있습니다.

Simlar Posts:

Short tutorial to SQL in HTML5

HTML 5 Web SQL Database

How to connect, select and insert.

Simlar Posts:

NerdTree vim plugin

http://www.catonmat.net/blog/vim-plugins-nerdtree-vim/

I usually use Project plugin for file navigation for my projects, but this NerdTree plugin looks also quite useful. Sometimes, it’s onerous to keep file list in project plugin.

Simlar Posts:

UC Irvine Machine Learning Repository

http://archive.ics.uci.edu/ml/

We currently maintain 187 data sets as a service to the machine learning community. You may view all data sets through our searchable interface. Our old web site is still available, for those who prefer the old format. For a general overview of the Repository, please visit our About page. For information about citing data sets in publications, please read our citation policy. If you wish to donate a data set, please consult our donation policy. For any other questions, feel free to contact the Repository librarians. We have also set up a mirror site for the Repository.

Simlar Posts: