-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathWalletServlet.java
More file actions
2395 lines (1855 loc) · 78.5 KB
/
WalletServlet.java
File metadata and controls
2395 lines (1855 loc) · 78.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package piuk.website;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.mail.internet.InternetAddress;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base32;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.util.encoders.Hex;
import org.jsoup.Jsoup;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.RequestTokenPair;
import com.dropbox.client2.session.Session.AccessType;
import com.dropbox.client2.session.WebAuthSession;
import com.dropbox.client2.session.WebAuthSession.WebAuthInfo;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.bitcoin.core.ECKey;
import com.google.bitcoin.core.NetworkParameters;
import com.yubico.client.v2.YubicoClient;
import com.yubico.client.v2.YubicoResponse;
import com.yubico.client.v2.YubicoResponseStatus;
import piuk.api.NotificationsManager;
import piuk.beans.BitcoinAddress;
import piuk.db.BitcoinDatabaseManager;
import piuk.db.Cache;
import piuk.db.DBBitcoinAddress;
import piuk.merchant.MyWallet;
import piuk.website.admin.AdminServlet;
import piuk.common.Pair;
import piuk.website.admin.RequestLimiter;
import piuk.common.Scrambler;
/**
* Servlet implementation class ChartsServlet
*/
@WebServlet({ HomeServlet.ROOT + "wallet/*", HomeServlet.ROOT + "pwallet/*" })
public class WalletServlet extends BaseServlet {
public static final long serialVersionUID = 1L;
public static final int AuthTypeStandard = 0;
public static final int AuthTypeYubikey = 1;
public static final int AuthTypeEmail = 2;
public static final int AuthTypeYubikeyMtGox = 3;
public static final int AuthTypeGoogleAuthenticator = 4;
public static final String DemoAccountGUID = "abcaa314-6f67-6705-b384-5d47fbe9d7cc";
private static final int MaxFailedLogins = 4;
private static final int EmailCodeLength = 5;
private static final int GoogleAuthentictorSecretSize = 10; //128 bits
final static private String DROPBOX_APP_KEY = AdminServlet.DROPBOX_APP_KEY;
final static private String DROPBOX_APP_SECRET = AdminServlet.DROPBOX_APP_SECRET;
final static private AccessType DROPBOX_ACCESS_TYPE = AccessType.APP_FOLDER;
final static private String DROPBOX_CACHE_PREFIX = "drop:";
final static private String DROPBOX_CALLBACK = "https://blockchain.info/wallet/dropbox-update";
public static final JsonFactory GDRIVE_JSON_FACTORY = new JacksonFactory();
public static final HttpTransport GDRIVE_TRANSPORT = new NetHttpTransport();
public static final String CLIENT_SECRETS_FILE_PATH = "/client_secrets.json";
public static GoogleClientSecrets GDRIVE_SECRETS; //Initizialized by ContextListener
public static final List<String> GDRIVE_SCOPES = Arrays.asList(
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile");
final static private String GDRIVE_CACHE_PREFIX = "drop:";
final static public boolean EnablePaymentWall = false;
final static int DROPBOX_CACHE_EXPIRY = 2629743; //1 Month
final public static int MaxAddresses = 400;
public static class GoogleAuthenticator {
public static String generateSecret() {
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[32];
random.nextBytes(bytes);
Base32 codec = new Base32();
byte[] secretKey = Arrays.copyOf(bytes, GoogleAuthentictorSecretSize);
byte[] bEncodedKey = codec.encode(secretKey);
return new String(bEncodedKey);
}
public static String getQRBarcodeURL(String user, String host, String secret) {
return "otpauth://totp/"+user+"@"+host+"?secret="+secret;
}
private static int verify_code(byte[] key,long t) throws NoSuchAlgorithmException, InvalidKeyException {
byte[] data = new byte[8];
long value = t;
for (int i = 8; i-- > 0; value >>>= 8) {
data[i] = (byte) value;
}
SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signKey);
byte[] hash = mac.doFinal(data);
int offset = hash[20 - 1] & 0xF;
// We're using a long because Java hasn't got unsigned int.
long truncatedHash = 0;
for (int i = 0; i < 4; ++i) {
truncatedHash <<= 8;
// We are dealing with signed bytes:
// we just keep the first byte.
truncatedHash |= (hash[offset + i] & 0xFF);
}
truncatedHash &= 0x7FFFFFFF;
truncatedHash %= 1000000;
return (int) truncatedHash;
}
public static boolean check_code(String secret, long code, long t) throws NoSuchAlgorithmException, InvalidKeyException {
Base32 codec = new Base32();
byte[] decodedKey = codec.decode(secret);
// Window is used to check codes generated in the near past.
// You can use this value to tune how far you're willing to go.
int window = 5;
for (int i = -window; i <= window; ++i) {
long hash = verify_code(decodedKey, (t - 1) + i);
if (hash == code) {
return true;
}
}
// The validation code is invalid.
return false;
}
}
public static class DropBoxCacheEntry implements Serializable {
private static final long serialVersionUID = 5L;
private final String guid;
private final String key;
private final String secret;
private String accessTokenKey;
private String accessTokenSecret;
public DropBoxCacheEntry(String guid, String key, String secret) {
super();
this.guid = guid;
this.key = key;
this.secret = secret;
}
public AccessTokenPair getAccessToken() {
if (accessTokenKey == null || accessTokenSecret == null)
return null;
return new AccessTokenPair(accessTokenKey, accessTokenSecret);
}
public void setAccessToken(AccessTokenPair accessToken) {
this.accessTokenKey = accessToken.key;
this.accessTokenSecret = accessToken.secret;
}
public String getGuid() {
return guid;
}
public String getKey() {
return key;
}
public String getsecret() {
return secret;
}
}
protected static boolean doGDriveBackup(Connection conn, String guid, String code) {
try {
String refreshToken = (String) Cache.get(GDRIVE_CACHE_PREFIX + code);
Credential credentials = null;
if (refreshToken != null) {
credentials = new GoogleCredential.Builder()
.setClientSecrets(GDRIVE_SECRETS)
.setTransport(GDRIVE_TRANSPORT)
.setJsonFactory(GDRIVE_JSON_FACTORY)
.build().setRefreshToken(refreshToken);
} else {
GoogleTokenResponse response =
new GoogleAuthorizationCodeTokenRequest(
GDRIVE_TRANSPORT,
GDRIVE_JSON_FACTORY,
GDRIVE_SECRETS.getWeb().getClientId(),
GDRIVE_SECRETS.getWeb().getClientSecret(),
code,
GDRIVE_SECRETS.getWeb().getRedirectUris().get(0)).execute();
credentials = new GoogleCredential.Builder()
.setClientSecrets(GDRIVE_SECRETS)
.setTransport(GDRIVE_TRANSPORT)
.setJsonFactory(GDRIVE_JSON_FACTORY)
.build().setFromTokenResponse(response);
Cache.put(GDRIVE_CACHE_PREFIX + code, credentials.getRefreshToken(), DROPBOX_CACHE_EXPIRY);
}
Drive drive = Drive.builder(GDRIVE_TRANSPORT, GDRIVE_JSON_FACTORY).setHttpRequestInitializer(credentials).build();
PreparedStatement selectPayload = conn.prepareStatement("select payload from bitcoin_wallets where guid = ?");
String payload = null;
try {
selectPayload.setString(1, guid);
ResultSet results = selectPayload.executeQuery();
if (results.next()) {
payload = results.getString(1);
} else {
throw new Exception("Unauthorized");
}
} finally {
BitcoinDatabaseManager.close(selectPayload);
}
if (payload != null && payload.length() > 0) {
SimpleDateFormat format = new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss");
String dateString = format.format(new Date());
String fileName = "wallet_"+dateString+".aes.json";
File file = new File();
file.setId(fileName);
file.setTitle(fileName);
file.setDescription(fileName);
file.setMimeType("text/plain");
drive.files().insert(file, new ByteArrayContent("text/plain", payload.getBytes("UTF-8"))).execute();
return true;
} else {
throw new Exception("Null payload");
}
} catch (Exception e) {
return false;
}
}
protected static boolean doDropboxBackup(Connection conn, String oauth_token) {
try {
DropBoxCacheEntry entry = (DropBoxCacheEntry) Cache.get(DROPBOX_CACHE_PREFIX + oauth_token);
if (entry == null) {
throw new Exception("Could not find dropbox authentication session");
}
AppKeyPair appKeys = new AppKeyPair(DROPBOX_APP_KEY, DROPBOX_APP_SECRET);
WebAuthSession dropboxSession = null;
if (entry.getAccessToken() != null) {
dropboxSession = new WebAuthSession(appKeys, DROPBOX_ACCESS_TYPE, entry.getAccessToken());
} else {
dropboxSession = new WebAuthSession(appKeys, DROPBOX_ACCESS_TYPE);
dropboxSession.retrieveWebAccessToken(new RequestTokenPair(entry.getKey(), entry.getsecret()));
//Update the access token and re-save the cache entry
entry.setAccessToken(dropboxSession.getAccessTokenPair());
Cache.put(DROPBOX_CACHE_PREFIX + oauth_token, entry, DROPBOX_CACHE_EXPIRY);
}
DropboxAPI<WebAuthSession> api = new DropboxAPI<WebAuthSession>(dropboxSession);
String payload = null;
PreparedStatement selectPayload = conn.prepareStatement("select payload from bitcoin_wallets where guid = ?");
try {
selectPayload.setString(1, entry.getGuid());
ResultSet results = selectPayload.executeQuery();
if (results.next()) {
payload = results.getString(1);
} else {
throw new Exception("Unauthorized");
}
} finally {
BitcoinDatabaseManager.close(selectPayload);
}
if (payload != null && payload.length() > 0) {
InputStream stream = new ByteArrayInputStream(payload.getBytes("UTF-8"));
SimpleDateFormat format = new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss");
String dateString = format.format(new Date());
api.putFile("wallet_"+dateString+".aes.json", stream, stream.available(), null, null);
return true;
} else {
throw new Exception("Null payload");
}
} catch (Exception e) {
return false;
}
}
public static class WalletObject {
String payload;
String email;
int auth_type;
String yubikey;
long account_locked_time;
int failed_logins;
String email_code;
String guid;
int notifications_type;
long email_code_last_updated;
byte[] payload_checksum;
String google_secret;
String shared_key;
String secret_phrase;
int email_verified;
String http_url;
String skype_username;
int notifications_on;
int notifications_confirmations;
int auto_email_backup;
String alias;
public static WalletObject getWallet(Connection conn, String guid) throws SQLException {
return getWallet(conn, guid, null);
}
public static WalletObject getWallet(Connection conn, String guid, String alias) throws SQLException {
WalletObject obj = new WalletObject();
String sql = "select guid, payload, auth_type, yubikey, email, acount_locked_time, email_code, notifications_type, email_code_last_updated, failed_logins, payload_checksum, google_secret, shared_key, secret_phrase, email_verified, http_url, skype_username, notifications_on, notifications_confirmations, auto_email_backup, alias from bitcoin_wallets where guid = ?";
if (alias != null)
sql += " or alias = ?";
PreparedStatement smt = conn.prepareStatement(sql);
try {
smt.setString(1, guid);
if (alias != null)
smt.setString(2, alias); //Alias
//Should not be using it anymore
guid = null;
ResultSet results = smt.executeQuery();
if (results.next()) {
obj.guid = results.getString(1);
obj.payload = results.getString(2);
obj.auth_type = results.getInt(3);
obj.yubikey = results.getString(4);
obj.email = results.getString(5);
obj.account_locked_time = results.getLong(6);
obj.email_code = results.getString(7);
obj.notifications_type = results.getShort(8);
obj.email_code_last_updated = results.getLong(9);
obj.failed_logins = results.getInt(10);
obj.payload_checksum = results.getBytes(11);
obj.google_secret = results.getString(12);
obj.shared_key = results.getString(13);
obj.secret_phrase = results.getString(14);
obj.email_verified = results.getInt(15);
obj.http_url = results.getString(16);
obj.skype_username = results.getString(17);
obj.notifications_on = results.getInt(18);
obj.notifications_confirmations = results.getInt(19);
obj.auto_email_backup = results.getInt(20);
obj.alias = results.getString(21);
return obj;
}
} finally {
BitcoinDatabaseManager.close(smt);
}
return null;
}
}
public List<String> guidFromEmail(Connection conn, String email) throws SQLException {
List<String> data = new ArrayList<String>();
PreparedStatement select = conn.prepareStatement("select guid from bitcoin_wallets where email = ? limit 3");
try {
select.setString(1, email);
ResultSet results = select.executeQuery();
while(results.next()) {
data.add(results.getString(1));
}
} finally {
BitcoinDatabaseManager.close(select);
}
return data;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
super.doGet(req, res);
} catch (ServletException e) {
return;
}
req.setAttribute("no_search", true);
req.setAttribute("show_adv", false);
req.setAttribute("resource", LOCAL_RESOURCE_URL); //Never use static.blockchain.info
req.setAttribute("no_footer", true);
req.setAttribute("home_active", null);
req.setAttribute("wallet_active", " class=\"active\"");
req.setAttribute("enable_paymentwall", EnablePaymentWall);
req.setAttribute("enable_deposit", true);
req.setAttribute("dev_mode", devMode);
req.setAttribute("slogan", "Be Your Own Bank");
//Make all links absolute
req.setAttribute("root", HTTPS_ROOT);
if (req.getPathInfo() == null || req.getPathInfo().length() == 0) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-index.jsp").forward(req, res);
return;
}
String pathString = req.getPathInfo().substring(1);
String components[] = pathString.split("/", -1);
if (pathString == null || pathString.length() == 0 || components.length == 0) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-index.jsp").forward(req, res);
return;
}
/** If no special cases were matched we actually display the wallet to the user from here on **/
//Force https:// on all reauests from here on
if (!req.isSecure() && !devMode) {
req.setAttribute("initial_error", "You must use https:// not http:// please update your link");
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-index.jsp").forward(req, res);
return;
} else {
//If were using https:// we can make link relative again
req.setAttribute("root", ROOT);
}
//Does not need to be escaped as it is never output
String guid = components[0].trim();
Connection conn = BitcoinDatabaseManager.conn();
try {
if (guid.equals("faq")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-beginners-faq.jsp").forward(req, res);
return;
}if (guid.equals("technical-faq")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-technical-faq.jsp").forward(req, res);
return;
} else if (guid.equals("login")) {
String saved_guid = getCookieValue(req, "cguid");
if (saved_guid != null && saved_guid.length() == 36 && !saved_guid.equals(DemoAccountGUID)) {
res.sendRedirect(BaseServlet.ROOT + "wallet/" + saved_guid);
return;
} else {
req.setAttribute("guid", "");
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-app.jsp").forward(req, res);
}
return;
} else if (guid.equals("new")) { //Special case for demo account - send users to signup page instead
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-new.jsp").forward(req, res);
return;
} else if (guid.equals("paypal-vs-bitcoin")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-vs-paypal.jsp").forward(req, res);
return;
} else if (guid.equals("android-app")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-android.jsp").forward(req, res);
return;
} else if (guid.equals("iphone-app")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-iphone.jsp").forward(req, res);
return;
} else if (guid.equals("sms-phone-deposits")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-sms.jsp").forward(req, res);
return;
} else if (guid.equals("yubikey")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-yubikey.jsp").forward(req, res);
return;
} else if (guid.equals("google-authenticator")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-google-authenticator.jsp").forward(req, res);
return;
} else if (guid.equals("security")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-security.jsp").forward(req, res);
return;
} else if (guid.equals("devices")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-devices.jsp").forward(req, res);
return;
} else if (guid.equals("support-pages")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-support.jsp").forward(req, res);
return;
} else if (guid.equals("paper-tutorial")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-paper-tutorial.jsp").forward(req, res);
return;
} else if (guid.equals("payment-notifications")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-notifications.jsp").forward(req, res);
return;
} else if (guid.equals("backups")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-backups.jsp").forward(req, res);
return;
} else if (guid.equals("anonymity")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-anonymity.jsp").forward(req, res);
return;
} else if (guid.equals("wallet-format")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-format.jsp").forward(req, res);
return;
} else if (guid.equals("escrow")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-escrow.jsp").forward(req, res);
return;
} else if (guid.equals("buy-one-bitcoin")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-buy-one-bitcoin.jsp").forward(req, res);
return;
} else if (guid.equals("features")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-features.jsp").forward(req, res);
return;
} else if (guid.equals("features")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-features.jsp").forward(req, res);
return;
} else if (guid.equals("verifier")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-verifier.jsp").forward(req, res);
return;
} else if (guid.equals("decryption-error")) {
req.setAttribute("no_header", true);
getServletContext().getRequestDispatcher("/WEB-INF/wallet/mobile/bitcoin-wallet-decryption-error.jsp").forward(req, res);
return;
} else if (guid.equals("deposit-methods")) {
getServletContext().getRequestDispatcher("/WEB-INF/wallet/bitcoin-wallet-deposit-methods.jsp").forward(req, res);
return;
} else if (guid.equals("wallet.404.manifest") || guid.equals("wallet.index.manifest")) {
res.setStatus(404);
return;
} else if (guid.equals("wallet.manifest")) {
res.addHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate");
res.addHeader("Pragma", "no-cache");
res.addHeader("Expires", "Wed, 11 Jan 1984 05:00:00 GMT");
res.addHeader("Content-type", "text/cache-manifest");
guid = req.getParameter("guid");
if (guid != null) {
UUID rguid = UUID.fromString(guid);
PreparedStatement select = conn.prepareStatement("select payload_checksum, auth_type from bitcoin_wallets where guid = ?");
try {
select.setString(1, rguid.toString());
ResultSet results = select.executeQuery();
if (results.next()) {
if (results.getBytes(1) != null)
req.setAttribute("payload_checksum", new String(Hex.encode(results.getBytes(1))));
req.setAttribute("auth_type", results.getInt(2));
}
req.setAttribute("initial_success", "Confirmation Email Sent");
} finally {
BitcoinDatabaseManager.close(select);
}
}
getServletContext().getRequestDispatcher("/WEB-INF/wallet/bitcoin-wallet-manifest.jsp").forward(req, res);
return;
} else if (guid.equals("iphone-view")) {
req.setAttribute("no_header", true);
String rguid = req.getParameter("guid");
String sharedKey = req.getParameter("sharedKey");
if (rguid == null || rguid.length() == 0 || sharedKey == null || sharedKey.length() == 0)
return;
PreparedStatement select_smt = conn.prepareStatement("select payload from bitcoin_wallets where guid = ? and shared_key = ?");
try {
select_smt.setString(1, rguid);
select_smt.setString(2, sharedKey);
ResultSet results = select_smt.executeQuery();
if (results.next()) {
req.setAttribute("guid", rguid);
req.setAttribute("sharedKey", sharedKey);
getServletContext().getRequestDispatcher("/WEB-INF/wallet/mobile/bitcoin-wallet-mobile-index.jsp").forward(req, res);
} else {
req.setAttribute("initial_error", "Wallet identifier not found. Your wallet is not yet saved on our server yet. Please setup a new account to avoid losing your wallet.");
getServletContext().getRequestDispatcher("/WEB-INF/wallet/mobile/bitcoin-wallet-mobile-not-found.jsp").forward(req, res);
return;
}
} finally {
BitcoinDatabaseManager.close(select_smt);
}
return;
} else if (guid.equals("forgot-identifier")) {
String email = req.getParameter("email");
if (email != null && email.length() > 0) {
email = email.trim();
RequestLimiter.didRequest(req.getRemoteAddr(), 100); //Limited to approx 6 failed tries every 4 hours (Global over whole site)
if (isValidEmailAddress(email)) {
List<String> guids = guidFromEmail(conn, email);
for (String email_guid : guids) {
sendEmailLink(email_guid, false);
}
if (guids.size() > 0)
req.setAttribute("initial_success", "Confirmation Email Sent");
else
req.setAttribute("initial_success", "Email Not Found");
} else {
req.setAttribute("initial_error", "Email Address Invalid");
}
}
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-forgot-identifier.jsp").forward(req, res);
return;
} else if (guid.equals("dropbox-update")) {
String oauth_token = req.getParameter("oauth_token");
if (doDropboxBackup(conn, oauth_token)) {
res.getOutputStream().print("Wallet successfully saved to dropbox. You may now close this window");
} else {
res.getOutputStream().print("Error Saving to dropbox");
}
return;
} else if (guid.equals("gdrive-update")) {
String rguid = (String)getSesssionValue(req, res, "temp_guid");
String token = req.getParameter("code");
if (rguid == null){
throw new Exception("Temp guid expired");
}
//Set the new auth token
PreparedStatement update_smt = conn.prepareStatement("update bitcoin_wallets set gdrive_auth_token = ? where guid = ?");
try {
update_smt.setString(1, token);
update_smt.setString(2, rguid);
update_smt.executeUpdate();
} finally {
BitcoinDatabaseManager.close(update_smt);
}
if (doGDriveBackup(conn, rguid, token)) {
res.getOutputStream().print("Wallet successfully saved to google drive. You may now close this window");
} else {
res.setContentType("text/html");
res.getOutputStream().print("<h1>Error Saving to Google Drive.</h1> Be sure you have installed the <a href=\"https://chrome.google.com/webstore/detail/djjkppdfofjnpcbnkkangbhanjdnoocd\">My Wallet Chrome App</a> and blockchain.info is listed in your Google Drive Apps.");
}
return;
} else if (guid.equals("gdrive-login")) {
String rguid = req.getParameter("guid");
String sharedKey = req.getParameter("sharedKey");
String auth_token = null;
//Read it back to double check
PreparedStatement select_smt = conn.prepareStatement("select gdrive_auth_token from bitcoin_wallets where guid = ? and shared_key = ?");
try {
select_smt.setString(1, rguid);
select_smt.setString(2, sharedKey);
ResultSet results = select_smt.executeQuery();
if (results.next()) {
auth_token = results.getString(1);
} else {
throw new Exception("Unauthorized");
}
} finally {
BitcoinDatabaseManager.close(select_smt);
}
if (auth_token != null) {
if (doGDriveBackup(conn, rguid, auth_token)) {
res.getOutputStream().print("Wallet successfully saved to Google drive.");
return;
}
}
setSessionValue(req, res, "temp_guid", rguid, 1200);
GoogleAuthorizationCodeRequestUrl urlBuilder =
new GoogleAuthorizationCodeRequestUrl(
GDRIVE_SECRETS.getWeb().getClientId(),
GDRIVE_SECRETS.getWeb().getRedirectUris().get(0),
GDRIVE_SCOPES)
.setAccessType("offline").setApprovalPrompt("force");
String redirect_url = urlBuilder.build();
res.sendRedirect(redirect_url);
return;
} else if (guid.equals("dropbox-login")) {
String rguid = req.getParameter("guid");
String sharedKey = req.getParameter("sharedKey");
String auth_token = null;
//Read it back to double check
PreparedStatement select_smt = conn.prepareStatement("select dropbox_auth_token from bitcoin_wallets where guid = ? and shared_key = ?");
try {
select_smt.setString(1, rguid);
select_smt.setString(2, sharedKey);
ResultSet results = select_smt.executeQuery();
if (results.next()) {
auth_token = results.getString(1);
} else {
throw new Exception("Unauthorized");
}
} finally {
BitcoinDatabaseManager.close(select_smt);
}
if (auth_token != null) {
if (doDropboxBackup(conn, auth_token)) {
res.getOutputStream().print("Wallet successfully saved to dropbox.");
return;
}
}
AppKeyPair appKeys = new AppKeyPair(DROPBOX_APP_KEY, DROPBOX_APP_SECRET);
WebAuthSession dropboxSession = new WebAuthSession(appKeys, DROPBOX_ACCESS_TYPE);
WebAuthInfo authInfo = dropboxSession.getAuthInfo(DROPBOX_CALLBACK);
if (authInfo != null) {
boolean didUpdate = false;
//Set the new auth token
PreparedStatement update_smt = conn.prepareStatement("update bitcoin_wallets set dropbox_auth_token = ? where guid = ? and shared_key = ?");
try {
update_smt.setString(1, authInfo.requestTokenPair.key);
update_smt.setString(2, rguid);
update_smt.setString(3, sharedKey);
//If successfull redirect the user to the oauth login page
if (update_smt.executeUpdate() == 1) {
didUpdate = true;
}
} finally {
BitcoinDatabaseManager.close(update_smt);
}
if (didUpdate) {
Cache.put(DROPBOX_CACHE_PREFIX + authInfo.requestTokenPair.key, new DropBoxCacheEntry(rguid, authInfo.requestTokenPair.key, authInfo.requestTokenPair.secret), DROPBOX_CACHE_EXPIRY);
res.sendRedirect(authInfo.url);
}
} else {
throw new Exception("Unauthorized");
}
return;
} else if (guid.equals("resolve-alias")) {
String rguid = req.getParameter("guid");
PreparedStatement select_smt = conn.prepareStatement("select guid, shared_key from bitcoin_wallets where (guid = ? or alias = ?) and auth_type = 0");
try {
select_smt.setString(1, rguid);
select_smt.setString(2, rguid);
ResultSet results = select_smt.executeQuery();
if (results.next()) {
guid = results.getString(1);
String sharedKey = results.getString(2);
res.setContentType("text/json");
res.getOutputStream().print("{\"guid\" : \""+guid+"\", \"sharedKey\" : \"" + sharedKey + "\"}");
} else {
res.setStatus(500);
res.setContentType("text/plain");
res.getOutputStream().print("Wallet identifier not found");
}
} finally {
BitcoinDatabaseManager.close(select_smt);
}
return;
} else if (guid.equals("wallet.aes.json")) {
String rguid = req.getParameter("guid");
String sharedKey = req.getParameter("sharedKey");
String checksumString = req.getParameter("checksum");
if (rguid == null || rguid.length() == 0 || sharedKey == null || sharedKey.length() == 0)
return;
PreparedStatement select_smt = conn.prepareStatement("select payload, payload_checksum from bitcoin_wallets where guid = ? and shared_key = ?");
String payload = null;
try {
select_smt.setString(1, rguid);
select_smt.setString(2, sharedKey);
ResultSet results = select_smt.executeQuery();
if (results.next()) {
res.setContentType("application/octet-stream");
try {
byte[] checkwith = results.getBytes(2);
if (checksumString != null && checkwith != null) {
byte[] checksum = Hex.decode(checksumString);
if (Arrays.equals(checkwith, checksum)) {
res.getOutputStream().print("Not modified");
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
payload = results.getString(1);
} else {
res.setStatus(500);
res.setContentType("text/plain");
res.getOutputStream().print("Wallet identifier not found");
return;
}
if (payload != null)
res.getOutputStream().print(payload);
} finally {
BitcoinDatabaseManager.close(select_smt);
}
return;
} else if (guid.equals("unsubscribe")) {
String rguid = req.getParameter("guid");
if (rguid == null || rguid.length() == 0)
return;
String unscrambled = Scrambler.unscramble(rguid);
PreparedStatement disable_notifications = conn.prepareStatement("update bitcoin_wallets set notifications_type = 0 where guid = ?");
try {
disable_notifications.setString(1, unscrambled);
if (disable_notifications.executeUpdate() == 1) {
req.setAttribute("initial_success", "Your email has been unsubscribed from all notifications");
} else {
req.setAttribute("initial_error", "Wallet identifier or email code were incorrect. You have not been unsubscribed");
}
} finally {
BitcoinDatabaseManager.close(disable_notifications);
}
getServletContext().getRequestDispatcher("/WEB-INF/wallet/"+ BaseServlet.ROOT + "bitcoin-wallet-index.jsp").forward(req, res);
return;
} else if (guid.equals("send-bitcoins-email")) {
String to = req.getParameter("to");
String rguid = req.getParameter("guid");
String priv = req.getParameter("priv");
String sharedKey = req.getParameter("sharedKey");
sendBitcoinsEmail(to, rguid, sharedKey, priv);
return;
}
//Guid might actually be an alias
final WalletObject obj = WalletObject.getWallet(conn, guid, guid);
//Should not be using it anymore
guid = null;
if (obj != null) {
if (obj.payload_checksum != null) {
String payload_checksum = new String(Hex.encode(obj.payload_checksum));
req.setAttribute("payload_checksum", payload_checksum);
}
if (obj.failed_logins >= MaxFailedLogins) {
if (lockAccount(obj.guid, obj.email, 240)) {
throw new Exception("Your account account has been locked");