Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Temas - Cervantes_xD

#1
C# - VB.NET / [C#] El cervanBot para underc0de
Agosto 22, 2011, 09:57:06 AM
Bueno, pues en MitM ya lo tengo posteado xD

Es el mismo bot que estoy haciendo pero con modificaciones para UC, ya que el comando principal lo he implementado que es el de poder ver los post recientes en un foro SMF 2.0 como este y como mitm. Obviamente el cargo de Admin se lo dejo a ANTRAX que es el admin del canal, pero el code estará aquí para quien quiera bajarlo y ver las chapuzas que he hecho (LOL)

Código: csharp
//Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SocketsC;

namespace SocketsC
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket cliente = new Socket();
            cliente.Connect();
        }
    }
}


Código: csharp
//getWebDoc.cs
using System.Web;
using System.Net;
using System.IO;
using System.Text;


namespace SocketsC
{
    class getWebDoc
    {
        public static void getDocMitM(ref List<String> noticias)
        {
            int ultimos = 0;
            StringBuilder final = new StringBuilder("");

            if (noticias == null)
            {
                noticias = new List<String>();
            }
            else
                if (noticias.Count != 0)
                    noticias.RemoveAt(0);

            try
            {

                String baseUri = "http://www.underc0de.org/foro/SSI.php?ssi_function=recentTopics";
                HttpWebRequest connection =
                (HttpWebRequest)HttpWebRequest.Create(baseUri);

                connection.Method = "GET";
                HttpWebResponse response =
                (HttpWebResponse)connection.GetResponse();

                StreamReader sr =
                new StreamReader(response.GetResponseStream(),
                Encoding.UTF8);

                String respuesta;

                while (!sr.EndOfStream)
                {
                    respuesta = sr.ReadLine();
                    //Console.WriteLine(respuesta);
                    try
                    {
                        if (respuesta.Length > 5)
                        {
                            if (respuesta.Substring(0, 6) == "\t\t\t\t\t[")
                            {
                                //Console.WriteLine(respuesta);
                                sr.ReadLine();
                                sr.ReadLine();
                                respuesta = sr.ReadLine();
                                int i = 0;

                                while (respuesta.ElementAt<char>(i) != '\"')
                                    i++;
                                i++;

                                while (respuesta.ElementAt<char>(i) != '\"')
                                {
                                    final.Append(respuesta.ElementAt<char>(i));
                                    i++;
                                }

                                final.Append(" - ");
                                i = i+2;

                                while (respuesta.ElementAt<char>(i) != '<')
                                {
                                    final.Append(respuesta.ElementAt<char>(i));
                                    i++;
                                }
                                final.Append("\r\n");
                                noticias.Add(final.ToString());
                                final.Clear();
                               
                                ultimos++;
                                if (ultimos == 5)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    catch { }
                }
                sr.Dispose();
                sr.Close();
            }
            catch
            {
                Console.WriteLine("No se ha podido obtener documento");
            }
        }       
    }
}


Código: csharp
//Socket.cs
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;

namespace SocketsC
{
    class Socket
    {
        string admin = "ANTRAX";
        string publicos = "Publicos: <!help> <!MD5 cadena> <!news>\r\n";
        string privados = "Privados: <quit> <exit> <reconnect>\r\n";

        TcpClient socketForServer;
        string server = "ifg.ircnode.com";
        int puerto = 6667;
        string canal = "#underc0de";
        StreamReader streamReader;
        StreamWriter streamWriter;
        String usuario = "";
        String comando;
        int salidaApp = 0;
        List<String> noticias = new List<String>();

        public static int numPalabras(string cad)
        {
            int pal = 1;
            int i = 0;
            try
            {
                while (i < cad.Length)
                {
                    if (cad.ElementAt<char>(i) == ' ')
                    {
                        pal++;
                        //Console.WriteLine((int)cad.ElementAt<char>(i));
                    }
                    i++;
                }
            }
            catch
            { }
            return pal;
        }

        public static string MD5(string password)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(password);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            password = s.ToString();
            return password;
        }

        public void getComUser(String orden, ref String user, ref String command)
        {
            try
            {
                String commandPri = "";
                //Capturando el comando
                command = "";
                int i = 1;
                while (orden.ElementAt<char>(i) != ':')
                {
                    i++;
                }
                i++;
                command = orden.Substring(i, orden.Length - i);
                if (numPalabras(command) > 1)
                {
                    i = 0;
                    while (command.ElementAt<char>(i) != ' ')
                    {
                        i++;
                    }
                   
                    commandPri = command.Substring(0, i);
                    //Console.WriteLine(commandPri);
                }
               

                //Capturando el user
                user = "";
                i = 1;
                while (orden.ElementAt<char>(i) != '!')
                {
                    i++;
                }
                user = orden.Substring(1, i-1);
                Console.WriteLine(user+"/"+command);

                if (command == "quit")
                {
                    if (user == admin)
                    {
                        streamWriter.WriteLine("PART "+canal+"\r\n");
                        streamWriter.Flush();
                        streamWriter.WriteLine("QUIT\r\n");
                        streamWriter.Flush();
                        streamWriter.Close();
                        streamReader.Close();
                        salidaApp = 1;
                    }
                }
                if (commandPri == "!MD5")
                {
                    i = 0;
                    while (command.ElementAt<char>(i) != ' ')
                        i++;
                    i++;

                    streamWriter.WriteLine("PRIVMSG "+canal+" :" + user + ": " + MD5(command.Substring(i, command.Length - i)));
                    streamWriter.Flush();
                }
                if (command == "reconnect")
                {
                    if (user == admin)
                    {
                        streamWriter.WriteLine("JOIN " + canal + "\r\n");
                        streamWriter.Flush();
                    }
                }
                if (command == "exit")
                {
                    if (user == admin)
                    {
                        streamWriter.WriteLine("PART " + canal + "\r\n");
                        streamWriter.Flush();
                    }
                }
                if (command == "!news")
                {
                    getWebDoc.getDocMitM(ref noticias);
                    while(noticias.Count != 0)
                    {
                        string notAct = noticias.ElementAt<String>(0);
                        streamWriter.WriteLine("PRIVMSG " + canal + " :" + notAct);
                        streamWriter.Flush();
                        noticias.RemoveAt(0);
                    }
                }
                if (command == "!help")
                {
                    streamWriter.WriteLine("PRIVMSG " + canal + " :" + user);
                    streamWriter.Flush();
                    streamWriter.WriteLine("PRIVMSG "+ canal + " :" + publicos);
                    streamWriter.Flush();
                    streamWriter.WriteLine("PRIVMSG " + canal + " :" + privados);
                    streamWriter.Flush();
                }

            }
            catch
            {
                //Console.WriteLine("Crap");
            }
        }

        public void Connect()
        {
             
            try
            { 
                //Creamos un TcpCliente y le pasamos
                //el server y el puerto.
                socketForServer = new TcpClient(server, puerto);
            }
            catch
            {
                Console.WriteLine(
                "No se pudo conectar a {0}:{1}", server, puerto);
                return;
            }


            //aqui es lo mismo que en el server. Usamos StreamWriter y Reader.
            NetworkStream networkStream = socketForServer.GetStream();

            streamReader =
                  new System.IO.StreamReader(networkStream);

            streamWriter =
                  new System.IO.StreamWriter(networkStream);

            try
            {
                //Básico para la conexión
                String salida;
                String outputString = streamReader.ReadLine();
                Console.WriteLine(outputString);
                outputString = streamReader.ReadLine();
                Console.WriteLine(outputString);

                streamWriter.WriteLine("PASS miclavedered1"); //1.- Clave de red
                streamWriter.Flush();
                streamWriter.WriteLine("NICK cervanBot\r\n"); //2.- Nick del bot
                streamWriter.Flush();
                //A partir de aquí el servidor comenzará a enviar PINGS
                outputString = streamReader.ReadLine();
                salida = outputString.Substring(0, 4);
                Console.WriteLine(outputString);
                if (salida == "PING")
                {
                    streamWriter.WriteLine("PONG" + outputString.Substring(4, outputString.Length - 4));
                    streamWriter.Flush();
                }
                streamWriter.WriteLine("USER cervbot tolmoon tolsun :Bot Cervantes\r\n");
                            //3.- Nombre de usuario. Ya desde aquí oficialmente estás dentro de la red
                streamWriter.Flush();

                outputString = streamReader.ReadLine();
                salida = outputString.Substring(0, 4);
                Console.WriteLine(outputString);
                if (salida == "PING")
                {
                    streamWriter.WriteLine("PONG" + outputString.Substring(4, outputString.Length - 4));
                    streamWriter.Flush();
                }
                streamWriter.WriteLine("JOIN "+canal+"\r\n"); //4.- Nos unimos al canal

                streamWriter.Flush();

                while (true)
                {
                    outputString = streamReader.ReadLine();
                    salida = outputString.Substring(0, 4);
                    if (salida == "PING")
                    {
                        Console.WriteLine(outputString);
                        streamWriter.WriteLine("PONG" + outputString.Substring(4, outputString.Length - 4));
                        streamWriter.Flush();
                        //Respondiendo a los PINGS
                    }
                    else
                        getComUser(outputString, ref usuario, ref comando);
                    if (salidaApp == 1)
                        break;
                }
             
            }
            catch
            {
                Console.WriteLine("Exception reading from Server");
                //Se cagó el socket
            }
            finally
            {
                networkStream.Close();
            }
        }

    }
}


Espero que les guste y que no me fusilen por las cagadas que de seguro tendrá el code xD pero sobretodo no quería usar regex y me he quebrado la cabeza para lograrlo. No obstante, mereció la pena x)

Un saludo.
#2
Base64.hpp
Código: cpp
#include <iostream>
#include <string>
#include <math.h>
#include <cstdio>
#include <cstdlib>

using namespace std;

class Base64
{
private:
static string alfabeto;
static string TextToBinBase(string a, int b);
static void Reverse(string &a);
static void Complete(string &a, int b);
public:
static string Encode(string a);
static string Decode(string a);
static string Binary(int a, int b);
static int BinToInt(string a);
static string TextToBin(string a, int b);

};


Base64.cpp
Código: cpp
#include "Base64.hpp"
#include <sstream>

using namespace std;

string Base64::alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

string Base64::Binary(int a, int b)
{
string result = "";
while(a != 0)
{
if((a%2) == 0)
result += '0';
else
result += '1';
a = a/2;
}

Complete(result, b);
Reverse(result);
return result;
}

string Base64::Encode(string a)
{
string binario = TextToBin(a, 8);
stringstream ret;
string *buffer;

int padding;
int alt = binario.length()%6;
int aux;

if(alt == 0)
{
int numcadenas = binario.length() / 6;
buffer = new string[numcadenas];
if(buffer != NULL)
{
for(int i = 0; i < numcadenas; i++)
{
buffer[ i ] = binario.substr(i*6, 6);
aux = BinToInt(buffer[ i ]);
ret << alfabeto.at(aux);
}

delete[] buffer;
}
}
else
{
padding = (6 - alt) / 2;
Complete(binario, binario.length() + (6-alt));
int numcadenas = binario.length() / 6;
buffer = new string[numcadenas];
if(buffer != NULL)
{
int i;
for(i = 0; i < numcadenas; i++)
{
buffer[ i ] = binario.substr(i*6, 6);
aux = BinToInt(buffer[ i ]);
ret << alfabeto.at(aux);
}

for(i = 0; i < padding; i++)
ret<<"=";

delete[] buffer;
}
}

return ret.str();
}

string Base64::Decode(string a)
{
string binario;
string cadena;
stringstream delpadding;

int i;

for(i = 0; i < a.length(); i++)
{
if(a.at(i) != '=')
delpadding<<a.at(i);
}

cadena = delpadding.str();
binario = TextToBinBase(cadena, 6);

stringstream ret;
string *buffer;

int padding;
int alt = binario.length()/8;
int aux;

buffer = new string[alt];

if(buffer != NULL)
{
for(i = 0; i < alt; i++)
{
buffer[ i ] = binario.substr(i*8, 8);
aux = BinToInt(buffer[ i ]);
ret << (char)aux;
}
cout<<endl;
delete[] buffer;
}

return ret.str();
}

string Base64::TextToBin(string a, int b)
{
stringstream c;
for(int i = 0; i < a.length(); i++)
{
c<<Binary((int)a.at(i), b);
}
return c.str();
}

string Base64::TextToBinBase(string a, int b)
{
stringstream c;
for(int i = 0; i < a.length(); i++)
{
int pos = (int)alfabeto.find(a.at(i));
c<<Binary(pos, b);
}
return c.str();
}

void Base64::Reverse(string& a)
{
string aux = "";
for(int i = 0; i < a.length(); i++)
aux += a.at(a.length() - i - 1);
a = aux;
}

void Base64::Complete(string &a, int b)
{
if(a.length() < b)
{
int fin = b - a.length();
a.append(fin, '0');
}
}

int Base64::BinToInt(string a)
{
int aux = 0;

for(int i = 0; i < a.length(); i++)
{
if(a.at(i) == '1')
{
float ex = a.length() -i -1;
aux += (int)pow(2, ex);
}
}

return aux;
}


Main.cpp
Código: cpp
#include "Base64.hpp"

/*
Compilación utilizando g++:
g++ Main.cpp Base64.cpp -o base64

Uso:
base64 -flag string
Ej:
base64 -c hola

Flags disponibles:

-c : Encripta
-d : Desencripta

Se pueden encriptar cadenas más grandes a una sola palabra si se coloca todo entre comillas dobles
Ej:
base64 -c "Encriptando textos con espacios"
*/

using namespace std;

void usage()
{
cout<<"Usage: "<<endl;
cout<<"base64 -c string || Crypt a string to a Base64 string"<<endl;
cout<<"base64 -d string || Decrypt a Base64 string"<<endl;
}

int main(int argv, char** args)
{
if(argv != 3)
{
usage();
}
else
{
string op, str;
op = args[1];
str = args[2];

if(op == "-d")
{
cout<<Base64::Decode(str)<<endl;
}
if(op == "-c")
{
cout<<Base64::Encode(str)<<endl;
}
if( (op != "-c") && (op != "-d"))
{
usage();
}
}
return 0;
}


Generado con el compilador de C++ de Visual C++ Express 2010

El proceso es el siguiente:
Codificación:

1.- Convertir el texto a binario utilizado el valor ASCII de sus caracteres, 8 bits deben salir (si es menos se rellena con ceros) por carácter
2.- Separar en cadenas de 6

Si la última cadena no es de 6 bits, se completa con 0 y a la hora de representar la cadena se añade el caracter = (padding), ¿cuántos? pues un = por cada dos ceros, a la hora de desencriptar no se tienen en cuenta

3.- Cada subcadena de 6 pasarla a entero y el valor que dé se corresponde con una posición en la tabla "alfabeto"

Decodificación:
1.- Convertir el texto a binario utilizado la posición que cada carácter ocupa en la tabla, 6 bits deben salir y no hay que rellenar nada (he ignorado el padding, por lo que su valor no se convierte :B es sólo un "aditivo" a la hora de encriptar)
2.- La longitud de la cadena es múltiplo de 8, así que se divide todo en subcadenas binarias de 8 bits
3.- Convertir cada cadena binaria a entero
4.- Pasar cada entero a ASCII (un simple casting :P)

Voilá! Espero que les sea de utilidad (aunque no lo creo x) )

He usado todo prácticamente estático porque no he visto la necesidad de tener que crear un objeto que lo único que tenga sean algoritmos y nada más sustancial, la ventaja es que obviamente no se necesita crear un objeto de la clase para poder encriptar/desencriptar

Un saludo

P.D: He usados tablas y cosas así, con lo cual hay bastantes cosas entre corchetes, y no sé si alguna de esas ha sido interpretada mal (como los [ i ] para poner la letra en cursiva xD)
Si no funciona me avisan y trato de arreglarlo
#3
Aquí un pequeño código que me ayudaron a llevar a cabo. Su función es la de cambiar automáticamente el fondo de pantalla para el gestor de ventanas fluxbox en GNU/Linux

Código: php
#!/bin/bash

# Directorio de fondos de pantalla
img_dir=~/Imagenes
# Tiempo de transiccion entre cada imagen
tiempo=30
# Numero de veces que se repite la secuencia una vez
# que todas las imagenes pasaron como fondos de pantalla
numero_de_veces=50

cd $img_dir

for i in `seq 1 $numero_de_veces`; do
for i in `ls *.{jpg,png}`; do
  fbsetbg -f $i
  sleep $tiempo
done
done

exit


Es para imágenes en formato jpg y png :P