예제 #1
0
def load_certificates():
    try:
        ca_f = open(ca_path, 'r')
    except Exception:
        print "ERROR: Could not open %s" % ca_path
        print "ca-bundle.crt file should be placed in ~/.electrum/ca/ca-bundle.crt"
        print "Documentation on how to download or create the file here: http://curl.haxx.se/docs/caextract.html"
        print "Payment will continue with manual verification."
        return False
    c = ""
    for line in ca_f:
        if line == "-----BEGIN CERTIFICATE-----\n":
            c = line
        else:
            c += line
        if line == "-----END CERTIFICATE-----\n":
            x = x509.X509()
            try:
                x.parse(c)
            except Exception as e:
                util.print_error("cannot parse cert:", e)
            ca_list[x.getFingerprint()] = x
    ca_f.close()
    util.print_error("%d certificates" % len(ca_list))
    return True
예제 #2
0
def verify_cert_chain(chain):
    """ Verify a chain of certificates. The last certificate is the CA"""
    load_ca_list()
    # parse the chain
    cert_num = len(chain)
    x509_chain = []
    for i in range(cert_num):
        x = x509.X509(bytearray(chain[i]))
        x509_chain.append(x)
        if i == 0:
            x.check_date()
        else:
            if not x.check_ca():
                raise BaseException("ERROR: Supplied CA Certificate Error")
    if not cert_num > 1:
        raise BaseException(
            "ERROR: CA Certificate Chain Not Provided by Payment Processor")
    # if the root CA is not supplied, add it to the chain
    ca = x509_chain[cert_num - 1]
    if ca.getFingerprint() not in ca_list:
        keyID = ca.get_issuer_keyID()
        f = ca_keyID.get(keyID)
        if f:
            root = ca_list[f]
            x509_chain.append(root)
        else:
            raise BaseException("Supplied CA Not Found in Trusted CA Store.")
    # verify the chain of signatures
    cert_num = len(x509_chain)
    for i in range(1, cert_num):
        x = x509_chain[i]
        prev_x = x509_chain[i - 1]
        algo, sig, data = prev_x.get_signature()
        sig = bytearray(sig)
        pubkey = rsakey.RSAKey(x.modulus, x.exponent)
        if algo == x509.ALGO_RSA_SHA1:
            verify = pubkey.hashAndVerify(sig, data)
        elif algo == x509.ALGO_RSA_SHA256:
            hashBytes = bytearray(hashlib.sha256(data).digest())
            verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA256 + hashBytes)
        elif algo == x509.ALGO_RSA_SHA384:
            hashBytes = bytearray(hashlib.sha384(data).digest())
            verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA384 + hashBytes)
        elif algo == x509.ALGO_RSA_SHA512:
            hashBytes = bytearray(hashlib.sha512(data).digest())
            verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA512 + hashBytes)
        else:
            raise BaseException("Algorithm not supported")
            util.print_error(self.error, algo.getComponentByName('algorithm'))
        if not verify:
            raise BaseException(
                "Certificate not Signed by Provided CA Certificate Chain")

    return x509_chain[0], ca
예제 #3
0
def check_cert(host, cert):
    try:
        b = pem.dePem(cert, 'CERTIFICATE')
        x = x509.X509(b)
    except:
        traceback.print_exc(file=sys.stdout)
        return

    try:
        x.check_date()
        expired = False
    except:
        expired = True

    m = "host: %s\n" % host
    m += "has_expired: %s\n" % expired
    util.print_msg(m)
예제 #4
0
def check_cert(host, cert):
    try:
        x = x509.X509()
        x.parse(cert)
    except:
        traceback.print_exc(file=sys.stdout)
        return

    try:
        x.check_date()
        expired = False
    except:
        expired = True

    m = "host: %s\n"%host
    m += "has_expired: %s\n"% expired
    util.print_msg(m)
예제 #5
0
                         do_handshake_on_connect=True)
 except ssl.SSLError, e:
     self.print_error("SSL error:", e)
     if e.errno != 1:
         return
     if is_new:
         rej = cert_path + '.rej'
         if os.path.exists(rej):
             os.unlink(rej)
         os.rename(temporary_path, rej)
     else:
         with open(cert_path) as f:
             cert = f.read()
         try:
             b = pem.dePem(cert, 'CERTIFICATE')
             x = x509.X509(b)
         except:
             traceback.print_exc(file=sys.stderr)
             self.print_error("wrong certificate")
             return
         try:
             x.check_date()
         except:
             self.print_error("certificate has expired:", cert_path)
             os.unlink(cert_path)
             return
         self.print_error("wrong certificate")
     return
 except BaseException, e:
     self.print_error(e)
     if e.errno == 104:
예제 #6
0
         ca_certs=(temporary_path if is_new else cert_path),
         do_handshake_on_connect=True)
 except ssl.SSLError, e:
     print_error("SSL error:", self.host, e)
     if e.errno != 1:
         return
     if is_new:
         rej = cert_path + '.rej'
         if os.path.exists(rej):
             os.unlink(rej)
         os.rename(temporary_path, rej)
     else:
         with open(cert_path) as f:
             cert = f.read()
         try:
             x = x509.X509()
             x.parse(cert)
             x.slow_parse()
         except:
             traceback.print_exc(file=sys.stderr)
             print_error("wrong certificate", self.host)
             return
         try:
             x.check_date()
         except:
             print_error("certificate has expired:", cert_path)
             os.unlink(cert_path)
             return
         print_error("wrong certificate", self.host)
     return
 except BaseException:
예제 #7
0
    def verify(self):

        if not ca_list:
            self.error = "Trusted certificate authorities list not found"
            return False

        paymntreq = self.data
        if not paymntreq.signature:
            self.error = "No signature"
            return

        cert = paymentrequest_pb2.X509Certificates()
        cert.ParseFromString(paymntreq.pki_data)
        cert_num = len(cert.certificate)

        x509_chain = []
        for i in range(cert_num):
            x = x509.X509()
            x.parseBinary(bytearray(cert.certificate[i]))
            x.slow_parse()
            x509_chain.append(x)
            if i == 0:
                try:
                    x.check_date()
                    x.check_name(self.domain)
                except Exception as e:
                    self.error = str(e)
                    return
            else:
                if not x.check_ca():
                    self.error = "ERROR: Supplied CA Certificate Error"
                    return

        if not cert_num > 1:
            self.error = "ERROR: CA Certificate Chain Not Provided by Payment Processor"
            return False

        for i in range(1, cert_num):
            x = x509_chain[i]
            prev_x = x509_chain[i - 1]

            algo, sig, data = prev_x.extract_sig()
            sig = bytearray(sig[5:])
            pubkey = x.publicKey
            if algo.getComponentByName('algorithm') == x509.ALGO_RSA_SHA1:
                verify = pubkey.hashAndVerify(sig, data)
            elif algo.getComponentByName('algorithm') == x509.ALGO_RSA_SHA256:
                hashBytes = bytearray(hashlib.sha256(data).digest())
                prefixBytes = bytearray([
                    0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
                    0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20
                ])
                verify = pubkey.verify(sig, prefixBytes + hashBytes)
            else:
                self.error = "Algorithm not supported"
                util.print_error(self.error,
                                 algo.getComponentByName('algorithm'))
                return

            if not verify:
                self.error = "Certificate not Signed by Provided CA Certificate Chain"
                return

        ca = x509_chain[cert_num - 1]
        supplied_CA_fingerprint = ca.getFingerprint()
        supplied_CA_names = ca.extract_names()
        CA_OU = supplied_CA_names['OU']

        x = ca_list.get(supplied_CA_fingerprint)
        if x:
            x.slow_parse()
            names = x.extract_names()
            CA_match = True
            if names['CN'] != supplied_CA_names['CN']:
                print "ERROR: Trusted CA CN Mismatch; however CA has trusted fingerprint"
                print "Payment will continue with manual verification."
        else:
            CA_match = False

        pubkey0 = x509_chain[0].publicKey
        sig = paymntreq.signature
        paymntreq.signature = ''
        s = paymntreq.SerializeToString()
        sigBytes = bytearray(sig)
        msgBytes = bytearray(s)

        if paymntreq.pki_type == "x509+sha256":
            hashBytes = bytearray(hashlib.sha256(msgBytes).digest())
            prefixBytes = bytearray([
                0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
                0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20
            ])
            verify = pubkey0.verify(sigBytes, prefixBytes + hashBytes)
        elif paymntreq.pki_type == "x509+sha1":
            verify = pubkey0.hashAndVerify(sigBytes, msgBytes)
        else:
            self.error = "ERROR: Unsupported PKI Type for Message Signature"
            return False

        if not verify:
            self.error = "ERROR: Invalid Signature for Payment Request Data"
            return False

        ### SIG Verified
        self.details = pay_det = paymentrequest_pb2.PaymentDetails()
        self.details.ParseFromString(paymntreq.serialized_payment_details)

        for o in pay_det.outputs:
            addr = transaction.get_address_from_output_script(o.script)[1]
            self.outputs.append(('address', addr, o.amount))

        self.memo = self.details.memo

        if CA_match:
            self.status = 'Signed by Trusted CA:\n' + CA_OU
        else:
            self.status = "Supplied CA Not Found in Trusted CA Store."

        self.payment_url = self.details.payment_url

        return True
 def verify(self):
     if not ca_list:
         self.error = "Trusted certificate authorities list not found"
         return False
     paymntreq = pb2.PaymentRequest()
     paymntreq.ParseFromString(self.raw)
     if not paymntreq.signature:
         self.error = "No signature"
         return
     cert = pb2.X509Certificates()
     cert.ParseFromString(paymntreq.pki_data)
     cert_num = len(cert.certificate)
     x509_chain = []
     for i in range(cert_num):
         x = x509.X509()
         x.parseBinary(bytearray(cert.certificate[i]))
         x509_chain.append(x)
         if i == 0:
             try:
                 x.check_date()
             except Exception as e:
                 self.error = str(e)
                 return
             self.requestor = x.get_common_name()
             if self.requestor.startswith('*.'):
                 self.requestor = self.requestor[2:]
         else:
             if not x.check_ca():
                 self.error = "ERROR: Supplied CA Certificate Error"
                 return
     if not cert_num > 1:
         self.error = "ERROR: CA Certificate Chain Not Provided by Payment Processor"
         return False
     # if the root CA is not supplied, add it to the chain
     ca = x509_chain[cert_num - 1]
     if ca.getFingerprint() not in ca_list:
         keyID = ca.get_issuer_keyID()
         f = ca_keyID.get(keyID)
         if f:
             root = ca_list[f]
             x509_chain.append(root)
         else:
             self.error = "Supplied CA Not Found in Trusted CA Store."
             return False
     # verify the chain of signatures
     cert_num = len(x509_chain)
     for i in range(1, cert_num):
         x = x509_chain[i]
         prev_x = x509_chain[i - 1]
         algo, sig, data = prev_x.get_signature()
         sig = bytearray(sig)
         pubkey = x.publicKey
         if algo == x509.ALGO_RSA_SHA1:
             verify = pubkey.hashAndVerify(sig, data)
         elif algo == x509.ALGO_RSA_SHA256:
             hashBytes = bytearray(hashlib.sha256(data).digest())
             verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA256 + hashBytes)
         elif algo == x509.ALGO_RSA_SHA384:
             hashBytes = bytearray(hashlib.sha384(data).digest())
             verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA384 + hashBytes)
         elif algo == x509.ALGO_RSA_SHA512:
             hashBytes = bytearray(hashlib.sha512(data).digest())
             verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA512 + hashBytes)
         else:
             self.error = "Algorithm not supported"
             util.print_error(self.error,
                              algo.getComponentByName('algorithm'))
             return False
         if not verify:
             self.error = "Certificate not Signed by Provided CA Certificate Chain"
             return False
     # verify the BIP70 signature
     pubkey0 = x509_chain[0].publicKey
     sig = paymntreq.signature
     paymntreq.signature = ''
     s = paymntreq.SerializeToString()
     sigBytes = bytearray(sig)
     msgBytes = bytearray(s)
     if paymntreq.pki_type == "x509+sha256":
         hashBytes = bytearray(hashlib.sha256(msgBytes).digest())
         verify = pubkey0.verify(sigBytes,
                                 x509.PREFIX_RSA_SHA256 + hashBytes)
     elif paymntreq.pki_type == "x509+sha1":
         verify = pubkey0.hashAndVerify(sigBytes, msgBytes)
     else:
         self.error = "ERROR: Unsupported PKI Type for Message Signature"
         return False
     if not verify:
         self.error = "ERROR: Invalid Signature for Payment Request Data"
         return False
     ### SIG Verified
     self.error = 'Signed by Trusted CA: ' + ca.get_common_name()
     return True
예제 #9
0
    def get_socket(self):
        if self.use_ssl:
            cert_path = os.path.join(self.config_path, 'certs', self.host)
            if not os.path.exists(cert_path):
                is_new = True
                s = self.get_simple_socket()
                if s is None:
                    return
                # try with CA first
                try:
                    context = self.get_ssl_context(cert_reqs=ssl.CERT_REQUIRED,
                                                   ca_certs=ca_path)
                    s = context.wrap_socket(s, do_handshake_on_connect=True)
                except ssl.SSLError as e:
                    self.print_error(e)
                except:
                    return
                else:
                    try:
                        peer_cert = s.getpeercert()
                    except OSError:
                        return
                    if self.check_host_name(peer_cert, self.host):
                        self.print_error("SSL certificate signed by CA")
                        return s
                # get server certificate.
                # Do not use ssl.get_server_certificate because it does not work with proxy
                s = self.get_simple_socket()
                if s is None:
                    return
                try:
                    context = self.get_ssl_context(cert_reqs=ssl.CERT_NONE,
                                                   ca_certs=None)
                    s = context.wrap_socket(s)
                except ssl.SSLError as e:
                    self.print_error("SSL error retrieving SSL certificate:",
                                     e)
                    return
                except:
                    return

                try:
                    dercert = s.getpeercert(True)
                except OSError:
                    return
                s.close()
                cert = ssl.DER_cert_to_PEM_cert(dercert)
                # workaround android bug
                cert = re.sub("([^\n])-----END CERTIFICATE-----",
                              "\\1\n-----END CERTIFICATE-----", cert)
                temporary_path = cert_path + '.temp'
                util.assert_datadir_available(self.config_path)
                with open(temporary_path, "w", encoding='utf-8') as f:
                    f.write(cert)
                    f.flush()
                    os.fsync(f.fileno())
            else:
                is_new = False

        s = self.get_simple_socket()
        if s is None:
            return

        if self.use_ssl:
            try:
                context = self.get_ssl_context(
                    cert_reqs=ssl.CERT_REQUIRED,
                    ca_certs=(temporary_path if is_new else cert_path))
                s = context.wrap_socket(s, do_handshake_on_connect=True)
            except socket.timeout:
                self.print_error('timeout')
                return
            except ssl.SSLError as e:
                self.print_error("SSL error:", e)
                if e.errno != 1:
                    return
                if is_new:
                    rej = cert_path + '.rej'
                    if os.path.exists(rej):
                        os.unlink(rej)
                    os.rename(temporary_path, rej)
                else:
                    util.assert_datadir_available(self.config_path)
                    with open(cert_path, encoding='utf-8') as f:
                        cert = f.read()
                    try:
                        b = pem.dePem(cert, 'CERTIFICATE')
                        x = x509.X509(b)
                    except:
                        traceback.print_exc(file=sys.stderr)
                        self.print_error("wrong certificate")
                        return
                    try:
                        x.check_date()
                    except:
                        self.print_error("certificate has expired:", cert_path)
                        os.unlink(cert_path)
                        return
                    self.print_error("wrong certificate")
                if e.errno == 104:
                    return
                return
            except BaseException as e:
                self.print_error(e)
                traceback.print_exc(file=sys.stderr)
                return

            if is_new:
                self.print_error("saving certificate")
                os.rename(temporary_path, cert_path)

        return s
예제 #10
0
class Interface(threading.Thread):
    def __init__(self, server, config=None):

        threading.Thread.__init__(self)
        self.daemon = True
        self.config = config if config is not None else SimpleConfig()
        self.connect_event = threading.Event()

        self.subscriptions = {}
        self.lock = threading.Lock()

        self.rtime = 0
        self.bytes_received = 0
        self.is_connected = False
        self.poll_interval = 1

        self.debug = False  # dump network messages. can be changed at runtime using the console

        #json
        self.message_id = 0
        self.unanswered_requests = {}

        # parse server
        self.server = server
        try:
            host, port, protocol = self.server.split(':')
            port = int(port)
        except Exception:
            self.server = None
            return

        if protocol not in 'ghst':
            raise Exception('Unknown protocol: %s' % protocol)

        self.host = host
        self.port = port
        self.protocol = protocol
        self.use_ssl = (protocol in 'sg')
        self.proxy = self.parse_proxy_options(self.config.get('proxy'))
        if self.proxy:
            self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1

    def queue_json_response(self, c):

        # uncomment to debug
        if self.debug:
            print_error("<--", c)

        msg_id = c.get('id')
        error = c.get('error')

        if error:
            print_error("received error:", c)
            if msg_id is not None:
                with self.lock:
                    method, params, callback = self.unanswered_requests.pop(
                        msg_id)
                callback(
                    self, {
                        'method': method,
                        'params': params,
                        'error': error,
                        'id': msg_id
                    })

            return

        if msg_id is not None:
            with self.lock:
                method, params, callback = self.unanswered_requests.pop(msg_id)
            result = c.get('result')

        else:
            # notification
            method = c.get('method')
            params = c.get('params')

            if method == 'blockchain.numblocks.subscribe':
                result = params[0]
                params = []

            elif method == 'blockchain.headers.subscribe':
                result = params[0]
                params = []

            elif method == 'blockchain.address.subscribe':
                addr = params[0]
                result = params[1]
                params = [addr]

            with self.lock:
                for k, v in self.subscriptions.items():
                    if (method, params) in v:
                        callback = k
                        break
                else:
                    print_error("received unexpected notification", method,
                                params)
                    print_error(self.subscriptions)
                    return

        callback(self, {
            'method': method,
            'params': params,
            'result': result,
            'id': msg_id
        })

    def on_version(self, i, result):
        self.server_version = result

    def start_http(self):
        self.session_id = None
        self.is_connected = True
        self.connection_msg = ('https' if self.use_ssl else
                               'http') + '://%s:%d' % (self.host, self.port)
        try:
            self.poll()
        except Exception:
            print_error("http init session failed")
            self.is_connected = False
            return

        if self.session_id:
            print_error('http session:', self.session_id)
            self.is_connected = True
        else:
            self.is_connected = False

    def run_http(self):
        self.is_connected = True
        while self.is_connected:
            try:
                if self.session_id:
                    self.poll()
                time.sleep(self.poll_interval)
            except socket.gaierror:
                break
            except socket.error:
                break
            except Exception:
                traceback.print_exc(file=sys.stdout)
                break

        self.is_connected = False

    def poll(self):
        self.send([], None)

    def send_http(self, messages, callback):
        import urllib2, json, time, cookielib
        print_error("send_http", messages)

        if self.proxy:
            socks.setdefaultproxy(self.proxy_mode, self.proxy["host"],
                                  int(self.proxy["port"]))
            socks.wrapmodule(urllib2)

        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        urllib2.install_opener(opener)

        t1 = time.time()

        data = []
        ids = []
        for m in messages:
            method, params = m
            if type(params) != type([]): params = [params]
            data.append({
                'method': method,
                'id': self.message_id,
                'params': params
            })
            self.unanswered_requests[
                self.message_id] = method, params, callback
            ids.append(self.message_id)
            self.message_id += 1

        if data:
            data_json = json.dumps(data)
        else:
            # poll with GET
            data_json = None

        headers = {'content-type': 'application/json'}
        if self.session_id:
            headers['cookie'] = 'SESSION=%s' % self.session_id

        try:
            req = urllib2.Request(self.connection_msg, data_json, headers)
            response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
        except Exception:
            return

        for index, cookie in enumerate(cj):
            if cookie.name == 'SESSION':
                self.session_id = cookie.value

        response = response_stream.read()
        self.bytes_received += len(response)
        if response:
            response = json.loads(response)
            if type(response) is not type([]):
                self.queue_json_response(response)
            else:
                for item in response:
                    self.queue_json_response(item)

        if response:
            self.poll_interval = 1
        else:
            if self.poll_interval < 15:
                self.poll_interval += 1
        #print self.poll_interval, response

        self.rtime = time.time() - t1
        self.is_connected = True
        return ids

    def start_tcp(self):

        self.connection_msg = self.host + ':%d' % self.port

        if self.proxy is not None:

            socks.setdefaultproxy(self.proxy_mode, self.proxy["host"],
                                  int(self.proxy["port"]))
            socket.socket = socks.socksocket

            # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
            def getaddrinfo(*args):
                return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0],
                                                                     args[1]))]

            socket.getaddrinfo = getaddrinfo

        if self.use_ssl:
            cert_path = os.path.join(self.config.path, 'certs', self.host)

            if not os.path.exists(cert_path):
                is_new = True
                # get server certificate.
                # Do not use ssl.get_server_certificate because it does not work with proxy
                try:
                    l = socket.getaddrinfo(self.host, self.port,
                                           socket.AF_UNSPEC,
                                           socket.SOCK_STREAM)
                except socket.gaierror:
                    print_error("error: cannot resolve", self.host)
                    return

                for res in l:
                    try:
                        s = socket.socket(res[0], socket.SOCK_STREAM)
                        s.connect(res[4])
                    except:
                        s = None
                        continue

                    try:
                        s = ssl.wrap_socket(s,
                                            ssl_version=ssl.PROTOCOL_SSLv3,
                                            cert_reqs=ssl.CERT_NONE,
                                            ca_certs=None)
                    except ssl.SSLError, e:
                        print_error("SSL error retrieving SSL certificate:",
                                    self.host, e)
                        s = None

                    break

                if s is None:
                    return

                dercert = s.getpeercert(True)
                s.close()
                cert = ssl.DER_cert_to_PEM_cert(dercert)
                # workaround android bug
                cert = re.sub("([^\n])-----END CERTIFICATE-----",
                              "\\1\n-----END CERTIFICATE-----", cert)
                temporary_path = cert_path + '.temp'
                with open(temporary_path, "w") as f:
                    f.write(cert)

            else:
                is_new = False

        try:
            addrinfo = socket.getaddrinfo(self.host, self.port,
                                          socket.AF_UNSPEC, socket.SOCK_STREAM)
        except socket.gaierror:
            print_error("error: cannot resolve", self.host)
            return

        for res in addrinfo:
            try:
                s = socket.socket(res[0], socket.SOCK_STREAM)
                s.settimeout(2)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                s.connect(res[4])
            except:
                s = None
                continue
            break

        if s is None:
            print_error("failed to connect", self.host, self.port)
            return

        if self.use_ssl:
            try:
                s = ssl.wrap_socket(
                    s,
                    ssl_version=ssl.PROTOCOL_SSLv3,
                    cert_reqs=ssl.CERT_REQUIRED,
                    ca_certs=(temporary_path if is_new else cert_path),
                    do_handshake_on_connect=True)
            except ssl.SSLError, e:
                print_error("SSL error:", self.host, e)
                if e.errno != 1:
                    return
                if is_new:
                    rej = cert_path + '.rej'
                    if os.path.exists(rej):
                        os.unlink(rej)
                    os.rename(temporary_path, rej)
                else:
                    with open(cert_path) as f:
                        cert = f.read()
                    try:
                        x = x509.X509()
                        x.parse(cert)
                        x.slow_parse()
                    except:
                        traceback.print_exc(file=sys.stdout)
                        print_error("wrong certificate", self.host)
                        return
                    try:
                        x.check_date()
                    except:
                        print_error("certificate has expired:", cert_path)
                        os.unlink(cert_path)
                        return
                    print_error("wrong certificate", self.host)
                return
            except Exception:
                print_error("wrap_socket failed", self.host)
                traceback.print_exc(file=sys.stdout)
                return
예제 #11
0
class TcpInterface(threading.Thread):
    def __init__(self, server, config=None):
        threading.Thread.__init__(self)
        self.daemon = True
        self.config = config if config is not None else SimpleConfig()
        self.lock = threading.Lock()

        self.is_connected = False
        self.debug = False  # dump network messages. can be changed at runtime using the console
        self.message_id = 0
        self.unanswered_requests = {}

        # are we waiting for a pong?
        self.is_ping = False

        # parse server
        self.server = server
        self.host, self.port, self.protocol = self.server.split(':')
        self.port = int(self.port)
        self.use_ssl = (self.protocol == 's')
        self.proxy = self.parse_proxy_options(self.config.get('proxy'))
        if self.proxy:
            self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1

    def process_response(self, response):
        if self.debug:
            print_error("<--", response)

        msg_id = response.get('id')
        error = response.get('error')
        result = response.get('result')

        if error:
            print_error("received error:", response)
            return

        if msg_id is not None:
            with self.lock:
                method, params, _id, queue = self.unanswered_requests.pop(
                    msg_id)
            if queue is None:
                queue = self.response_queue
        else:
            # notification
            method = response.get('method')
            params = response.get('params')
            _id = None
            queue = self.response_queue
            # restore parameters
            if method == 'blockchain.numblocks.subscribe':
                result = params[0]
                params = []
            elif method == 'blockchain.headers.subscribe':
                result = params[0]
                params = []
            elif method == 'blockchain.address.subscribe':
                addr = params[0]
                result = params[1]
                params = [addr]

        if method == 'server.version':
            self.server_version = result
            self.is_ping = False
            return

        queue.put((self, {
            'method': method,
            'params': params,
            'result': result,
            'id': _id
        }))

    def start_tcp(self):

        if self.proxy is not None:
            socks.setdefaultproxy(self.proxy_mode, self.proxy["host"],
                                  int(self.proxy["port"]))
            socket.socket = socks.socksocket

            # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
            def getaddrinfo(*args):
                return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0],
                                                                     args[1]))]

            socket.getaddrinfo = getaddrinfo

        if self.use_ssl:
            cert_path = os.path.join(self.config.path, 'certs', self.host)
            if not os.path.exists(cert_path):
                is_new = True
                # get server certificate.
                # Do not use ssl.get_server_certificate because it does not work with proxy
                try:
                    l = socket.getaddrinfo(self.host, self.port,
                                           socket.AF_UNSPEC,
                                           socket.SOCK_STREAM)
                except socket.gaierror:
                    print_error("error: cannot resolve", self.host)
                    return

                for res in l:
                    try:
                        s = socket.socket(res[0], socket.SOCK_STREAM)
                        s.connect(res[4])
                    except:
                        s = None
                        continue

                    try:
                        s = ssl.wrap_socket(s,
                                            ssl_version=ssl.PROTOCOL_SSLv3,
                                            cert_reqs=ssl.CERT_NONE,
                                            ca_certs=None)
                    except ssl.SSLError, e:
                        print_error("SSL error retrieving SSL certificate:",
                                    self.host, e)
                        s = None

                    break

                if s is None:
                    return

                dercert = s.getpeercert(True)
                s.close()
                cert = ssl.DER_cert_to_PEM_cert(dercert)
                # workaround android bug
                cert = re.sub("([^\n])-----END CERTIFICATE-----",
                              "\\1\n-----END CERTIFICATE-----", cert)
                temporary_path = cert_path + '.temp'
                with open(temporary_path, "w") as f:
                    f.write(cert)

            else:
                is_new = False

        try:
            addrinfo = socket.getaddrinfo(self.host, self.port,
                                          socket.AF_UNSPEC, socket.SOCK_STREAM)
        except socket.gaierror:
            print_error("error: cannot resolve", self.host)
            return

        for res in addrinfo:
            try:
                s = socket.socket(res[0], socket.SOCK_STREAM)
                s.settimeout(2)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                s.connect(res[4])
            except:
                s = None
                continue
            break

        if s is None:
            print_error("failed to connect", self.host, self.port)
            return

        if self.use_ssl:
            try:
                s = ssl.wrap_socket(
                    s,
                    ssl_version=ssl.PROTOCOL_SSLv3,
                    cert_reqs=ssl.CERT_REQUIRED,
                    ca_certs=(temporary_path if is_new else cert_path),
                    do_handshake_on_connect=True)
            except ssl.SSLError, e:
                print_error("SSL error:", self.host, e)
                if e.errno != 1:
                    return
                if is_new:
                    rej = cert_path + '.rej'
                    if os.path.exists(rej):
                        os.unlink(rej)
                    os.rename(temporary_path, rej)
                else:
                    with open(cert_path) as f:
                        cert = f.read()
                    try:
                        x = x509.X509()
                        x.parse(cert)
                        x.slow_parse()
                    except:
                        traceback.print_exc(file=sys.stderr)
                        print_error("wrong certificate", self.host)
                        return
                    try:
                        x.check_date()
                    except:
                        print_error("certificate has expired:", cert_path)
                        os.unlink(cert_path)
                        return
                    print_error("wrong certificate", self.host)
                return
            except Exception:
                print_error("wrap_socket failed", self.host)
                traceback.print_exc(file=sys.stderr)
                return