# along with this program. If not, see <http://www.gnu.org/licenses/>.
-import random, socket, ast, re, ssl, errno, os
+import random, ast, re, errno, os
import threading, traceback, sys, time, json, Queue
import socks
+import socket
+import ssl
from version import ELECTRUM_VERSION, PROTOCOL_VERSION
from util import print_error, print_msg
+from simple_config import SimpleConfig
DEFAULT_TIMEOUT = 5
proxy_modes = ['socks4', 'socks5', 'http']
-class Interface(threading.Thread):
+def check_cert(host, cert):
+ from OpenSSL import crypto as c
+ _cert = c.load_certificate(c.FILETYPE_PEM, cert)
+
+ m = "host: %s\n"%host
+ m += "has_expired: %s\n"% _cert.has_expired()
+ m += "pubkey: %s bits\n" % _cert.get_pubkey().bits()
+ m += "serial number: %s\n"% _cert.get_serial_number()
+ #m += "issuer: %s\n"% _cert.get_issuer()
+ #m += "algo: %s\n"% _cert.get_signature_algorithm()
+ m += "version: %s\n"% _cert.get_version()
+ print_msg(m)
+
+
+def cert_has_expired(cert_path):
+ try:
+ import OpenSSL
+ except:
+ print_error("Warning: cannot import OpenSSL")
+ return False
+ from OpenSSL import crypto as c
+ with open(cert_path) as f:
+ cert = f.read()
+ _cert = c.load_certificate(c.FILETYPE_PEM, cert)
+ return _cert.has_expired()
+
+
+def check_certificates():
+ config = SimpleConfig()
+ mydir = os.path.join(config.path, "certs")
+ certs = os.listdir(mydir)
+ for c in certs:
+ print c
+ p = os.path.join(mydir,c)
+ with open(p) as f:
+ cert = f.read()
+ check_cert(c, cert)
+
+
+def cert_verify_hostname(s):
+ # hostname verification (disabled)
+ from backports.ssl_match_hostname import match_hostname, CertificateError
+ try:
+ match_hostname(s.getpeercert(True), host)
+ print_error("hostname matches", host)
+ except CertificateError, ce:
+ print_error("hostname did not match", host)
+
- def __init__(self, config=None):
+class Interface(threading.Thread):
+
- if config is None:
- from simple_config import SimpleConfig
- config = SimpleConfig()
+ def __init__(self, server, config = None):
threading.Thread.__init__(self)
self.daemon = True
- self.config = config
+ self.config = config if config is not None else SimpleConfig()
self.connect_event = threading.Event()
self.subscriptions = {}
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 = {}
self.pending_transactions_for_notifications= []
# parse server
- s = config.get('server')
- host, port, protocol = s.split(':')
+ self.server = server
+ host, port, protocol = self.server.split(':')
port = int(port)
+
if protocol not in 'ghst':
raise BaseException('Unknown protocol: %s'%protocol)
self.port = port
self.protocol = protocol
self.use_ssl = ( protocol in 'sg' )
- self.proxy = self.parse_proxy_options(config.get('proxy'))
- self.server = host + ':%d:%s'%(port, protocol)
+ 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
- # print_error( "<--",c )
+ if self.debug:
+ print_error( "<--",c )
msg_id = c.get('id')
error = c.get('error')
self.server_version = result
- def init_http(self, host, port, proxy=None, use_ssl=True):
+ 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 )
def poll(self):
- self.send([])
+ self.send([], None)
def send_http(self, messages, callback):
print_error( "send_http", messages )
if self.proxy:
- socks.setdefaultproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
+ socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]) )
socks.wrapmodule(urllib2)
cj = cookielib.CookieJar()
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.get('path'), 'certs', self.host)
+ cert_path = os.path.join( self.config.path, 'certs', self.host)
+
if not os.path.exists(cert_path):
- dir_path = os.path.join( self.config.get('path'), 'certs')
- if not os.path.exists(dir_path):
- os.mkdir(dir_path)
+ is_new = True
+ # get server certificate.
+ # Do not use ssl.get_server_certificate because it does not work with proxy
+ s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
try:
- cert = ssl.get_server_certificate((self.host, self.port))
+ s.connect((self.host, self.port))
except:
- print_error("failed to connect", self.host, self.port)
+ # print_error("failed to connect", self.host, self.port)
return
-
- with open(cert_path,"w") as f:
- f.write(cert)
- self.connection_msg = "%s:%d"%(self.host, self.port)
+ 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:", self.host, e)
+ return
+ dercert = s.getpeercert(True)
+ s.close()
+ cert = ssl.DER_cert_to_PEM_cert(dercert)
+ temporary_path = cert_path + '.temp'
+ with open(temporary_path,"w") as f:
+ f.write(cert)
+ else:
+ is_new = False
- if self.proxy is None:
- s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
- else:
- self.connection_msg += " using proxy %s:%s:%s"%(self.proxy.get('mode'), self.proxy.get('host'), self.proxy.get('port'))
- s = socks.socksocket()
- s.setproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
+ s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.settimeout(2)
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s = ssl.wrap_socket(s,
ssl_version=ssl.PROTOCOL_SSLv3,
cert_reqs=ssl.CERT_REQUIRED,
- ca_certs=cert_path,
+ 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:
+ os.rename(temporary_path, cert_path + '.rej')
+ else:
+ if cert_has_expired(cert_path):
+ print_error("certificate has expired:", cert_path)
+ os.unlink(cert_path)
+ else:
+ print_msg("wrong certificate", self.host)
return
except:
- traceback.print_exc(file=sys.stdout)
print_error("wrap_socket failed", self.host)
+ traceback.print_exc(file=sys.stdout)
return
- # hostname verification (disabled)
- if self.use_ssl and False:
- from backports.ssl_match_hostname import match_hostname, CertificateError
- try:
- match_hostname(s.getpeercert(), self.host)
- print_error("hostname matches", self.host)
- except CertificateError, ce:
- print_error("hostname does not match", self.host, s.getpeercert())
- return
+ if is_new:
+ print_error("saving certificate for", self.host)
+ os.rename(temporary_path, cert_path)
s.settimeout(60)
self.s = s
request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } )
self.unanswered_requests[self.message_id] = method, params, callback
ids.append(self.message_id)
- # uncomment to debug
- # print "-->", request
+ if self.debug:
+ print "-->", request
self.message_id += 1
out += request + '\n'
while out:
self.subscriptions[callback].append(message)
if not self.is_connected:
+ print_error("interface: trying to send while not connected")
return
if self.protocol in 'st':
return self.unanswered_requests == {}
- def synchronous_get(self, requests, timeout=100000000):
- # todo: use generators, unanswered_requests should be a list of arrays...
- queue = Queue.Queue()
- ids = self.send(requests, lambda i,r: queue.put(r))
- id2 = ids[:]
- res = {}
- while ids:
- r = queue.get(True, timeout)
- _id = r.get('id')
- if _id in ids:
- ids.remove(_id)
- res[_id] = r.get('result')
- out = []
- for _id in id2:
- out.append(res[_id])
- return out
-
- def start(self, queue):
- self.queue = queue
+ def start(self, queue = None, wait = False):
+ self.queue = queue if queue else Queue.Queue()
threading.Thread.start(self)
+ if wait:
+ self.connect_event.wait()
def run(self):
if __name__ == "__main__":
-
- q = Queue.Queue()
- i = Interface({'server':'btc.it-zone.org:50002:s', 'path':'/extra/key/wallet', 'verbose':True})
- i.start(q)
- time.sleep(1)
- exit()
-
+ check_certificates()