Mais um blog inútil.

Coding

Abril 13, 2009

A minha arvorezeca em tcl ;]

Arquivado em: arvorezinha, coding — madinfo @ 18:54

by Juvenal

 #!/usr/bin/env tclsh
 set chars 40
 set bottom 4
 set bott 4
 set s " "
 set f *
 proc repeat {a b} {return [string repeat $a $b]}
 for {set a 1;set b [expr ($chars / 2)*2];set x $bott;set y [expr ($chars - $bottom)+1]} {$a < = $chars||$x>1} {incr a 1;incr b -1} {
  if {$a< =$chars} {set z [repeat $f $a];puts [repeat $s $b]$z$z} {
   set z [repeat $f $bottom];puts [repeat $s $y]$z$z;incr x -1
  }
 }

Arvorezinha em Ook!

Arquivado em: arvorezinha, coding, fail — madinfo @ 18:28

Aqui fica:

Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook.
Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook.
Ook! Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook?
Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook! Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook?
Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook! Ook? Ook!
Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook. Ook? Ook.
Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook! Ook.

Compilador disponivel aqui: http://search.cpan.org/~jhi/Acme-Ook-0.11/lib/Acme/Ook.pm

Já de si é fail pq é perl…

Chama-se a isto a linguagem dos orangotangos…

orangotango

Olá FALSO

Abril 8, 2009

A Intel e os manuais

Arquivado em: coding, serious-business — dcoder @ 23:24

Viva meus amigos. Eu já tinha ouvido falar das muitas incorrecções dos manuais publicados pela Intel, particularmente em relação à contagem de ciclos das instruções (contagem de ciclos não faz sentido hoje em dia, claro que me refiro à latência/throughput), mas sempre imaginei que fosse apenas má língua. Aparentemente não.

O manual que descreve todas as instruções da ISA x86/x86_64, acessível aqui, contém as instruções CBW/CWDE/CDQE, representadas pelo byte 0x98 (mais prefixos). Estas instruções servem para estender o sinal de um registo de 8/16/32 bits para 16/32/64 bits.

No entanto, a Intel parece ignorar o opcode CWD/CDQ, representado pelo byte 0x99. Este efectua a mesma extensão de sinal, mas fá-lo de AX para DX ou de EAX para EDX. É comummente utilizado por compiladores ao preparar uma divisão com sinal (sem sinal é mais vantajoso simplesmente usar XOR (E)DX, (E)DX).

Alguém me explica esta ausência?

Arvorezinha em HASKELL

Arquivado em: arvorezinha, coding, useless — madinfo @ 11:43

Pois bem, depois de seguir atentamente os posts do falso com coisas completamente inúteis… Resolvi fazer a arvore em HASKELL.

Sem mais demoras aqui fica:

-- THIS HASKELL CODE CAN NEVER FAIL

module Main where

main = do putStr (unlines (take 5 (iterate('*':) "*")))
              putStrLn "2nd version:"
              putStr . unlines . take 5 . iterate ('*' :) $ "*" -- 2nd version

Como podem ver até é bem simples…

Podem instalar o compilador com:

sudo apt-get install ghc6sudo apt-get install haskell-mode

Compilar com:

ghc –make -O2 arvore.hs -o arvorehs

Ou mesmo utilizar o prelude que é bem fixe:

ghci

Versão optimizada por Ashes:

arvore n =  (take n (cycle ['*']))
arvorezinha n = putStr (unlines (map arvore [0..n]) )

Fevereiro 15, 2009

ALL GLORY TO THE HYPNOTOAD

Arquivado em: coding, useless — falso @ 02:19

Depois do grande sucesso do script de hypnotoad, decidi criar um projecto no google code pros scripts todos que vão aparecendo. Esta parece me uma razão bastante inutil pra blogar portanto aqui está!

http://code.google.com/p/hypnotoad/

EDIT: devido ao facto de estar deveras aborrecido, fui fazer um script para xchat no xchat-aqua para osx e já lá está tambem a versão oficial para xchat.

Setembro 21, 2008

Expressoes do Lulz

Arquivado em: coding, lulz, serious-business, useless — falso @ 04:45

Hoje finalmente tive pachorra, e comecei a fazer um site que já andava a falar há bue de tempo, um site com expressões típicas portuguesas. Utilizei uma framework open sores chamada codeigniter para fazer isto e ate agora parece me ser bacano. Não esperem nada de especial ainda, mas futuramente vai ser o site mais visitado do mundo ate ser comprado pelo google!

http://expressoes.blol.org/

Agosto 28, 2008

lulz do c

Arquivado em: coding, drama, openbsd — falso @ 23:56

Como já não blogo há muito tempo decidi vir falar sobre algo completamente inutil. Estava eu a tentar compilar o ircd da ptlink no OpenBSD com o pcc em vez do gcc, quando me deparo com um erro meio estranho…

pcc -I../include -g -O2 -DNDEBUG -c help.c
pcc -I../include -g -O2 -DNDEBUG -c hvc.c
hvc.c, line 100: return value required
*** Error code 1

Achei estranho este tipo de erro, ate porque isto é compilavel em outras circunstancias.

int m_hvc(aClient *cptr, aClient *sptr, int parc, char *parv[])
{
  if(!IsPrivileged(sptr))
    return; /* Linha 100 */
  if(parc < 2)
  {
    if(MyClient(sptr))

Nunca tinha visto “return;” em nenhum codigo na vida, e fiquei a pensar como é que o gcc papa isto sem espinhas. Pus return 0; porque me pareceu bem e o resto do programa compilou bem, mas depois deu problemas a linkar portanto cagay naquilo. Fiz uma experiencia:

{:/home/bud/gcc:48} cat main.c
#include <stdio.h>

int sida() {
        return;
}

int main() {
        printf("%x--\n",sida());

        return 0;
}
{:/home/bud/gcc:49} gcc -o sida main.c
{:/home/bud/gcc:50} ./sida
3bbc634d--
{:/home/bud/gcc:51} ./sida
5357df90--
{:/home/bud/gcc:52} ./sida
b3e1e9d9--

Belo random number generator :-P Com -Wall o gcc ja diz qualquer coisinha

main.c: In function `sida':
main.c:4: warning: `return' with no value, in function returning non-void

Acho que supostamente isto nao devia funcionar? O dcoder teve me a dar umas dicas e disse que o msvc tambem comia os return;. Bastante inútil este post, hein?

GPcode, again

Arquivado em: coding, serious-business — dcoder @ 05:27

Aparentemente alguém foi mais inteligente que os cromos da Kaspersky:

http://rump2008.cr.yp.to/6b53f0dad2c752ac2fd7cb80e8714a90.pdf

O ataque não é surpreendente. Uma vez que é utilizado RC4 para cifrar os ficheiros (eles usam a CryptoAPI), é utilizado o mesmo tipo de ataque que no famoso WEP. Basta ter ficheiros suficientes para conseguir obter correlações.

O que me leva a perguntar: porque raio ainda tanta gente usa RC4? Existem tantas outras stream ciphers seguras e que têm mecanismos próprios para definir chaves e IVs (e.g. Salsa20, Sosemanuk, Trivium, etc). Caso o autor usasse uma destas cifras sem tremendos problemas (é ridículo descartar os primeiros 1024 bytes da stream de RC4 porque libertam informação sobre a chave) com um IV para cada ficheiro, seria efectivamente impossível recuperar os dados.

Agosto 14, 2008

Import Library for RtlGenRandom

Arquivado em: coding, drama, serious-business, useless, windows — dcoder @ 15:19

Everyone needs cryptographically strong pseudo random numbers in this day and age. From card games to your Paypal HTTPS session, it has become an essential part of secure systems. Now, as a user it’s hard to generate randomness; we all know how many systems are seeded with time(NULL) or the like. That’s why most operating systems have mechanisms to provide randomness to the user. In Unix systems, this is usually done through /dev/?random; on Windows, through the function CryptGenRandom.

However, CryptGenRandom requires a handle to a CSP (acquired by calling CryptAcquireContext). If all we want is random bytes, this no good; a full-fledged CSP takes too many resources (and time to load) for the task at hand. So an alternative is to use the lower level function RtlGenRandom, which doesn’t require a CSP context. This name is an actual alias for the function ‘SystemFunction036’ in advapi32.dll. MSDN reports: “This function has no associated import library. This function is available as a resource named SystemFunction036 in Advapi32.dll. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Advapi32.dll”. But what if we don’t want the pain of loading and unloading libraries at runtime? I’ll show you how to make the required import library to avoid this.

The main problem you will encounter  is that RtlGenRandom’s calling convention is __stdcall, whereas its actual name in advapi32.dll does not reflect that (__stdcall functions have the number of bytes passed as parameters in the stack appended in the function name. In this case, it expects SystemFunction036 to be called SystemFunction036@8). Using the LIB utility doesn’t help, even when using aliases: it always expects the appended number of bytes to be there. So first idea is to use function ordinals. Running DUMPBIN /EXPORTS on advapi32.dll shows us:

621  26C 00008292 SystemFunction036 = _SystemFunction036@8

So now we know the ordinal of our function: 621. With this in mind, we can now use LIB to create a .lib to link against our application. First, create a .def file with the following lines:

LIBRARY advapi32.dll
EXPORTS
SystemFunction036@8 @ 621

Now run:

lib /DEF:RtlGenRandom.def /OUT:RtlGenRandom.lib /MACHINE:X86

Now you can just link the resulting .lib with your application to have the desired result.

However, this is not a good solution. Ordinals are by no means fixed (unless you’re dealing with Winsock2 or MFC dynamic libraries) and you have no guarantee they’ll be the same across Windows versions. So here’s another way to do it. First, create a C source file and declare an empty function equal to RtlGenRandom:

#include <windows.h>
#define RtlGenRandom SystemFunction036
#define DLLEXPORT 	__declspec(dllexport)
DLLEXPORT BOOLEAN WINAPI RtlGenRandom(PVOID in, ULONG len) {}

Now create a .def like the following:

LIBRARY advapi32.dll
EXPORTS
SystemFunction036

Now we compile the source and feed the DEF to the linker:

cl dummy.c dummy.def

The actual binary output of this compilation is irrelevant; what we want is the resulting dummy.lib. You can now link against this import library and it will link to the real advapi32.dll, thus giving us what we want. I used the following test source to try it out:

#include <stdio.h>
#include <windows.h>

#define RtlGenRandom                    SystemFunction036
BOOLEAN WINAPI RtlGenRandom(PVOID, ULONG);

int main(int argc, char **argv)
{
    BYTE blah[20];
    DWORD i;

    RtlGenRandom(blah, 20);

    for(i=0; i < 20; i++)
        printf("%02X ", blah[i]);

    return 0;
}

Compile with:

cl /O2 /MT test.c dummy.lib

Problem solved. Try it out.

PS: Someone’s bound to comment “oh but Windows’ PRNG is flawed, there was a paper on it some time ago”. That’s correct. However, both attacks (forward and backward security compromised) assume you already have knowledge of the whole state of the PRNG (i.e. you’ve owned the box) and that you’re running a Windows previous to XP SP3, which fixed the issue.

Julho 13, 2008

Windows e CryptGenKey

Arquivado em: assembly, coding, serious-business — dcoder @ 23:31

Suponho que quem ler isto conheça, ou pelo menos tenho noção, de como funciona o RSA. Com a API do Windows é-nos permitido gerar novas chaves, mas o expoente público (também conhecido por e) é sempre 65537 (0x10001). E se quisermos usar outro que não este?

Para minha surpresa, é impossível. Com o Enhanced Provider da Microsoft (rsaenh.dll), verifiquei que o valor 65537 está mesmo hardcoded no código; para gerar chaves com outro expoente temos de alterar o dll. Ao analisar o binário, rapidamente chegamos à função 6800FBD9 - é nesta que a geração é efectuada. Primeira paragem:

.text:6800FC34                 push    eax             ; int
.text:6800FC35                 mov     byte ptr [ebp+var_4], 1
.text:6800FC39                 mov     byte ptr [ebp+var_4+1], bl
.text:6800FC3C                 mov     byte ptr [ebp+var_4+2], 1
.text:6800FC40                 mov     byte ptr [ebp+var_4+3], bl ; var_4 = 0x00010001 == 65537
.text:6800FC43                 mov     [ebp+var_C], 3  ; length(var_4) = 3 bytes

Vemos aqui o valor e o seu tamanho a serem colocados numa variável. Portanto será aqui o primeiro lugar a alterar para o valor pretendido (e.g. 3 ou 17). Mas não fica por aqui.

.text:6800FC7D                 push    eax
.text:6800FC7E                 push    [ebp+var_C]     ; sizeof(10001)
.text:6800FC81                 lea     eax, [ebp+var_4]
.text:6800FC84                 push    eax             ; Ptr to 0x10001
.text:6800FC85                 push    esi             ; Keysize (bits)
.text:6800FC86                 call    sub_68027FDD    ; Generate public/private keypair

Vemos aqui o expoente público a ser passado à função que gera os a chave pública e privada. Adiante:

.text:6800FD8A                 push    [ebp+var_10]    ; Prime #1
.text:6800FD8D                 push    [ebp+var_8]     ; Prime #2
.text:6800FD90                 push    10001h          ; push 65537 -- public exponent
.text:6800FD95                 push    [ebp+arg_14]    ; Keysize in bits
.text:6800FD98                 push    eax             ; PRIVATEKEYBLOB (out)
.text:6800FD99                 push    dword ptr [edi] ; PUBLICKEYBLOB (in)
.text:6800FD9B                 call    sub_6801F9C0    ; Creates the PUBLICKEYBLOB/PRIVATEKEYBLOB structure

Vemos novamente ali o valor hardcoded a ser usado. Temos de mudar o valor colocado na stack para o desejado. No final desta função, teremos uma chave gerada com o expoente que queremos. Para mais info sobre as estruturas de saída desta função, vejam isto.