Generate sql table from file names

Someone who I work with is sad that it’s got to manually insert some movies into a database. So I wanted to help him building a fast solution he must only rename the files like this

description1_description2_test_lala.mp4

He runs the python script and it will automatically build a sql file with INSERT stataments 

I really like python for small tasks,anything than the old braindead C :)

The script is this :

 Python |  copy code |? 
01
import glob
02
import os
03
import sys
04
 
05
li = []
06
print """/
07
 
08
SQL GEN by opc0de 2013
09
 
10
"""
11
folder = raw_input('Enter folder ->')
12
tabela = raw_input('Tabela ->')
13
campuri = raw_input('Campuri ->')
14
if os.path.isdir(folder):
15
print "Directory exists ... reading file names"
16
else:
17
sys.exit("Invalid directory ... exiting")
18
folder = folder + '/*.*'
19
li = glob.glob(folder)
20
dump = open('dump.sql','w+')
21
for s in li:
22
count = len(folder) - 3
23
s = s[count:]
24
fname = s
25
s = s[:s.rfind('.')]
26
lista = s.split('_')
27
for j in range(len(lista)):
28
lista[j] = "\"" + lista[j] + "\""
29
linie = "INSERT INTO " + tabela + "(" + campuri + ") VALUES("
30
conc = ",".join(lista)
31
linie = linie + conc +",\"" + fname + "\")"
32
dump.write(linie + "\n")
33
print "Dump complete checkout dump.sql!"
34

 

wecodeforfood.com

I would like to present to you my new project http://wecodeforfood.com .

Is an initiative of me and other coders to start working for real people. Coding is something that everyone should know in the 21 st century unfortunately many of us are not interested in the subject, but that doesn’t mean they don’t have great ideas.

http://wecodeforfood.com is the solution for anyone who has a great idea but lacks of computer programming skill 

If you want to join the team send me your resume at : oktav a t wecodeforfood.com

Romanian brute force dictionary

Romanian word brute force dictionary (8 characters or longer).

Feel free to improve it.

Sorry for not posting in a while but I have been busy busy busy…

https://docs.google.com/file/d/0B8Fc2yw0n-t6ZlhZYXRpTjJuTHc/edit?usp=sharing

 

Country codes and flags

I’ve searched all day for some cool flag icons that are named by the country code, a list of countries to import them into a mysql database. I’ve found no such compilation and what I did I wrote a small script to extract them from an website http://www.translatorscafe.com/cafe/EN/ISO-3166-Country-Codes.htm

You can find them here

Simple Web Crawler

There are manny scripts to exploit vulnerabilities these days, (sqlinjection, web application) but the problem is how can you find vulnerable sites? 

I had for a long time the idea of a web crawler that will search for potential vulnerable urls but from the lack of time I decided to do this project in another life.

But that life seems that has come, I am tired of work and decided to take some time off,think at my priorities and do some relaxing code and a web crawler was just the project I needed to relax.

Here it is! Enjoy!

Update dynamic host with python

I recently purchased a raspberry pi, the famous pocket size PC running Linux. Is one of a great things you can buy with 50 euros. I want to be able always to ssh in it, since at home I don’t have a smart router witch is able to update a dynamic dns host when the ip changes I tought myself a cronjob on the pi will do the task.

I hate interpreted languages, they are slow and I hate returning to the old QBASIC days, but on my raspberry pi python seems the most accessible developing tool and it comes with all the shit you need. Developing in C is nice but installing libraries for a simple task is really a hassle,lazarus my favourite development platform doesn’t come with much libraries installed either.

So I decided to write a simple dynamic host updater ( NO – IP ) in python and guess what? I really liked python i’ve managed to build this simple project in 30 minutes. That made me think I want to improve my skill in python so I guess I will be writing interesting scripts in the future.

Here is the script if you are interested : 

USAGE:

python updatehosts.py username@no-ip.com password yourhost.zapto.org

 Python |  copy code |? 
01
import urllib 
02
import sys
03
 
04
print "NO IP UPDATE by opc0de (c) 2013 \n"
05
 
06
ip = urllib.urlopen('http://www.getip.com').read()
07
dump = '<td WIDTH="50%" class="val">'
08
ip = ip[ip.index(dump) + dump.__len__():]
09
ip = ip[:ip.index('</td>')]
10
 
11
try:
12
 urlx = 'http://' + sys.argv[1] + ':' + sys.argv[2] + '@dynupdate.no-ip.com/nic/update?hostname=' + sys.argv[3] + "&myip=" + ip
13
 resp = urllib.urlopen(urlx)
14
 print resp.read()
15
except:
16
 print 'Invalid usage use : updatehost.py username password host'
17

Swap file may contain sensitive data

Forensics is a topic that always raised my interest, if I would like to change my job from programmer in a different area then forensics analyst is one of my top choices.

I recently downloaded EnCase witch is an application that is used by law enforcement to analyse disks searching for sensitive data. I wondered if there is something I can find scanning my own disk. I always use secure delete utilities to wipe my data because you never know… :)

In a country witch is considered by manny a 3-rd world such as Romania, law enforcement often commits abuses and you might get in jail for a stupid file you downloaded from a torrent site.

During my home made forensics analyse I discovered that many files I have accessed were stored in the Window’s swap file. It was logic but I never think at that before, wiping data securely using known tools was in my opinion a good way to keep it safe…but it turns out is not.

So i asked a question on stackexchange, and I received a very nice answer from Cristian Dobre witch I would like to thank.

I will paste here the solution on how you can keep safe from a lot of non friendly organisations.

Yes, swap files can contain sensitive data.

On Windows you can configure the page file (swap file) to be cleared at shutdown this way:

  1. Start regedit32.exe
  2. Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management
  3. Set the data value of ClearPageFileAtShutdown to 1
  4. If the value does not exist, create it with the type REG_DWORD and set it to 1
  5. Restart

I don’t know for sure if this is a secure deletion of the swap data, but from the fact that it adds minutes to the shutdown process and from the text on Microsoft page about ClearPageFileAtShutdown:

Some third-party programs can temporarily store unencrypted (plain-text) passwords or other sensitive information in memory. Although clearing the paging file is not a suitable substitute for physical security of a computer, you might want to do this to increase the security of data on a computer while Windows is not running. “

I would think the data is securely wiped.

On Linux you can manually wipe the swap partition:

  1. Display swap details: swapon -s
  2. Unmount the swap partition: swapoff -a
  3. Overwrite it with zeros: dd if=/dev/zero of=/dev/sdaX bs=1024
  4. Get the UUID of your old swap partition from /etc/fstab
  5. Create a new swap partition with that UUID: mkswap /dev/sdaX -U <old_uuid> 1024
  6. Mount it for usage: swapon -a

Better wiping tools are provided by the Secure-Delete package which comes with the following commands:

  • srm (Secure remove) – used for deleting files or directories currently on your hard disk.
  • smem (Secure memory wiper) – used to wipe traces of data from your computer’s memory (RAM).
  • sfill (Secure free space wiper) – used to wipe all traces of data from the free space on your disk.
  • sswap (Secure swap wiper) – used to wipe all traces of data from your swap partition.

Sswap is designed to delete data which may lie still on your swapspace in a secure manner which can not be recovered by thiefs, law enforcement or other threats.The wipe algorithm is based on the paper “Secure Deletion of Data from Magnetic and Solid-State Memory” presented at the 6th Usenix Security Symposium by Peter Gutmann, one of the leading civilian cryptographers.

 

Cross-platform SMS sending in PDU mode using Lazarus

SMS remains a tool that is used by millions of people everyday since 1993,recently I was asked to develop a cross platform application that will send sms to people on their bills due date. I had an old 3G USB stick lying around just like the one in the picture below :

3g modem

3g modem

I thought I might use it to send sms.I have played before with sms using a set of Delphi components ( NrComm Lib ) but Delphi as you know is not cross platform , neither the components are free. Buying components is just not my style … I live in Romania if you lived here it probably wasn’t your style too. So I decided to write my own sms unit to achieve this purpose.I found some examples on sending sms using Lazarus and I have decided to test if the device works properly. I had the surprise of the device giving me an error every time I tried to send sms. But researching I saw that are two ways that the modem accepts sms messages ( text mode and pdu mode ) . Tried to send sms using pdu mode using the components I mentioned before and worked flawless, then I took the decision to write my unit to send sms in pdu mode.

The result is down bellow , use it how you wish if you got time improve it to receive sms,send mass sms etc.It uses the SynaSer library for interacting with the COM port :D

 Delphi |  copy code |? 
01
unit usms_sender;
02
 
03
{$mode objfpc}{$H+}
04
 
05
interface
06
 
07
uses
08
  Classes, SysUtils,SynaSer;
09
 
10
type
11
  TByteArray = array of Byte;
12
 
13
  ESMSException = class (Exception);
14
 
15
  TSMS = class (TObject)
16
  private
17
  sms : String;
18
  phone : String;
19
  pdu_string : String;
20
  phone_len : Integer;
21
  serial : TBlockSerial;
22
  connected : Boolean;
23
 
24
  function  IsNumeric(const S : String) : Boolean;
25
  procedure SetPhone(pho : String);
26
  procedure EncodeToGsmAlphabet(const ascii : String;out tmp : TByteArray);
27
  procedure Digest;
28
  function  PackPhoneNumber : String;
29
  function  AsciiToPdu(const ascii : String) : String;
30
  procedure SetSms(S : String);
31
 
32
 
33
  public
34
  constructor Create(const smsx : String; phonex : String);overload;
35
  constructor Create();
36
  destructor Destroy;override;
37
 
38
  procedure Send;
39
 
40
  procedure ConnectModem(const port : String; baud : Integer = 115200);
41
  procedure DisconnectModem;
42
 
43
  published
44
  property txtSMS : String read sms write SetSms;
45
  property txtPhone : String read phone write SetPhone;
46
  end;
47
 
48
implementation
49
 
50
procedure TSMS.Digest;
51
var
52
  tmp : String;
53
begin
54
    tmp := AsciiToPdu(sms);
55
    pdu_string:='001100' + IntToHex(phone_len,2) +'91' + PackPhoneNumber + '0000AA' + IntToHex((Length(sms)),2) + tmp ;
56
end;
57
 
58
destructor TSMS.Destroy;
59
begin
60
    DisconnectModem;
61
    inherited;
62
end;
63
 
64
procedure TSMS.DisconnectModem;
65
begin
66
    if connected then
67
    begin
68
      if Assigned(serial) then
69
      begin
70
      serial.CloseSocket;
71
      serial.Free;
72
      end;
73
      connected := false;
74
    end;
75
end;
76
 
77
procedure TSMS.ConnectModem(const port : String; baud : Integer = 115200);
78
begin
79
    serial := TBlockSerial.Create;
80
    serial.Config(baud,8,'N',1,false,true);
81
    serial.Connect(port);
82
    serial.ATCommand('AT');

 Delphi |  copy code |? 
1
&nbsp; &nbsp; &nbsp;Sleep(100); // I am not a fan of hardcoded sleep but it takes a while until the modem responds

 Delphi |  copy code |? 
001
   <!--DVFMTSC-->connected := serial.ATResult;
002
    if not connected then
003
    begin
004
    serial.Free;
005
    raise ESMSException.Create('Modem is not responding!');
006
    end;
007
end;
008
 
009
procedure TSMS.SetSms(S : String);
010
begin
011
    if Length(S) > 160 then raise ESMSException.Create('Message is to large!');
012
    sms := S;
013
end;
014
 
015
function PackBytes(a,b : Byte) : Byte;
016
begin
017
    Result := (b shl 4) or a;
018
end;
019
 
020
procedure TSms.Send;
021
begin
022
    if connected then
023
    begin
024
    Digest;
025
    serial.ATCommand('AT+CMGF=0');
026
    serial.ATCommand('AT+CMGS=' + IntToStr(Length(pdu_string) div 2 - 1));
027
    serial.SendString(pdu_string + #$1A);
028
    end
029
    else raise ESMSException.Create('No modem connected!');
030
end;
031
 
032
function TSms.PackPhoneNumber() : String;
033
var
034
  i : Integer;
035
begin
036
  Result := '';
037
  for i := 1 to (Length(phone) div 2)  do
038
      Result := Result + IntToHex(PackBytes(StrToInt('$'  + phone[(i * 2) - 1]),StrToInt('$' + phone[(i * 2)])),2);
039
end;
040
 
041
procedure TSMS.EncodeToGsmAlphabet(const ascii : String;out tmp : TByteArray);
042
var
043
  i : Integer;
044
  j : Byte;
045
const
046
  gsm7Bit: array [0 .. 127] of Byte = (64,163,36,165,232,223,249,236,242,199,10,216,248,13,197,229,0,95,0,0,0,0,0,0,0,0,0,0,198,230,223,201,32,33,34,35,164,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,161,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,196,204,209,220,167,191,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,228,246,241,252,224);
047
begin
048
  SetLength(tmp,0);
049
  for i := 1 to Length(ascii) do
050
  begin
051
      for j := 0 to 127 do
052
          if (gsm7Bit[j] = Ord(ascii[i])) then
053
          begin
054
            SetLength(tmp,Length(tmp) + 1);
055
            tmp[High(tmp)] := j;
056
            break;
057
          end;
058
  end;
059
end;
060
 
061
function ByteToBin(Value: Byte): string;
062
var
063
  i: Integer;
064
begin
065
  Result := '';
066
  for i := 6 downto 0 do
067
    if Value and (1 shl i) <> 0 then
068
      Result := Result + '1'
069
  else
070
    Result := Result + '0';
071
end;
072
 
073
function BinToInt(Value: string): Byte;
074
var
075
  i : Integer;
076
begin
077
  Result := 0;
078
  for i := 8 downto 1 do
079
    if Value[i] = '1' then Result := Result + (1 shl (8 - i));
080
end;
081
 
082
function TSMS.AsciiToPdu(const ascii : String) : String;
083
var
084
  bts : TByteArray;
085
  bin,tmp: string;
086
  total : TStringList;
087
  i,len : Integer;
088
begin
089
  Result := '';
090
  EncodeToGsmAlphabet(ascii,bts);
091
  total := TStringList.Create;
092
  for i:=Low(bts) to High(bts)do
093
  begin
094
    bin := ByteToBin(bts[i]);
095
    total.Add(bin);
096
  end;
097
  for i:=0 to total.Count -2  do
098
  begin
099
      len := 8 - Length(total[i]);
100
      if len = 8 then
101
      begin
102
          total[i] := '11111111';
103
          Continue;
104
      end;
105
      if len >0 then
106
      begin
107
      tmp := total[i+1];
108
      bin := Copy(tmp,Length(total[i + 1]) - len+1,len);
109
      tmp := total[i];
110
      Insert(bin,tmp,1);
111
      total[i] := tmp;
112
      bin := Copy(total[i+1],1,7 - len);
113
      total[i+1] := bin;
114
      end;
115
  end;
116
  for i := 0 to total.Count - 1 do
117
  begin
118
    tmp := total[i];
119
    if tmp = '' then Continue
120
    else if Length(tmp) < 8 then
121
      tmp := IntToHex(0,8-Length(tmp)) + tmp
122
    else if (BinToInt(tmp) > 254) then Continue;
123
    Result := Result + IntToHex(BinToInt(tmp),2);
124
  end;
125
  total.Free;
126
end;
127
 
128
procedure TSMS.SetPhone(pho : String);
129
begin
130
    if not (IsNumeric(pho)) then raise ESMSException.Create('Invalid phone number. Must be in international format eg 40741966242');
131
    phone_len:= Length(pho);
132
    if odd(Length(pho)) then
133
    phone := pho + 'F'
134
    else
135
    phone := pho;
136
end;
137
 
138
function TSMS.IsNumeric(const S: String) : Boolean;
139
var
140
  c : Char;
141
begin
142
    Result := True;
143
    for c in S do
144
        if not (c in ['0'..'9']) then
145
        begin
146
          Result := False;
147
          break;
148
        end;
149
end;
150
 
151
constructor TSMS.Create(const smsx : String; phonex : String);
152
begin
153
    inherited Create;
154
 
155
    SetPhone(phonex);
156
    SetSms(smsx);
157
end;
158
 
159
constructor TSMS.Create;
160
begin
161
    inherited Create;
162
end;
163
 
164
end.
165

Send message impersonating as any facebook user

I know the difference between a feature and and a vulnerability but Facebook has a vulfeature as I like to call it :) . Yesterday a friend told me to mail him on facebook , I didn’t knew that facebook supports mail so I said I must check this feature myself.

Said and done. I have used my email to send a message to myself and it worked fine. So I said to try the oldest and one of the first things I have learned : Send mail with SMTP with other sender.And guess what? It worked.

I installed ssmtp ( hope you are using some Debian linux  ):

sudo apt-get install ssmtp

After that I configured it using 

sudo nano /etc/ssmtp/ssmtp.conf

A sample configuration file :

 Bash |  copy code |? 
01
root=yourmail@somedomain.com
02
 
03
mailhub=smtp.yourserver.com:25
04
 
05
 
06
# Where will the mail seem to come from?
07
rewriteDomain=somedomain.com
08
 
09
# The full hostname
10
hostname=MyMediaServer.home
11
 
12
FromLineOverride=YES

I used as smtp server my office’s smtp server :) . Note that some providers such as RDS-RCS if you are from Romania, block the port 25 so you got to use either their owns in this case smtp.rdslink.ro or an outside source.

After you are done with the setup try sending me a hello by typing

ssmtp vtavi@facebook.com 

hello

Press CTRL + D to send mail

Of course you can do that with any smtp mailer :D .That’s it you can put any user’s e-mail address in the conf file and the message will appear as it was sent from that person. Of course facebook has prevented sharing links to prevent pishing and the message appears with a small exclamation mark if the domain of the sender does not match the smtp’s server. But 90% percent of people when it comes to computer security are pretty ignorant and I think a spear pishing campaign using wierd links to escape from facebook’s verification would work tremendously.

Here is how a spoofed message looks like , if the user has a custom e-mail address (not on a public mail provider) the exclamation mark will not bother to show.

Here is how a spoofed message looks like :

spoofed message

spoofed message

Happy spoofing! :P

The mighty Tor

The Tor network has always fascinated me is the ultimate trend in terms of privacy.You all heard of private VPN’s like cyberghost , hidemyass etc, my advice : don’t trust them! If you have read the recent ( last year) headlines you probably read about a annonymous member LulzSec was arrested in UK and guess what ? He was using hidemyass VPN :) .

If I have discovered Tor network way early in my life maybe it would saved me for a lot of problems :) .The only downside I can think off is very slow depending on the node you are connected at a certain time.

Recently I was asked by the bosses ( What would life be without them ? Great! :D ) to design a simple geo reversing tool for some partener . Basically what I must do is transform addresses into geo coordinates ( Latitude, Longitude ) from a CSV file. Said and done! To do this transformations you need a geodb engine I choose google is the best.  You make a http request containing the address and you get an xml response with the coordinates. I won’t get into details because that is not the purpose of this article.

But Google’s downside is that is limited for a number of requests per ip. Buying a license for that was not the bosses intention specialy this was a one time task. So it was for me to figure out a simple solution, and while thinking at it good old Tor popped to my head. I knew that you could request a new Identity so changing ip’s will be trivial one you know how to use it.

I done some fast research and came up with this unit that I hope you will find useful. I won’t tell you how to configure tor for this to work it if you don’t know that you shouldn’t be programming :P .

 Delphi |  copy code |? 
01
unit utoreq;
02
 
03
{$mode objfpc}{$H+}
04
 
05
//coded by opc0de (c) 2012
06
 
07
interface
08
 
09
uses
10
Classes, SysUtils,IdSocks, IdHTTP, IdIOHandlerStack,IdTCPClient;
11
 
12
function TorGet(const url : String) : String;
13
function GetNewIdentity() : Boolean;
14
 
15
type
16
ETorException = class(Exception);
17
 
18
const
19
host = '127.0.0.1';
20
port = 9050;
21
command_port = 9051;
22
 
23
implementation
24
 
25
function TorGet(const url : String) : String;
26
var
27
http : TIdHTTP;
28
socks : TIdSocksInfo;
29
stack : TIdIOHandlerStack;
30
begin
31
http := TIdHTTP.Create;
32
socks := TIdSocksInfo.Create;
33
stack := TIdIOHandlerStack.Create;
34
try
35
socks.Authentication:=saNoAuthentication;
36
socks.Host:=host;
37
socks.Port:=port;
38
socks.Version:=svSocks4A;
39
stack.TransparentProxy:=socks;
40
http.IOHandler := stack;
41
http.HandleRedirects:=true;
42
http.ReadTimeout:=50000; //Tor is pretty slow!
43
http.Request.Connection:='close';
44
Result := http.Get(url);
45
http.Free;
46
socks.Free;
47
stack.Free;
48
except
49
http.Free;
50
socks.Free;
51
stack.Free;
52
raise ETorException.Create('HTTP PROTOCOL FAILED.CHECK IF TOR IS OK!');
53
end;
54
end;
55
 
56
function GetNewIdentity() : Boolean;
57
var
58
tcp : TIdTcpClient;
59
begin
60
Result := False;
61
tcp := TIdTCPClient.Create();
62
try
63
tcp.Host := host;
64
tcp.Port := command_port;
65
tcp.Connect;
66
tcp.SendCmd('AUTHENTICATE ','');
67
if tcp.LastCmdResult.Code = '250' then
68
begin
69
tcp.SendCmd('signal NEWNYM','');
70
if tcp.LastCmdResult.Text[0] = 'OK' then
71
Result := True;
72
end;
73
tcp.Free;
74
except
75
raise ETorException.Create('Unable to talk to tor!');
76
tcp.Free;
77
end;
78
end;
79
 
80
end.

Do the GET request in a separate thread. Tor is real slow sometimes.

Good night!