Thanks to visit codestin.com
Credit goes to corecode.wordpress.com

Feeds:
Posts
Comments

Archive for the ‘dicas’ Category

In Git the CVE-2024-32002 is regarding a RCE (remote code execution) vulnerability that can be exploited through repositories with sub-modules. I won’t go deep in the CVE itself, as there are good sources around in how to exploit it and how it works, such like this [1].
The idea here is to step-by-step show how you could set an EXT4 file system with case-insensitive enabled.
First of all, it is important to mentioned that this feature was introduced in Linux 5.2 [2]. Hence you need to check if you system supports it. For this, just type:

$ cat /sys/fs/ext4/features/casefold

It should show: supported.
Now if your system supports it, let’s create a file system EXT4 with that feature enabled. But instead to format a whole partition to have it. Let’s use a block device using Loop device. Follow these steps:

# Create a file to be your block device

$ dd if=/dev/zero of=filename bs=1024 count=51200

# After that the filename was created with blocks of 1024 size in total of ~51M.

# Now, check which loop device is available:

$ losetup -f
# output example: /dev/loop1

#Create the the block device with the available loop device

$ losetup /dev/loop1 filename
# where filename is the block file you created using dd

Now that you have a loop device the next step is to create the file system with casefold enabled and mount it in some point.

$ mkfs -t ext4 -O casefold /dev/loop1

# create the  poc directory where you'll mount it in /mnt/poc
# remember to set the permissions to you
# chown -R your_user:your_user_group poc
# e.g: chown -R corecode:corecode poc

$ mount -t ext4 /dev/loop1 /mnt/poc

# check if was mounted
$ df -h /dev/loop1

# check that device/fs supports case insensitive looking for 
# Filesystem features:     ... filetype needs_recovery extent 64bit flex_bg casefold <--
$ sudo tune2fs -l /dev/loop1

# Now you have a folder set with that file system mounted. To enable case insensitive in a folder you need to:

$ chattr +F directory 

# If you want to check which a given directory is case-insensitive supported:

$ lsattr .
# output: ----------------F--- directory

In order to reproduce the Git CVE-2024-32002 PoC you can grab the script in here and give it a try. Pro-tip: change the execute program session to something Linux understand: e.g: cal or gnome-calculator or whatever you want.

References:
[1]https://amalmurali.me/posts/git-rce/
[2]https://www.collabora.com/news-and-blog/blog/2020/08/27/using-the-linux-kernel-case-insensitive-feature-in-ext4/

Read Full Post »

I hate docker! Yes, I hate a bit. Why? Just because I tried a lot to do a simple application that uses a mysql everything internal into a docker and I failed, terrible! I did researches a lot about how to set it and also failed terrible. Every piece of tutorial I found was about using a docker image container and linking it to another container running the application or even some bullshit about docker mysql image and web applications. NO! That wasn’t what I looking for at all. After did more research I found docker-compose, but yet nothing about put my application in a single image/docker together with mysql. I don’t care how it’s for some people that like things separated, but I also think in docker to do things that are easy to delivery and that was why I tried that. But let’s forget the rage and focus in the tutorial itself that I hope will help some people that are/were looking for the same as me.

Step 1: Install docker and docker-compose.

I choose for docker-ce and you can follow the steps to download/install here. For docker-compose I just did a sudo apt-get install docker-compose (I’m using ubuntu 16.04 LTS).

Step 2: You probably will see some error while trying to run docker. So, before you see that add you $USER to the docker group. Do this:

  1. sudo usermod -aG docker $USER 
  2. newgrp docker

Now you can use docker without issues.

Step 3: Write your docker-compose.yaml file: In my case I wanted to use mysql and everything into the same docker container image. When I say everything I mean my mysql databases, my mysqlserver with my databases, my application itself running internally to the container accessing the database and so on…

database:
  image: mysql
  container_name: application.v1
  volumes:
    - ./somefolder/some_script_to_install_your_app.sh:/tmp/install_your_app.sh
    - ./data_volume:/opt/data_volume/
  ports:
    - "3306:3306"
  environment:
   MYSQL_DATABASE: "your_data_base_name"
   MYSQL_USER: "some_user"
   MYSQL_PASSWORD: "some_user's_password"
   MYSQL_ROOT_PASSWORD: "root_passwd"

Using the docker-compose.yaml above you’ll be able to create a mysql image/container. Cool! But what about my application? The way I did it can be a little hack or not right but in few words, who cares! In essence a mysql image is a debian imagem with mysql set in it. So you can just install things into it and put your application to into that container/image as you want. In order to do that I just add some scripts in volume to install my application and internally the application access mysql through localhost host, simple! YEAH! The only thing is that you need to run first a docker-compose up (in the same directory were you .yaml file is)   to put your mysql server to run and in separated run your application as: docker exec application.v1 application (supposing your install it in /bin). If you don’t like or don’t want do type docker exec … you can just create a shell/bash wrap around the command that 1) starts the mysql server and 2) runs your application \o/. And finally you have an application running beautifully with a internal docker container mysql.  For the inconvenience of run a docker-compose up and so your application you can just hack this and run a: docker-compose stop && docker-compose up &> /dev && docker exec application.v1. It’s not pretty as you wish probably, but it works as a charm.
I hope that I have help you somehow because the internet is fully of garbage that don’t explain nothing right of with all details. I’m sure I not put all details here, but I’ willing to help in the comments session or even when I edit this post. For now, just try as an exercise put a script into your docker-compose.yaml that e.g:  install git and git clone your app and compile it and install into /bin. See if it runs, if it access mysql internally and that is all!

Read Full Post »

Sometimes is quite interesting to measure the run time of a given snippet your code. In C++11 is very simple and in my case I’m using just like that.

In my .h file I define

#ifndef __PROFILER__H
#define __PROFILER__H

#include <chrono>

using namespace std::chrono;

high_resolution_clock::time_point start(void);
high_resolution_clock::time_point end(void);
void finished(high_resolution_clock::time_point, high_resolution_clock::time_point);

#endif

And in my .cpp file

#include <iostream>
#include "profiler.h"


high_resolution_clock::time_point start(void) 
{
    return high_resolution_clock::now();
}

high_resolution_clock::time_point end(void)
{
    return high_resolution_clock::now();
}

void finished(high_resolution_clock::time_point start, high_resolution_clock::time_point end)
{
    duration<double> elapse = end - start;
    std::cout << "Elapsed time for function " << __FUNCTION__ << " :"<< elapse.count() << "s" << std::endl;
}

In order to use the code you just need to add the code ‘surrounded’ by start and finished functions, passing end as parameter. Like that:

#include <iostream>

// It's not often that you'll profiling your code so just add a D flag
// See Makefile
#if PROFILER 
#include "profiler.h"
#endif

// Some function to measure
void initLoad(void) {
    cout << "Initializing data in memory..." << endl;

#if PROFILER
    high_resolution_clock::time_point s = start();
#endif

    for (int i = 0; i < 100000000000; i++)
        cout << i << endl;

#if PROFILER
    finished(s, end());
#endif
}

In your Makefile you can use a D flag to optionally compile your code to use the profiling, such as:

SRC = $(wildcard src/*.cpp)
PROG_NAME = test
INCLUDE = -Iinclude 
LIBS = -Ilibs
FLAGS = -std=c++0x
DFLAGS = -q -nx -tui
PROFILER ?= 0

# To use profiler just add: make PROFILER=1
ifeq ($(PROFILER), 1)
	FLAGS += -DPROFILER
endif

test:
	g++ -o $(PROG_NAME) $(SRC) $(INCLUDE) $(LIBS) $(FLAGS)

Now you can use this ‘lib’ for any source you want to measure the run time typing: make PROFILER=1 🙂

That’s all folks!

Read Full Post »

Screen tip

How about to use bash configuration in your screen session?
Well that is very simple to config. Just add this into your .screenrc

defshell -bash`

Since sometimes your bash in a screen session is not identify in your terminal, you can also add this info into your PS variable in .bashrc. Just adding something like this in the end of your .bashrc:


set_term_name() {
    current="screen"
    if [ $TERM=$current ];
    then
        echo $TERM
    fi
}
export PS1="\u@\h \[\033[32m\]\w[\033[33m\] \$(set_term_name)\[\033[00m\] $"

That’s all folks!

Read Full Post »

If you are an unhappy user of Chromium-browser or chrome you know exactly what I’m talking about. I stopped to count how many time I had to reboot my whole system because these two guys. Yeah, I’m guilty in part. Since I often have 30 tabs in my browser. But, shouldn’t these guys handle with memory resource in a more clever way? Recently I read that the new way Chrome is deal with it is to kill tabs that reach a limit amount of memory, but it’s not a happy end at all.
In my system, Linux Mint (currently), I just lost my counts the times I had to reboot all the system because The Memory Eater.
For now , seems it hasn’t any solution, but I realized these guys have a chrome://memory-redirect tool [1], that show you how many memory are in using. Take a look at the s-shot.
chromium

While any real solution comes, how about to keep an eye in who is the greedy memory guy and close it :).

Resources:

[1] https://www.chromium.org/developers/memory-usage-backgrounder

 

Read Full Post »

Usando Kmemleak

Desenvolver software em C requer muita atenção, mas às vezes deixamos alguns descuidos. Em C um descuido pode ser grave, pode gerar bugs indesejados (não que haja algum desejado). Um dos erros comuns é não lidar corretamente com a alocação de recurso de memória. Em particular, alocar e esquecer de liberar ela para o sistema (memory leak).

Ao contrário de linguagens como Java, Python, C++ que possuem garbage collector, C é uma linguagem que espera de você a sabedoria de um Jedi na hora de lidar com recursos de baixo nível, tal como memória.

Quando um problema de memory leak acontece em user space (aplicações a nível de usuário)  a solução é partir para ferramentas bem conhecidas como Valgrind. Com ela é possível encontrar informações precisas sobre os memory leaks causados. Mas e se você programa em nível de Kernel, um driver/modulo por exemplo? Bem, o ponto é que você deve ser um mestre Jedi se chegou a esse nível e memory leaks não deveriam ser erros comuns no seu dia a dia. Mas somos humanos, certo?

Kmemleak foi introduzido no kernel 2.6.17-rc6. É nada mais que um mecanismo de memleak detector em kernel space. Tem lá o seu custo, já que a ideia por trás do kmemleak é varrer de tempos em tempos o kernel, descobrir quais memorias estão/foram alocadas e quais não foram liberadas, dessa forma sinalizando ou possíveis memleaks ou de fato um. 

Há uma discussão extensa sobre esse recurso. Se ele é realmente útil, se o custo dele não é um peso para quem quer usar. Principalmente em sistemas com muito recurso de memoria. Não por menos, quando se usa o kmemleak se percebe um certo acréscimo de tempo no boot do sistema.

Porém, considerações de lado, vamos imaginar que em algum momento você precisará usar este recurso. Então, como usá-lo?

Antes de tudo você irá precisar compilar o seu kernel com esse recurso selecionado  CONFIG_DEBUG_KMEMLEAK (kernel hacking -> kernel memory leak detector). Segundo, você irá precisar setar o tamanho do log que o kmemleak irá usar. O valor default é 400, aconselho usar o limite: 40000 assim você irá evitar surpresas (o recurso estourar o log e ficar desabilitado).

Com o kernel compilado com as opções de kmemleak é só instalar e rebootar a máquina. Feito isso partimos para a montagem do debugfs, pois é lá que o sysfs para o kmemleak estará presente para ser usado.  Para tal: mount -t debugfs nodev /sys/kernel/debug/.  Pronto, seu kmemleak detector está pronto para ser usado.

Como usá-lo:

  • echo clear > /sys/kernel/debug/kmemleak (limpa o log atual e talvez você queira fazer isso antes de buscar pelos leaks do seu módulo)
  • echo scan > /sys/kernel/debug/kmemleak (força um scan nesse instante, uma vez que por default o scan é realizado de 10 em 10 minutos. Este é o valor default e você poderá alterá-lo)
  • cat /sys/kernel/debug/kmemleak (irá listar os possíveis memory leaks encontrados)

Para saber mais sobre como usar o kmemleak dê uma olhada na documentação link [1]

Para testar como ele funciona você pode escrever um simples módulo hello world e provocar um memory leak.

  #include <inux/kernel.h>                                                                                                                                                                                                       
  #include <linux/module.h>
  #include <linux/init.h>
  #include <linux/vmalloc.h>

  void causing_memleak(void)
  {
          char *ptr;
          ptr = vmalloc(1024);
  }

  static int __init hello_init(void)
  {
          causing_memleak();
          pr_debug(KERN_DEBUG "Hello World!\n");
          return 0;
  }
  
  static void hello_cleanup(void)
  {
          pr_debug(KERN_DEBUG "Cleaning up\n");
  }
  
  module_init(hello_init);
  module_exit(hello_cleanup);

No código acima a função “causing_memleak” aloca um dado recurso de memória, mas nunca o libera. Se você carregar este módulo e depois liberar ele, por fim usar kmemleak: cat /sys/kernel/debug/kmemleak, você verá que ele foi detectado.

Finalizando, é um recurso útil, mas o mais esperado é que você saiba o que tá fazendo e que jamais deixe que situações como esta ocorra em kernel space :). Mas se um dia precisar usar kmemleak, go ahead.

Referências:
[1] https://www.kernel.org/doc/Documentation/kmemleak.txt

[2] http://lwn.net/Articles/187193/

[3] http://psankar.blogspot.com.br/2010/11/detecting-memory-leaks-in-kernel.html

[4]  https://lwn.net/Articles/187979/

Read Full Post »

Você que está brincando com o eudpytula, essa é pra você.

  • Compila: make localmodconfig (assim ele vai selecionar os módulos que realmente importam para sua distro)
  • yes “” | make localmodconfig (dê yes pra todo mundo)
  • make -j42 (substitua 42 pelo seu número de cores, ou deixe o 42 e ele usará o máximo)
  • make modules (construindo seus módulos)
  • make modules_install
  • make install
  • Reboot, teste, chore se o seu kernel bugar.
  • Hora da limpeza, você terá que deletar do /boot, na mão, o que você não quer. Depois, grub-mkconfig -o <<caminho do grub.cfc).

 

Done =)

Read Full Post »

Para aqueles que começaram a programar em Python agora, encontrar regras de indentação, e mais importante, quebrar elas e receber erros no shell, não deve ser algo muito interessante.
Eu particularmente gosto das regras do Python, elas agregam valor as boas práticas de coding. Tudo para que seu código seja mais legível e outros possam lê-lo um dia, em um futuro, sem precisar te xingar.

Como auxílio as boas práticas é possível encontrar alguns cheats e ferramentes que podem ajudar.
Primeiro, os cheats (e infelizmente essa é apenas para usuários vim/vi).

  • Nada mais que 80 colunas: essa ideia não poderia ser melhor, já que nem todo mundo usa um monitor wide screen, certo. Basta por essa linha no seu .vimrc silent match ErrorMsg /\%>80v/
  • 4 espaços: essa vem direto do PEP08. Diferente do Kernel que usa 8 espaços ou GNU style. Python usa 4 espaços (nada de tab!). Basta setar as seguintes linha no seu .vimrc e tudo funcionará perfeitamente.
set smartindent
set tabstop=4
set softtabstop=4
set shiftwidth=4
set expandtab
  • Retab: útil se o seu arquivo está zoneado por tabs. Basta digitar ESC: %retab no vim. Ele vai arrumar seu .py de acordo com a configuração anterior de espaços.
  • Removendo espaços no final da linha ou traling white spaces: autocmd BufWritePre *.py :%s/\s\+$//e.

Bacana, certo?

Para auxiliar ainda mais, que tal usar uma ferramenta chamada pep8 que vai te ajudar a checar se o seu arquivo está de acordo com o pep08 e de quebra usar o Pylint para analisar estaticamente o seu código?

Ambas são incrivelmente fáceis de se usar. Então, espero que essas dicas tenham sido úteis =)

Read Full Post »

Sou um leitor assíduo do Geeks for Geeks, um dos melhores sites para apaixonados em C, estudantes de computação, e afins. O legal desse site é que ele te ajuda a entender várias coisas bacanas da linguagem C. Além de te mostrar jeitos curiosos de usar a linguagem, e inevitavelmente te fazendo aprender alguns truques da linguagem.

Recentemente eu estava lendo o GfG e me deparei com o problema de somar dois números em C sem usar os operadores de +, -, *, /…no site há uma solução usando biwise, super bacana e elegante. Mas o grande tchan está nos comentários onde um cara resolveu o problema de outro jeito. Para ser mais especifico, deste jeito  printf(“%d\n”,printf(“%*s%*s”,var,””,var2,””)); .

E  o que essa linha faz? Ela retorna o resultado da soma de var com var2. Mas como essa linha funciona? É agora que a coisa fica interessante.

A função printf retorna o número de parâmetros printados na tela, ok, até aqui tudo bem. Mas como raios ele mostra a soma? Vamos lá. Primeiro temos que entender o que o %*s faz. Esse cara %*s formata a sua saída na tela alinhando-a, mas para isso ele precisa vim no seguinte formato.:  (%*s, vezes, string) o que irá resultar em um alinhamento, isso mesmo, a direita, de vezes na string se vezes >= len(string), senão, nada vai acontecer.

Agora como a tal soma ali em cima funciona. Dado que você tem %*s, var, “”, var2, “” e que você quer somar var + var2, este comando vai alinhar o espaço vazio var vezes e o segundo espaço vazio var2 vezes, resultando em var + var2 parâmetros a ser printados. Desse modo teremos  o valor inteiro da soma destes no segundo printf. Simples e curioso não?

Agora vai me dizer que C não é a coisas mais linda do mundo ;]

Nota, se você usar %.*s, você formatara sua string, tipo %*.s, 2, “casa” irá mostrar “ca” na saída do printf.

Read Full Post »

Algumas pessoas escutam isso e saem correndo para as colinas, mas fato, escovar bits, ou brincar com eles e a lógica de  Bool é como brincar com a linguagem nativa do seu computador. Alias, não é como se, é de fato falar e brincar com a linguagem nativa de sua máquina.

Vou aqui falar de forma bem superficial  sobre os operadores bitwise, os magos que nos ajudam a brincar como s bits. Em C, claro, são estes os nossos amiguinhos.

  • &, and. Uso.: 1001 & 1110 , resulta em 1000 (vocês lembram da lógica booleana certo?);
  • |, or. 1110 | 1001, resulta 1111;
  • ~, complementa, tudo que é zero vira um e tudo que um vira zero. ~1100, resulta 0011;
  • ^, xor, ou exclusivo. Os iguais são zero e os diferentes um. 1001 ^ 1110, resulta 0111;
  • >> e <<, deslocamento para a direita e esquerda respectivamente. 1001 >> 2, desloca dois bits para a direita de 1001 resultando 0010. O contrário acontece para o deslocamento a esquerda.

Agora que vocês conhecem essas quatro maravilhas que tal brincar com eles? Talvez você se pergunta “mas para que raios isso é útil”. Acredite, se você gosta de programar e principalmente gosta de entender como um computador funciona, e ainda mais importante, programa em C, você um dia usará este operadores. Por hora eu recomendo os puzzles de um site muito bom Geeks for Geeks. Nesse site você vai encontrar problemas que quase sempre são resolvidos usando bitwise, claro que eles são resolvidos assim porque alguma limitação é imposta. E é exatamente este o ponto, o porquê você deve aprender sobre isto agora, para que um dia quando precisar e tiver limites no que deve fazer (complexidade, otimização, etc)  usá-los de forma satisfatória.

Leiam e acessem o Geeks for geeks, principalmente a sessão de puzzles, isso é pura diversão x].

Read Full Post »

Older Posts »

Design a site like this with WordPress.com
Get started