martes, 19 de agosto de 2008

Kernel Simple

h0aX [hoax_ws@yahoo.es]

En la edición 43 de este boletín se publicó un código titulado "Mulo-BootLoader" donde se presentaba un boot loader en su estado más simple. Siguiendo la misma praxis probablemente deba nombrar este código "Kernel a lo bestia" o algo parecido, pero por respeto a las bestias me limitaré a llamarlo "Kernel Simple".

Esta vez en nuestro taller de códigos presentaré el primer kernel publicado en BlackHat, tan cubano como inacabado pero muy útil para aquellos que deseen orientación en la utilización de las interrupciones del BIOS como primera línea de fuego en el acceso al hardware de nuestras PCs.

Aclaro que el código va dedicado solo a programadores experimentados en C, con sólidas bases de ensamblador y arquitectura de máquinas 8086. Por falta de tiempo no podría entregarme al placer de escribir un manual del tipo -Comenzando el desarrollo de un kernel-, no obstante estoy dispuesto a compartir gustosamente mi bibliografía con aquellas personas que me hagan saber su interés.

Por último sería injusto dejar de mencionar el sistema ADIX OS de Aditya Kumar Singh como mi principal referencia para este experimento.

[Instalando el kernel en un floppy]
Al final de este artículo encontrarás disponible para su descarga el archivo Calipso.zip. A continuación se describen los pasos a seguir para instalar su contenido.

1 Con una consola del sistema posiciónate en el directorio BOOT
2 Introduce un diskette formateado en la disquetera
3 Ejecuta el siguiente comando en el símbolo del sistema "PC boot12.bin 0 3 –f0" (sin comillas)
4 Ejecuta el siguiente comando en el símbolo del sistema "PC boot12.bin 3e 1c2 –f0 3e"
5 Por último copiamos el kernel al diskette con el comando "COPY ..\Kernel\kernel.bin a:"

Nota: PC.exe es un programa llamado Partial Copy cuya funcionalidad consiste en el copiado de datos raw a disco, de este modo escribimos el bootloader en el sector de arranque inicial del disquette.

Para probar el sistema reinicia el PC con el diskette.

Archivos relacionados

Calipso.zip

Continuar leyendo

Respuesta al Ejercicio BH 63

Eddy [delvalle@otepr.co.cu]

Enunciado:

Hay M soldados en un cerco y tienen un solo caballo. Para salir forman circularmente y comienzan a contar inicialmente por un soldado elegido al azar. Cada N soldados uno sale y el último se queda con el caballo.
Hacer un programa que permita imprimir que soldado saldrá del cerco eon el caballo si se conoce la cantidad de soldados (M) y el incremento (N) en el conteo.

#!/usr/bin/env python
cant_soldados = int(raw_input("Entre la cantidad soldados: "))
iteraciones = int(raw_input("Entre el numero escogido: "))

soldados = range(1, cant_soldados+1)

i = 0
n = 1
while len(soldados) > 1:
if i == len(soldados):
i = 0
if n == iteraciones:
del soldados[i]
n = 1
else:
n = n + 1
i = i + 1

print soldados[0]

Continuar leyendo

Ejercicio BH 64

Confeccione un programa para imprimir todos los números pares de 4 cifras formados por los d¡gitos 0,1,2,3 que cumplan la condición de que los d¡gitos que lo forman no se repitan.

Continuar leyendo

Extraer elementos de tipo específico de una lista

Eddy [delvalle@otepr.co.cu]

Esta es una función a la que se le pasa como parámetro un tipo y una colección, y ella devuelve sólo los elementos que son del tipo que se le pasó como parámetro, este puede ser, por su puesto, una clase definina por ti.
La sección de código bajo la definición de la función es para probar la función con un ejemplo.

#!/usr/bin/env python
def extraerPorTipo(tipo, coleccion):
lista = []
for elemento in coleccion:
if isinstance(elemento, tipo):
lista.append(elemento)
return lista

#esta seccion hace la comprobacion de la función
cadena = "esta es una cadena"
milista = ["asd", 3, "hola", 5.0, 4, cadena]
print "de la lista "+str(milista)+" son de tipo entero:"
print extraerPorTipo(int, milista)
raw_input("presione enter para continuar")

#esto devolvera:
# de la lista ['asd', 3, 'hola', 5.0, 4, 'esta es una cadena'] son de tipo entero:
# [3, 4]

Continuar leyendo

Lupa

CHenry [chenry@lab.matcom.uh.cu]

Windows tiene un programa que hace algo similar, no obstante, nunca está demás ver una réplica de dicha utilidad, más cuando esta ha sido creada por un cubano, miembro de BlackHat y muchísimo más si pone a disposición de todos el código fuente.

/* Escrito por chenry para la comunidad de BH
Compilado con VS2003
*/
#include "stdafx.h"
#include "lupa.h"
#define MAX_LOADSTRING 100

HINSTANCE hInst;
TCHAR szTitle[MAX_LOADSTRING] = "Lupa by chenry for BH";
TCHAR szWindowClass[MAX_LOADSTRING] = "lupa";

ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
  MSG msg;
  HACCEL hAccelTable;

   MyRegisterClass(hInstance);

  if (!InitInstance (hInstance, nCmdShow))
  {
    return FALSE;
  }

  hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_LUPA);

  while (GetMessage(&msg, NULL, 0, 0))
  {
    if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
    {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }

  return (int) msg.wParam;
}

ATOM MyRegisterClass(HINSTANCE hInstance)
{
  WNDCLASSEX wcex;

  wcex.cbSize = sizeof(WNDCLASSEX);

  wcex.style = CS_HREDRAW | CS_VREDRAW;
  wcex.lpfnWndProc = (WNDPROC)WndProc;
  wcex.cbClsExtra = 0;
  wcex.cbWndExtra = 0;
  wcex.hInstance = hInstance;
  wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_LUPA);
  wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
  wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
  wcex.lpszMenuName = (LPCTSTR)IDC_LUPA;
  wcex.lpszClassName = szWindowClass;
  wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

  return RegisterClassEx(&wcex);
}

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
  HWND hWnd;

  hInst = hInstance; // Store instance handle in our global variable

  hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW | WS_VSCROLL,
50,50,200,200, NULL, NULL, hInstance, NULL);

  if (!hWnd)
  {
    return FALSE;
  }

  ShowWindow(hWnd, nCmdShow);
  UpdateWindow(hWnd);

  return TRUE;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  int wmId, wmEvent;
  PAINTSTRUCT ps;

  HDC hdc,hdcDesktop;
  static RECT paintRect;

  RECT clientRect;
  POINT punto;

  static bool isPainting;
  SCROLLINFO scroll;

  static int zoom;
  static bool onTimer=false;

  switch (message)
  {
    case WM_VSCROLL:
    {
      GetClientRect(hWnd,&clientRect);
      switch (LOWORD(wParam))
      {
        case SB_LINEUP:
        {
          if(zoom>1&&zoom<6)
          {
            zoom = zoom - 1;
            SetScrollPos(hWnd,SB_VERT,(zoom -1) * clientRect.bottom/5,TRUE);
          }
          return 0;
        }
        case SB_LINEDOWN:
        {
          if(zoom>0&&zoom<5)
          {
            zoom = zoom + 1;
            SetScrollPos(hWnd,SB_VERT,(zoom -1) * clientRect.bottom/5,TRUE);
          }
          return 0;
        }
      }

      return 0;
    }
    case WM_SIZE:
    {
      GetClientRect(hWnd,&clientRect);
      scroll.cbSize = sizeof(SCROLLINFO);
      scroll.fMask = SIF_ALL;
      scroll.nMin = 0;
      scroll.nMax = clientRect.bottom;
      scroll.nPage = clientRect.bottom/5;
      scroll.nPos = (zoom -1) * clientRect.bottom/5;
      SetScrollInfo(hWnd,SB_VERT,&scroll,TRUE);
      return 0;
    }
    case WM_LBUTTONDOWN:
    {
      hdcDesktop = GetDC(NULL);
      SetROP2(hdcDesktop, R2_NOT);

      Rectangle(hdcDesktop,paintRect.left,paintRect.top,paintRect.right,paintRect.bottom);
      DeleteDC(hdcDesktop);

      SetCapture(hWnd);
      isPainting = true;
      onTimer=false;

      return 0;
    }
    case WM_LBUTTONUP:
    {
      hdcDesktop = GetDC(NULL);
      SetROP2(hdcDesktop, R2_NOT);
      Rectangle(hdcDesktop,paintRect.left,paintRect.top,paintRect.right,paintRect.bottom);
      DeleteDC(hdcDesktop);

      InvalidateRect(hWnd,NULL,true);

      ReleaseCapture();
      isPainting = false;
      onTimer=true;

      return 0;
    }

    case WM_MOUSEMOVE:
    {
      if(isPainting)
      {
        GetCursorPos(&punto);

        hdcDesktop = GetDC(NULL);
        SetROP2(hdcDesktop, R2_NOT);
        Rectangle(hdcDesktop,paintRect.left,paintRect.top,paintRect.right,paintRect.bottom);
        DeleteDC(hdcDesktop);

        GetClientRect(hWnd,&clientRect);

        paintRect.left = punto.x - (clientRect.right - clientRect.left)/(2*zoom);
        paintRect.right = punto.x + (clientRect.right - clientRect.left)/(2*zoom);
        paintRect.top = punto.y - (clientRect.bottom - clientRect.top)/(2*zoom);
        paintRect.bottom = punto.y + (clientRect.bottom - clientRect.top)/(2*zoom);

        hdcDesktop = GetDC(NULL);
        SetROP2(hdcDesktop, R2_NOT);

        Rectangle(hdcDesktop,paintRect.left,paintRect.top,paintRect.right,paintRect.bottom);
        DeleteDC(hdcDesktop);

        InvalidateRect(hWnd,NULL,true);
      }
      return 0;
    }
    case WM_CREATE:
    {
      zoom = 5;
      GetClientRect(hWnd,&clientRect);
      scroll.cbSize = sizeof(SCROLLINFO);
      scroll.fMask = SIF_ALL;
      scroll.nMin = 0;
      scroll.nMax = clientRect.bottom;
      scroll.nPage = clientRect.bottom/5;
      scroll.nPos = (zoom -1) * clientRect.bottom/5;;
      SetScrollInfo(hWnd,SB_VERT,&scroll,TRUE);

      isPainting = false;
      SetWindowPos(hWnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE);
      SetTimer(hWnd,1,100,NULL);
      return 0;
    }
    case WM_TIMER:
    {
      if(onTimer)
      {
        hdc = GetDC(hWnd);

        hdcDesktop = GetDC(NULL);
        GetClientRect(hWnd,&clientRect);
        if(isPainting)
        StretchBlt(hdc,clientRect.left,clientRect.top,(clientRect.right - clientRect.left),(clientRect.bottom - clientRect.top),hdcDesktop,paintRect.left,paintRect.top,(paintRect.right - paintRect.left),(paintRect.bottom - paintRect.top),SRCINVERT);
        else
StretchBlt(hdc,clientRect.left,clientRect.top,(clientRect.right - clientRect.left),(clientRect.bottom - clientRect.top),hdcDesktop,paintRect.left,paintRect.top,(paintRect.right - paintRect.left),(paintRect.bottom - paintRect.top),SRCCOPY);

        DeleteDC(hdcDesktop);

        ReleaseDC(hWnd,hdc);

      }
      return 0;
    }
    case WM_COMMAND:
    {
      wmId = LOWORD(wParam);
      wmEvent = HIWORD(wParam);

// Parse the menu selections:
      switch (wmId)
      {
        case IDM_EXIT:
        DestroyWindow(hWnd);
        return 0;
        default:
        return DefWindowProc(hWnd, message, wParam, lParam);
      }
      return 0;
    }
    case WM_PAINT:
    {
      hdc = BeginPaint(hWnd, &ps);

      hdcDesktop = GetDC(NULL);
      GetClientRect(hWnd,&clientRect);
      if(isPainting)
      StretchBlt(hdc,clientRect.left,clientRect.top,(clientRect.right - clientRect.left),(clientRect.bottom - clientRect.top),hdcDesktop,paintRect.left,paintRect.top,(paintRect.right - paintRect.left),(paintRect.bottom - paintRect.top),SRCINVERT);
      else
      StretchBlt(hdc,clientRect.left,clientRect.top,(clientRect.right - clientRect.left),(clientRect.bottom - clientRect.top),hdcDesktop,paintRect.left,paintRect.top,(paintRect.right - paintRect.left),(paintRect.bottom - paintRect.top),SRCCOPY);

      DeleteDC(hdcDesktop);

      EndPaint(hWnd, &ps);
      return 0;
    }
    case WM_DESTROY:
    {
      PostQuitMessage(0);
      return 0;
    }
    default:
    return DefWindowProc(hWnd, message, wParam, lParam);
  }
  return 0;
}

void DrawBoxOutline (HWND hwnd, RECT rect)
{
  HDC hdc ;
  hdc = GetDC (NULL) ;
  SetROP2 (hdc, R2_NOT) ;
  SelectObject (hdc, GetStockObject (NULL_BRUSH)) ;
  Rectangle (hdc, rect.left, rect.top, rect.right, rect.bottom) ;
  ReleaseDC (hwnd, hdc) ;
}

Archivos relacionados

Lupa.zip

Continuar leyendo