update to certificate check for Subject Alt Names
[electrum-nvc.git] / lib / paymentrequest.py
1 import hashlib
2 import httplib
3 import os.path
4 import re
5 import sys
6 import threading
7 import time
8 import traceback
9 import urllib2
10
11 try:
12     import paymentrequest_pb2
13 except:
14     print "protoc --proto_path=lib/ --python_out=lib/ lib/paymentrequest.proto"
15     sys.exit(1)
16
17 import urlparse
18 import requests
19 from M2Crypto import X509
20
21 from bitcoin import is_valid
22 import urlparse
23
24 import transaction
25
26 REQUEST_HEADERS = {'Accept': 'application/bitcoin-paymentrequest', 'User-Agent': 'Electrum'}
27 ACK_HEADERS = {'Content-Type':'application/bitcoin-payment','Accept':'application/bitcoin-paymentack','User-Agent':'Electrum'}
28
29 class PaymentRequest:
30
31     def __init__(self):
32         self.ca_path = os.path.expanduser("~/.electrum/ca/ca-bundle.crt")
33         self.ca_list = {}
34         try:
35             with open(self.ca_path, 'r') as ca_f:
36                 c = ""
37                 for line in ca_f:
38                     if line == "-----BEGIN CERTIFICATE-----\n":
39                         c = line
40                     else:
41                         c += line
42                     if line == "-----END CERTIFICATE-----\n":
43                         x = X509.load_cert_string(c)
44                         self.ca_list[x.get_fingerprint()] = x
45         except Exception:
46             print "ERROR: Could not open %s"%self.ca_path
47             print "ca-bundle.crt file should be placed in ~/.electrum/ca/ca-bundle.crt"
48             print "Documentation on how to download or create the file here: http://curl.haxx.se/docs/caextract.html"
49             print "Payment will continue with manual verification."
50
51
52
53     def verify(self, url):
54
55         u = urlparse.urlparse(urllib2.unquote(url))
56         self.domain = u.netloc
57
58         connection = httplib.HTTPConnection(u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(u.netloc)
59         connection.request("GET",u.geturl(), headers=REQUEST_HEADERS)
60         resp = connection.getresponse()
61
62         r = resp.read()
63         paymntreq = paymentrequest_pb2.PaymentRequest()
64         paymntreq.ParseFromString(r)
65
66         sig = paymntreq.signature
67
68         cert = paymentrequest_pb2.X509Certificates()
69         cert.ParseFromString(paymntreq.pki_data)
70         cert_num = len(cert.certificate)
71
72         x509_1 = X509.load_cert_der_string(cert.certificate[0])
73         if self.domain != x509_1.get_subject().CN:
74             validcert = False
75             try:
76                 SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
77                 for s in SANs:
78                     s = s.strip()
79                     if s.startswith("DNS:") and s[4:] == self.domain:
80                         validcert = True
81                         print "Match SAN DNS"
82                     elif s.startswith("IP:") and s[3:] == self.domain:
83                         validcert = True
84                         print "Match SAN IP"
85                     elif s.startswith("email:") and s[6:] == self.domain:
86                         validcert = True
87                         print "Match SAN email"
88             except Exception, e:
89                 print "ERROR: No SAN data"
90             if not validcert:
91                 ###TODO: check for wildcards
92                 print "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
93                 print self.domain, x509_1.get_subject().CN
94                 return
95
96         x509 = []
97         CA_OU = ''
98
99         if cert_num > 1:
100             for i in range(cert_num - 1):
101                 x509.append(X509.load_cert_der_string(cert.certificate[i+1]))
102                 if x509[i].check_ca() == 0:
103                     print "ERROR: Supplied CA Certificate Error"
104                     return
105             for i in range(cert_num - 1):
106                 if i == 0:
107                     if x509_1.verify(x509[i].get_pubkey()) != 1:
108                         print "ERROR: Certificate not Signed by Provided CA Certificate Chain"
109                         return
110                 else:
111                     if x509[i-1].verify(x509[i].get_pubkey()) != 1:
112                         print "ERROR: CA Certificate not Signed by Provided CA Certificate Chain"
113                         return
114
115             supplied_CA_fingerprint = x509[cert_num-2].get_fingerprint()
116             supplied_CA_CN = x509[cert_num-2].get_subject().CN
117             CA_match = False
118
119             x = self.ca_list.get(supplied_CA_fingerprint)
120             if x:
121                 CA_OU = x.get_subject().OU
122                 CA_match = True
123                 if x.get_subject().CN != supplied_CA_CN:
124                     print "ERROR: Trusted CA CN Mismatch; however CA has trusted fingerprint"
125                     print "Payment will continue with manual verification."
126             else:
127                 print "ERROR: Supplied CA Not Found in Trusted CA Store."
128                 print "Payment will continue with manual verification."
129         else:
130             print "ERROR: CA Certificate Chain Not Provided by Payment Processor"
131             return False
132
133         paymntreq.signature = ''
134         s = paymntreq.SerializeToString()
135         pubkey_1 = x509_1.get_pubkey()
136
137         if paymntreq.pki_type == "x509+sha256":
138             pubkey_1.reset_context(md="sha256")
139         elif paymntreq.pki_type == "x509+sha1":
140             pubkey_1.reset_context(md="sha1")
141         else:
142             print "ERROR: Unsupported PKI Type for Message Signature"
143             return False
144
145         pubkey_1.verify_init()
146         pubkey_1.verify_update(s)
147         if pubkey_1.verify_final(sig) != 1:
148             print "ERROR: Invalid Signature for Payment Request Data"
149             return False
150
151         ### SIG Verified
152
153         self.payment_details = pay_det = paymentrequest_pb2.PaymentDetails()
154         pay_det.ParseFromString(paymntreq.serialized_payment_details)
155
156         if pay_det.expires and pay_det.expires < int(time.time()):
157             print "ERROR: Payment Request has Expired."
158             return False
159
160         self.outputs = []
161         for o in pay_det.outputs:
162             addr = transaction.get_address_from_output_script(o.script)[1]
163             self.outputs.append( (addr, o.amount) )
164
165         if CA_match:
166             print 'Signed By Trusted CA: ', CA_OU
167
168         return True
169
170
171
172     def send_ack(self, raw_tx, refund_addr):
173
174         pay_det = self.payment_details
175         if pay_det.payment_url:
176             paymnt = paymentrequest_pb2.Payment()
177
178             paymnt.merchant_data = pay_det.merchant_data
179             paymnt.transactions.append(raw_tx)
180
181             ref_out = paymnt.refund_to.add()
182             ref_out.script = transaction.Transaction.pay_script(refund_addr)
183             paymnt.memo = "Paid using Electrum"
184             pm = paymnt.SerializeToString()
185
186             payurl = urlparse.urlparse(pay_det.payment_url)
187             try:
188                 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=self.ca_path)
189             except requests.exceptions.SSLError:
190                 print "Payment Message/PaymentACK verify Failed"
191                 try:
192                     r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=False)
193                 except Exception as e:
194                     print "Payment Message/PaymentACK Failed"
195                     print e
196                     return
197             try:
198                 paymntack = paymentrequest_pb2.PaymentACK()
199                 paymntack.ParseFromString(r.content)
200                 print "PaymentACK message received: %s" % paymntack.memo
201             except Exception:
202                 print "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
203
204
205 uri = "bitcoin:mpu3yTLdqA1BgGtFUwkVJmhnU3q5afaFkf?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D26c19879d44c3891214e7897797b9160&amount=1"
206 url = "https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D26c19879d44c3891214e7897797b9160"
207
208 #uri = "bitcoin:1m9Lw2pFCe6Hs7xUuo9fMJCzEwQNdCo5e?amount=0.0012&r=https%3A%2F%2Fbitpay.com%2Fi%2F8XNDiQU92H2whNG4j8hZ5M"
209 #url = "https%3A%2F%2Fbitpay.com%2Fi%2F8XNDiQU92H2whNG4j8hZ5M"
210
211
212 if __name__ == "__main__":
213
214     pr = PaymentRequest()
215     if not pr.verify(url):
216         sys.exit(1)
217
218     print 'Payment Request Verified Domain: ', pr.domain
219     print 'outputs', pr.outputs
220     print 'Payment Memo: ', pr.payment_details.memo
221
222     tx = "blah"
223     pr.send_ack(tx, "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")
224