예제 #1
0
def send_request(
    host,
    port,
    endpoint,
    method,
    token,
    data=None,
    cert=None,
    key=None,
    ca_cert=None,
    check_ocsp=True,
):
    def callback(conn, encoded_ocsp, data):
        ocsp_resp = load_der_ocsp_response(encoded_ocsp)
        return ocsp_resp.response_status == OCSPResponseStatus.SUCCESSFUL and ocsp_resp.certificate_status == OCSPCertStatus.GOOD

    context = Context(TLSv1_2_METHOD)
    context.load_client_ca(bytes(ca_cert, encoding="utf8"))
    context.use_certificate_file(cert)
    context.use_privatekey_file(key)
    context.set_ocsp_client_callback(callback)

    conn = Connection(context, socket.socket(socket.AF_INET,
                                             socket.SOCK_STREAM))
    conn.connect((host, port))
    if check_ocsp:
        conn.request_ocsp()
    conn.send(
        bytes(
            f"{method} {endpoint} HTTP/1.1\nHost: {host}:{port}\n" +
            f"Content-Type: text/plain\norigin: https://{host}:{port}\nToken: {token}\nContent-Length: {len(data)}\n\n{data}",
            encoding="utf8"))
    response = conn.read(2048)
    conn.close()
예제 #2
0
def printcert(host, port, hostname):
    con = Connection(Context(TLSv1_METHOD), socket(AF_INET, SOCK_STREAM))
    con.connect((host, port))
    con.set_tlsext_host_name(hostname if hostname else host)
    con.do_handshake()
    con.shutdown()
    con.close()
    print dump_certificate(FILETYPE_PEM, walkchain(con.get_peer_cert_chain()))
예제 #3
0
 def connect(self, *args, **kwargs):
     while True:
         try:
             _Connection.connect(self, *args, **kwargs)
             break
         except WantReadError:
             exc_clear()
             wait_read(self._sock.fileno(), timeout=self._timeout)
         except WantWriteError:
             exc_clear()
             wait_write(self._sock.fileno(), timeout=self._timeout)
예제 #4
0
 def connect(self, *args, **kwargs):
     while True:
         try:
             _Connection.connect(self, *args, **kwargs)
             break
         except WantReadError:
             exc_clear()
             wait_read(self._sock.fileno(), timeout=self._timeout)
         except WantWriteError:
             exc_clear()
             wait_write(self._sock.fileno(), timeout=self._timeout)
예제 #5
0
def main():
    def err_exit(ret, msg):
        ret['failed'] = True
        ret['msg'] = msg
        module.fail_json(**ret)

    module = AnsibleModule(argument_spec=dict(
        host=dict(required=True, type='str'),
        certificates=dict(required=True, type='dict'),
    ), )

    host = module.params['host']
    certificates = copy.copy(module.params['certificates'])
    split = host.split(':')
    split.reverse()
    host = split.pop()
    ret['host'] = host
    ret['port'] = None
    ret['downloaded'] = False
    ret['ansible_facts'] = dict(certificates=certificates)

    try:
        port = int(split.pop()) if split else 443
        hostport = "{}:{}".format(host, port)
        ret['port'] = port

        if host in certificates and hostport not in certificates:
            certificates[hostport] = certificates[host]

        if hostport not in certificates or certificates[hostport] is None:
            s = socket(AF_INET, SOCK_STREAM)
            ctx = Context(TLSv1_METHOD)
            con = Connection(ctx, s)
            con.connect((host, port))
            con.do_handshake()
            x509 = con.get_peer_cert_chain()[-1]
            con.shutdown()
            con.close()
            ret['downloaded'] = True
            certificates[hostport] = dump_certificate(FILETYPE_PEM, x509)
            if host not in certificates or certificates[host] is None:
                certificates[host] = certificates[hostport]

        module.exit_json(**ret)
    except Exception as e:
        msg_ = traceback.format_exc()
        module.fail_json(msg="{}: {}".format(repr(e), msg_))
예제 #6
0
class SocketClient(object):
    """This class sends all info to the server
    """

    cacertpath = "ca/cacert.pem"
    BUFF = 8192

    def __init__(self,HOST='130.236.219.232', PORT = 443):
        self.mutex = threading.Semaphore(1)
        self.connected = False
        self.connect()
        self.host_addr = HOST
        self.host_port = PORT

    def connect(self):
        print "You are trying to connect..."
        for x in range(7):
            if not self.connected:
                try:
                    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    context = Context(TLSv1_METHOD)
                    context.use_certificate_file(self.cacertpath)
                    context.set_timeout(2)
                    self.sslsocket = Connection(context,s)
                    self.sslsocket.connect((self.host_addr,self.host_port))
                    #starting a thread that listen to what server sends which the clients need to be able to send and recive data at the same time
                    t = threading.Thread(target=self.receive)
                    t.daemon = True
                    t.start()
                    if self.sslsocket:
                        self.connected = True
                    print "connection established"
                    #self.authentication("Kalle", "te")
                    t = threading.Thread(target=self.sendinput)
                    t.start()
                except socket.error:
                    print "You failed to connect, retrying......."
                    time.sleep(5)

    def authentication(self, username, password):
        self.sslsocket.send(username)
        self.sslsocket.send(password)

    #sending string to server
    def send(self,str):
        try:
            self.sslsocket.write("start")
            totalsent =  0
            while totalsent < str.__len__():
                sent = self.sslsocket.write(str[totalsent:])
                if sent == 0:
                    raise RuntimeError, "socket connection broken"
                totalsent = totalsent + sent
            self.sslsocket.write("end")
        except SSL.SysCallError:
            print "your server is dead, you have to resend data"
            self.connected = False
            self.sslsocket.shutdown()
            self.sslsocket.close()
            self.mutex.acquire()
            print "Du är inne i connect via send SysCallError"
            self.connect()
            self.mutex.release()
        except SSL.Error:
            self.connected = False
            self.mutex.acquire()
            print "Du är inne i connect via send ssl error"
            self.connect()
            self.mutex.release()

    #Sending input to server
    def sendinput(self):
        try:
            while True:
                input = raw_input()
                self.send(input)
        except KeyboardInterrupt:
            print "du är inne i sendinput"
            self.sslsocket.shutdown()
            self.sslsocket.close()
            exit(0)

    #getting data from server
    def receive(self):
        output = ""
        try:
            while True:
                data = self.sslsocket.recv(self.BUFF)
                if data == "start":
                    while True: 
                        data = self.sslsocket.recv(self.BUFF)
                        if data == "end":
                            print output
                            output = ""
                            break
                        output = output + data
        except SSL.SysCallError:
            print "OMG Server is down"
            self.connected = False
            print self.connected
            self.sslsocket.shutdown()
            self.sslsocket.close() 
            self.mutex.acquire()
            self.connect()
            self.mutex.release()
예제 #7
0
def index():
    form = ActionForm(request.form, csrf_context=session)

    if request.method == 'POST' and form.validate(
    ) and current_user.is_authenticated:
        comment_value = request.form['comment']
        action_value = request.form['action']
        user_name = current_user.username
        user_ip = get_client_ip()

        action_data = dict(comment=comment_value,
                           action=action_value,
                           user=user_name,
                           ip=user_ip)

        rx = ""

        try:
            print('Creating socket', file=sys.stderr)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            #s.settimeout(10.0)
            if repeater_listen_psk:
                ctx = Context(TLSv1_2_METHOD)
                ctx.set_cipher_list(b'PSK')
                ctx.set_psk_client_callback(client_callback)
                s = Connection(ctx, s)
                print('PSK Context created', file=sys.stderr)

            print('Connecting:', REPEATER_LISTENER)
            s.connect(REPEATER_LISTENER)
            print('Connected')

            try:
                hello_msg = s.recv(5)
                print(f'hello msg: {hello_msg}', file=sys.stderr)
            except socket.timeout:
                traceback.print_exc(file=sys.stderr)

            #send_delay = request.form.get('test_send_delay') or 0
            #sleep(int(send_delay))
            #if action_value == 'test_send':
            #    msg = comment_value.encode()
            #else:
            #    msg = json.dumps(action_data).encode()
            msg = json.dumps(action_data).encode()
            msg_len = len(msg)
            print(f'Sending {msg_len}b message: {msg}', file=sys.stderr)
            s.send(msg)
            #recv_delay = request.form.get('test_recv_delay') or 0
            #sleep(int(recv_delay))

            try:
                rx = s.recv(2)
            except ConnectionResetError:
                traceback.print_exc(file=sys.stderr)
                pass
            s.close()

            if len(rx) > 0:
                action_data['submitted'] = True
                action_data['submit_result'] = "Server reply: " + rx.decode()
            else:
                action_data['submitted'] = True
                action_data['submit_result'] = '<Unknown - no reply>'

        except Exception as e:
            traceback.print_exc(file=sys.stderr)
            action_data['submitted'] = False
            action_data[
                'submit_result'] = 'Unexpected error while sending: ' + str(e)

        ev = LogEvent.from_action(action_data, current_user)
        db.session.add(ev)
        db.session.commit()
    else:
        action_data = None

    connections = ''
    logs = []

    if current_user.is_authenticated:
        if os.path.exists(LISTENER_FILE):
            with open(LISTENER_FILE) as f:
                connections = f.read()
        else:
            connections = 'No file'

        logs = LogEvent.query.order_by(LogEvent.ts.desc()).limit(10).all()

    return render_template("index.html",
                           actions=REPEATER_ACTIONS,
                           form=form,
                           connections=connections,
                           logs=logs,
                           action=action_data)