fix: sanitize outputs
[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     raise Exception()
16
17 import urlparse
18 import requests
19 from M2Crypto import X509
20
21 from bitcoin import is_valid
22 import urlparse
23
24
25 import util
26 import transaction
27
28
29 REQUEST_HEADERS = {'Accept': 'application/bitcoin-paymentrequest', 'User-Agent': 'Electrum'}
30 ACK_HEADERS = {'Content-Type':'application/bitcoin-payment','Accept':'application/bitcoin-paymentack','User-Agent':'Electrum'}
31
32 ca_path = os.path.expanduser("~/.electrum/ca/ca-bundle.crt")
33 ca_list = {}
34 try:
35     with open(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                 ca_list[x.get_fingerprint()] = x
45 except Exception:
46     print "ERROR: Could not open %s"%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     raise Exception()
51
52
53 class PaymentRequest:
54
55     def __init__(self, url):
56         self.url = url
57         self.outputs = []
58         self.error = ""
59
60
61     def verify(self):
62         u = urlparse.urlparse(self.url)
63         self.domain = u.netloc
64
65         try:
66             connection = httplib.HTTPConnection(u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(u.netloc)
67             connection.request("GET",u.geturl(), headers=REQUEST_HEADERS)
68             resp = connection.getresponse()
69         except:
70             self.error = "cannot read url"
71             return
72
73         paymntreq = paymentrequest_pb2.PaymentRequest()
74         try:
75             r = resp.read()
76             paymntreq.ParseFromString(r)
77         except:
78             self.error = "cannot parse payment request"
79             return
80
81         sig = paymntreq.signature
82         if not sig:
83             self.error = "No signature"
84             return 
85
86         cert = paymentrequest_pb2.X509Certificates()
87         cert.ParseFromString(paymntreq.pki_data)
88         cert_num = len(cert.certificate)
89
90         x509_1 = X509.load_cert_der_string(cert.certificate[0])
91         if self.domain != x509_1.get_subject().CN:
92             validcert = False
93             try:
94                 SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
95                 for s in SANs:
96                     s = s.strip()
97                     if s.startswith("DNS:") and s[4:] == self.domain:
98                         validcert = True
99                         print "Match SAN DNS"
100                     elif s.startswith("IP:") and s[3:] == self.domain:
101                         validcert = True
102                         print "Match SAN IP"
103                     elif s.startswith("email:") and s[6:] == self.domain:
104                         validcert = True
105                         print "Match SAN email"
106             except Exception, e:
107                 print "ERROR: No SAN data"
108             if not validcert:
109                 ###TODO: check for wildcards
110                 self.error = "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
111                 return
112
113         x509 = []
114         CA_OU = ''
115
116         if cert_num > 1:
117             for i in range(cert_num - 1):
118                 x509.append(X509.load_cert_der_string(cert.certificate[i+1]))
119                 if x509[i].check_ca() == 0:
120                     self.error = "ERROR: Supplied CA Certificate Error"
121                     return
122             for i in range(cert_num - 1):
123                 if i == 0:
124                     if x509_1.verify(x509[i].get_pubkey()) != 1:
125                         self.error = "ERROR: Certificate not Signed by Provided CA Certificate Chain"
126                         return
127                 else:
128                     if x509[i-1].verify(x509[i].get_pubkey()) != 1:
129                         self.error = "ERROR: CA Certificate not Signed by Provided CA Certificate Chain"
130                         return
131
132             supplied_CA_fingerprint = x509[cert_num-2].get_fingerprint()
133             supplied_CA_CN = x509[cert_num-2].get_subject().CN
134             CA_match = False
135
136             x = ca_list.get(supplied_CA_fingerprint)
137             if x:
138                 CA_OU = x.get_subject().OU
139                 CA_match = True
140                 if x.get_subject().CN != supplied_CA_CN:
141                     print "ERROR: Trusted CA CN Mismatch; however CA has trusted fingerprint"
142                     print "Payment will continue with manual verification."
143             else:
144                 print "ERROR: Supplied CA Not Found in Trusted CA Store."
145                 print "Payment will continue with manual verification."
146         else:
147             self.error = "ERROR: CA Certificate Chain Not Provided by Payment Processor"
148             return False
149
150         paymntreq.signature = ''
151         s = paymntreq.SerializeToString()
152         pubkey_1 = x509_1.get_pubkey()
153
154         if paymntreq.pki_type == "x509+sha256":
155             pubkey_1.reset_context(md="sha256")
156         elif paymntreq.pki_type == "x509+sha1":
157             pubkey_1.reset_context(md="sha1")
158         else:
159             self.error = "ERROR: Unsupported PKI Type for Message Signature"
160             return False
161
162         pubkey_1.verify_init()
163         pubkey_1.verify_update(s)
164         if pubkey_1.verify_final(sig) != 1:
165             self.error = "ERROR: Invalid Signature for Payment Request Data"
166             return False
167
168         ### SIG Verified
169
170         self.payment_details = pay_det = paymentrequest_pb2.PaymentDetails()
171         pay_det.ParseFromString(paymntreq.serialized_payment_details)
172
173         if pay_det.expires and pay_det.expires < int(time.time()):
174             self.error = "ERROR: Payment Request has Expired."
175             return False
176
177         for o in pay_det.outputs:
178             addr = transaction.get_address_from_output_script(o.script)[1]
179             self.outputs.append( (addr, o.amount) )
180
181         self.memo = pay_det.memo
182
183         if CA_match:
184             self.status = 'Signed by Trusted CA:\n' + CA_OU
185
186         print "payment url", pay_det.payment_url
187         return True
188
189
190
191     def send_ack(self, raw_tx, refund_addr):
192
193         pay_det = self.payment_details
194         if not pay_det.payment_url:
195             return False, "no url"
196
197         paymnt = paymentrequest_pb2.Payment()
198         paymnt.merchant_data = pay_det.merchant_data
199         paymnt.transactions.append(raw_tx)
200
201         ref_out = paymnt.refund_to.add()
202         ref_out.script = transaction.Transaction.pay_script(refund_addr)
203         paymnt.memo = "Paid using Electrum"
204         pm = paymnt.SerializeToString()
205
206         payurl = urlparse.urlparse(pay_det.payment_url)
207         try:
208             r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=ca_path)
209         except requests.exceptions.SSLError:
210             print "Payment Message/PaymentACK verify Failed"
211             try:
212                 r = requests.post(payurl.geturl(), data=pm, headers=ACK_HEADERS, verify=False)
213             except Exception as e:
214                 print e
215                 return False, "Payment Message/PaymentACK Failed"
216
217         if r.status_code >= 500:
218             return False, r.reason
219
220         try:
221             paymntack = paymentrequest_pb2.PaymentACK()
222             paymntack.ParseFromString(r.content)
223         except Exception:
224             return False, "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
225
226         print "PaymentACK message received: %s" % paymntack.memo
227         return True, paymntack.memo
228
229
230
231
232 if __name__ == "__main__":
233
234     try:
235         uri = sys.argv[1]
236     except:
237         print "usage: %s url"%sys.argv[0]
238         print "example url: \"bitcoin:mpu3yTLdqA1BgGtFUwkVJmhnU3q5afaFkf?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3D2a828c05b8b80dc440c80a5d58890298&amount=1\""
239         sys.exit(1)
240
241     address, amount, label, message, request_url, url = util.parse_url(uri)
242     pr = PaymentRequest(request_url)
243     if not pr.verify():
244         sys.exit(1)
245
246     print 'Payment Request Verified Domain: ', pr.domain
247     print 'outputs', pr.outputs
248     print 'Payment Memo: ', pr.payment_details.memo
249
250     tx = "blah"
251     pr.send_ack(tx, refund_addr = "1vXAXUnGitimzinpXrqDWVU4tyAAQ34RA")
252