forked from hbci4j/hbci4java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractPinTanPassport.java
1767 lines (1493 loc) · 66.8 KB
/
AbstractPinTanPassport.java
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
/**********************************************************************
*
* This file is part of HBCI4Java.
* Copyright (c) 2001-2008 Stefan Palme
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
**********************************************************************/
package org.kapott.hbci.passport;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import org.kapott.hbci.GV.GVTAN2Step;
import org.kapott.hbci.GV.HBCIJobImpl;
import org.kapott.hbci.callback.HBCICallback;
import org.kapott.hbci.comm.Comm;
import org.kapott.hbci.dialog.DialogContext;
import org.kapott.hbci.dialog.DialogEvent;
import org.kapott.hbci.dialog.HBCIMessage;
import org.kapott.hbci.dialog.HBCIMessageQueue;
import org.kapott.hbci.dialog.KnownDialogTemplate;
import org.kapott.hbci.dialog.KnownReturncode;
import org.kapott.hbci.dialog.KnownTANProcess;
import org.kapott.hbci.dialog.KnownTANProcess.Variant;
import org.kapott.hbci.dialog.RawHBCIDialog;
import org.kapott.hbci.dialog.SCARequest;
import org.kapott.hbci.exceptions.HBCI_Exception;
import org.kapott.hbci.exceptions.InvalidUserDataException;
import org.kapott.hbci.manager.ChallengeInfo;
import org.kapott.hbci.manager.Feature;
import org.kapott.hbci.manager.HBCIDialog;
import org.kapott.hbci.manager.HBCIHandler;
import org.kapott.hbci.manager.HBCIKernelImpl;
import org.kapott.hbci.manager.HBCIKey;
import org.kapott.hbci.manager.HBCIUser;
import org.kapott.hbci.manager.HBCIUtils;
import org.kapott.hbci.manager.HBCIUtilsInternal;
import org.kapott.hbci.manager.HHDVersion;
import org.kapott.hbci.manager.HHDVersion.Type;
import org.kapott.hbci.manager.TanMethod;
import org.kapott.hbci.protocol.SEG;
import org.kapott.hbci.protocol.factory.SEGFactory;
import org.kapott.hbci.security.Crypt;
import org.kapott.hbci.security.Sig;
import org.kapott.hbci.status.HBCIMsgStatus;
import org.kapott.hbci.status.HBCIRetVal;
import org.kapott.hbci.structures.Konto;
import org.kapott.hbci.tools.CryptUtils;
import org.kapott.hbci.tools.NumberUtil;
import org.kapott.hbci.tools.ParameterFinder;
import org.kapott.hbci.tools.ParameterFinder.Query;
import org.kapott.hbci.tools.StringUtil;
/**
* Abstrakte Basis-Implementierung des PIN/TAN-Supports.
*/
public abstract class AbstractPinTanPassport extends AbstractHBCIPassport
{
/**
* Hier speichern wir zwischen, ob wir eine HKTAN-Anfrage in der Dialog-Initialisierung gesendet haben und wenn ja, welcher Prozess-Schritt es war
*/
private final static String CACHE_KEY_SCA_STEP = "__sca_step__";
/**
* Hier speichern wir, ob wir eine SCA-Ausnahme fuer einen GV von der Bank erhalten haben
*/
public final static String KEY_PD_SCA = "__pintan_sca___";
/**
* Hier speichern wir den Challenge-Text der Bank fuer die TAN-Abfrage.
*/
public final static String KEY_PD_CHALLENGE = "__pintan_challenge___";
/**
* Hier speichern wir das HHDuc fuer die TAN-Abfrage.
*/
public final static String KEY_PD_HHDUC = "__pintan_hhduc___";
/**
* Hier speichern wir die Auftragsreferenz fuer die TAN-Abfrage.
*/
public final static String KEY_PD_ORDERREF = "__pintan_orderref___";
private String certfile;
private boolean checkCert;
private String proxy;
private String proxyuser;
private String proxypass;
private boolean verifyTANMode;
// Das aktuell ausgewaehlte TAN-Verfahren
private String tanMethod;
// True, wenn das aktuelle TAN-Verfahren automatisch gewaehlt wurde
private boolean tanMethodAutoSelected;
// Die TAN-Verfahren fuer den User (aus dem 3920-Rueckmeldecode)
private List<String> tanMethodsUser;
// Die TAN-Verfahren mit den Parametern aus den BPD
private Hashtable<String,Properties> tanMethodsBank;
private String pin;
/**
* ct.
* @param initObject
*/
public AbstractPinTanPassport(Object initObject)
{
super(initObject);
this.tanMethodsBank=new Hashtable<String, Properties>();
this.tanMethodsUser=new ArrayList<String>();
}
/**
* @see org.kapott.hbci.passport.HBCIPassportInternal#getPassportTypeName()
*/
public String getPassportTypeName()
{
return "PinTan";
}
/**
* @see org.kapott.hbci.passport.AbstractHBCIPassport#setBPD(java.util.Properties)
*/
public void setBPD(Properties p)
{
super.setBPD(p);
if (p!=null && p.size()!=0) {
// hier die liste der verfügbaren sicherheitsverfahren aus den
// bpd (HITANS) extrahieren
tanMethodsBank.clear();
// willuhn 2011-06-06 Maximal zulaessige HITANS-Segment-Version ermitteln
// Hintergrund: Es gibt User, die nur HHD 1.3-taugliche TAN-Generatoren haben,
// deren Banken aber auch HHD 1.4 beherrschen. In dem Fall wuerde die Bank
// HITANS/HKTAN/HITAN in Segment-Version 5 machen, was in der Regel dazu fuehren
// wird, dass HHD 1.4 zur Anwendung kommt. Das bewirkt, dass ein Flicker-Code
// erzeugt wird, der vom TAN-Generator des Users gar nicht lesbar ist, da dieser
// kein HHD 1.4 beherrscht. Mit dem folgenden Parameter kann die Maximal-Version
// des HITANS-Segments nach oben begrenzt werden, so dass z.Bsp. HITANS5 ausgefiltert
// wird.
int maxAllowedVersion = Integer.parseInt(HBCIUtils.getParam("kernel.gv.HITANS.segversion.max","0"));
for (Enumeration e=p.propertyNames();e.hasMoreElements();) {
String key=(String)e.nextElement();
// p.getProperty("Params_x.TAN2StepParY.ParTAN2StepZ.TAN2StepParamsX_z.*")
if (key.startsWith("Params")) {
String subkey=key.substring(key.indexOf('.')+1);
if (subkey.startsWith("TAN2StepPar")) {
// willuhn 2011-05-13 Wir brauchen die Segment-Version, weil mittlerweile TAN-Verfahren
// mit identischer Sicherheitsfunktion in unterschiedlichen Segment-Versionen auftreten koennen
// Wenn welche mehrfach vorhanden sind, nehmen wir nur das aus der neueren Version
int segVersion = Integer.parseInt(subkey.substring(11,12));
subkey=subkey.substring(subkey.indexOf('.')+1);
if (subkey.startsWith("ParTAN2Step") &&
subkey.endsWith(".secfunc"))
{
// willuhn 2011-06-06 Segment-Versionen ueberspringen, die groesser als die max. zulaessige sind
if (maxAllowedVersion > 0 && segVersion > maxAllowedVersion)
{
HBCIUtils.log("skipping segversion " + segVersion + ", larger than allowed version " + maxAllowedVersion, HBCIUtils.LOG_DEBUG);
continue;
}
String secfunc=p.getProperty(key);
// willuhn 2011-05-13 Checken, ob wir das Verfahren schon aus einer aktuelleren Segment-Version haben
Properties prev = tanMethodsBank.get(secfunc);
if (prev != null)
{
// Wir haben es schonmal. Mal sehen, welche Versionsnummer es hat
int prevVersion = Integer.parseInt(prev.getProperty("segversion"));
if (prevVersion > segVersion)
{
HBCIUtils.log("found another twostepmech " + secfunc + " in segversion " + segVersion + ", already have one in segversion " + prevVersion + ", ignoring segversion " + segVersion, HBCIUtils.LOG_DEBUG);
continue;
}
}
Properties entry=new Properties();
// willuhn 2011-05-13 Wir merken uns die Segment-Version in dem Zweischritt-Verfahren
// Daran koennen wir erkennen, ob wir ein mehrfach auftretendes
// Verfahren ueberschreiben koennen oder nicht.
entry.put("segversion",Integer.toString(segVersion));
String paramHeader=key.substring(0,key.lastIndexOf('.'));
// Params_x.TAN2StepParY.ParTAN2StepZ.TAN2StepParamsX_z
// alle properties durchlaufen und alle suchen, die mit dem
// paramheader beginnen, und die entsprechenden werte im
// entry abspeichern
for (Enumeration e2=p.propertyNames();e2.hasMoreElements();) {
String key2=(String)e2.nextElement();
if (key2.startsWith(paramHeader+".")) {
int dotPos=key2.lastIndexOf('.');
entry.setProperty(
key2.substring(dotPos+1),
p.getProperty(key2));
}
}
// diesen mechanismus abspeichern
tanMethodsBank.put(secfunc,entry);
}
}
}
}
}
}
/**
* @see org.kapott.hbci.passport.AbstractHBCIPassport#onDialogEvent(org.kapott.hbci.dialog.DialogEvent, org.kapott.hbci.dialog.DialogContext)
*/
@Override
public void onDialogEvent(DialogEvent event, DialogContext ctx)
{
super.onDialogEvent(event, ctx);
if (event == DialogEvent.MSG_CREATED)
{
this.checkSCARequest(ctx);
}
else if (event == DialogEvent.MSG_SENT)
{
this.checkInvalidPIN(ctx);
this.check3920(ctx);
this.check3072(ctx);
this.checkSCAResponse(ctx);
}
else if (event == DialogEvent.JOBS_CREATED)
{
this.patchMessagesFor2StepMethods(ctx);
}
}
/**
* Prueft, ob es Anzeichen fuer eine falsche PIN gibt.
* Wenn ja, geben wir per Callback Bescheid.
* @param ctx der Kontext.
*/
private void checkInvalidPIN(DialogContext ctx)
{
// Falsche PIN kann es bei einem anonymen Dialog nicht geben
if (ctx.isAnonymous())
return;
HBCIMsgStatus status = ctx.getMsgStatus();
if (status == null)
return;
if (status.isOK())
return;
HBCIRetVal ret = status.getInvalidPINCode();
if (ret == null)
return;
HBCIUtils.log("PIN-Fehler erkannt, Meldung der Bank: " + ret.code + ": " + ret.text, HBCIUtils.LOG_INFO);
this.clearPIN();
// Aufrufer informieren, dass falsche PIN eingegeben wurde (um evtl. PIN aus Puffer zu löschen, etc.)
HBCIUtilsInternal.getCallback().callback(this,HBCICallback.WRONG_PIN,"*** invalid PIN entered",HBCICallback.TYPE_TEXT,new StringBuffer());
}
/**
* Prueft, ob im Response der Code 3920 enthalten ist.
* Dort liefert die Bank neue Zweischritt-Verfahren.
* @param ctx der Kontext.
*/
private void check3920(DialogContext ctx)
{
// In einem anonymen Dialog koennen keine 3920 enthalten sein, da die User-spezifisch sind
if (ctx.isAnonymous())
return;
HBCIMsgStatus status = ctx.getMsgStatus();
if (status == null)
return;
////////////////////////////////////////////////////
// TAN-Verfahren ermitteln und uebernehmen
final List<HBCIRetVal> recvList = KnownReturncode.W3920.searchReturnValues(status);
if (recvList == null || recvList.isEmpty())
return;
HBCIUtils.log("autosecfunc: found " + recvList.size() + " 3920s in response, detect allowed twostep secmechs", HBCIUtils.LOG_DEBUG);
final List<String> oldList = new ArrayList<String>(this.tanMethodsUser);
final Set<String> newSet = new HashSet<String>(); // Damit doppelte nicht doppelt in der Liste landen
for (HBCIRetVal r:recvList)
{
if (r.params != null)
newSet.addAll(Arrays.asList(r.params));
}
final List<String> newList = new ArrayList<String>(newSet);
if (newList.size() > 0 && !newList.equals(oldList))
{
this.tanMethodsUser.clear();
this.tanMethodsUser.addAll(newList);
HBCIUtils.log("autosecfunc: found 3920 in response - updated list of allowed twostepmechs - old: " + oldList + ", new: " + this.tanMethodsUser, HBCIUtils.LOG_DEBUG);
}
//
////////////////////////////////////////////////////
if (this.isAnonymous())
return;
////////////////////////////////////////////////////
// Dialog neu starten, wenn das Verfahren sich geaendert hat
// aktuelle secmech merken und neue auswählen (basierend auf evtl. gerade neu empfangenen informationen (3920s))
final String oldMethod = this.tanMethod;
final String newMethod = this.getCurrentTANMethod(true);
if (Objects.equals(oldMethod,newMethod))
return;
// Wenn es eine Synchronisierung ist, lassen wir das Repeat weg.
// Die Postbank kommt nicht damit klar, wenn man eine neue Synchronisierung mit dem anderen TAN-Verfahren direkt hinterher sendet
if (ctx.getDialogInit().getTemplate() == KnownDialogTemplate.SYNC)
return;
// wenn sich das ausgewählte secmech geändert hat, müssen wir
// einen dialog-restart fordern, weil während eines dialoges
// das secmech nicht gewechselt werden darf
HBCIUtils.log("autosecfunc: after this dialog-init we had to change selected pintan method from " + oldMethod + " to " + newMethod + ", so a restart of this dialog is needed", HBCIUtils.LOG_DEBUG);
HBCIUtils.log("Derzeitiges TAN-Verfahren aktualisiert, starte Dialog neu", HBCIUtils.LOG_INFO);
ctx.setRepeat(true);
//
////////////////////////////////////////////////////
}
/**
* Prueft, ob im Response der Code 3072 enthalten ist.
* Dort liefert die Bank ggf. aktualisierte Zugangsdaten.
* @param ctx der Kontext.
*/
private void check3072(DialogContext ctx)
{
// Neue Zugangsdaten kann es anonym nicht geben.
if (ctx.isAnonymous())
return;
HBCIMsgStatus status = ctx.getMsgStatus();
if (status == null)
return;
HBCIRetVal[] seg = status.segStatus != null ? status.segStatus.getWarnings() : null;
if (seg == null)
return;
final HBCIRetVal ret = KnownReturncode.W3072.searchReturnValue(seg);
if (ret == null)
return;
String newCustomerId = "";
String newUserId = "";
int l2=ret.params.length;
if(l2>0) {
newUserId = ret.params[0];
newCustomerId = ret.params[0];
}
if(l2>1) {
newCustomerId = ret.params[1];
}
if(l2>0) {
HBCIUtils.log("autosecfunc: found 3072 in response - change user id", HBCIUtils.LOG_DEBUG);
// Aufrufer informieren, dass UserID und CustomerID geändert wurde
StringBuffer retData=new StringBuffer();
retData.append(newUserId+"|"+newCustomerId);
HBCIUtilsInternal.getCallback().callback(this,HBCICallback.USERID_CHANGED,"*** User ID changed",HBCICallback.TYPE_TEXT,retData);
}
}
/**
* Prueft, ob die Dialog-Initialisierung um ein HKTAN erweitert werden muss.
* @param ctx der Kontext.
*/
private void checkSCARequest(DialogContext ctx)
{
HBCIUtils.log("check SCA request",HBCIUtils.LOG_DEBUG);
final SCARequest sca = this.getSCARequest(ctx);
if (sca == null)
{
HBCIUtils.log("no SCA request for this context, skipping check",HBCIUtils.LOG_DEBUG);
return;
}
Integer step = (Integer) ctx.getMeta().get(CACHE_KEY_SCA_STEP);
// Wir haben noch kein HKTAN gesendet. Dann senden wir jetzt Schritt 1
if (step == null)
{
step = 1;
ctx.getMeta().put(CACHE_KEY_SCA_STEP,step);
}
final Variant variant = sca.getVariant();
KnownTANProcess tp = KnownTANProcess.get(variant,step.intValue());
if (tp == KnownTANProcess.PROCESS2_STEP2)
{
// Checken, ob wir Decoupled verwenden. In dem Fall
// TAN-Prozess von "2" auf "S" ändern
final Properties secmechInfo = this.getCurrentSecMechInfo();
final HHDVersion hhd = HHDVersion.find(secmechInfo);
final String segversion = secmechInfo != null ? secmechInfo.getProperty("segversion") : null;
HBCIUtils.log("detected HHD version: " + hhd,HBCIUtils.LOG_DEBUG);
if (hhd != null && hhd.getType() == Type.DECOUPLED)
{
Integer i = null;
try
{
i = Integer.parseInt(segversion);
}
catch (Exception e) {}
if (i != null && i.intValue() >= 7)
{
HBCIUtils.log("switching TAN process from " + tp + " to " + KnownTANProcess.PROCESS2_STEPS,HBCIUtils.LOG_DEBUG);
tp = KnownTANProcess.PROCESS2_STEPS;
}
}
}
final int version = sca.getVersion();
// wir fuegen die Daten des HKTAN ein
final HBCIKernelImpl k = ctx.getKernel();
final String prefix = "TAN2Step" + version;
k.rawSet(prefix,"requested"); // forcieren, dass das Segment mit gesendet wird - auch wenn es eigentlich optional ist
k.rawSet(prefix + ".process",tp.getCode());
String segcode = sca.getTanReference();
if (Feature.PINTAN_SEGCODE_STRICT.isEnabled())
{
if (step == 2)
segcode = "";
}
HBCIUtils.log("creating HKTAN for SCA [process : " + tp + ", order code: " + segcode + ", step: " + step + "]",HBCIUtils.LOG_DEBUG);
k.rawSet(prefix + ".ordersegcode",segcode);
k.rawSet(prefix + ".OrderAccount.bic","");
k.rawSet(prefix + ".OrderAccount.iban","");
k.rawSet(prefix + ".OrderAccount.number","");
k.rawSet(prefix + ".OrderAccount.subnumber","");
k.rawSet(prefix + ".OrderAccount.KIK.blz","");
k.rawSet(prefix + ".OrderAccount.KIK.country","");
k.rawSet(prefix + ".orderhash",(variant == Variant.V2) ? "" : ("B00000000"));
k.rawSet(prefix + ".orderref",(step == 2) ? (String) this.getPersistentData(KEY_PD_ORDERREF) : "");
k.rawSet(prefix + ".notlasttan",(tp == KnownTANProcess.PROCESS1 || step == 2) ? "N" : ""); // Darf nur bei TAN-Prozess 1, 2 und S belegt sein
k.rawSet(prefix + ".challengeklass",(variant == Variant.V2) ? "" : "99");
k.rawSet(prefix + ".tanmedia",sca.getTanMedia());
}
/**
* Erzeugt einen passenden SCA-Request fuer die Dialog-Initialisierung.
* @param ctx der Context.
* @return der SCA-Request oder NULL, wenn keiner noetig ist.
*/
private SCARequest getSCARequest(DialogContext ctx)
{
HBCIUtils.log("create new SCA request",HBCIUtils.LOG_DEBUG);
final RawHBCIDialog init = ctx.getDialogInit();
if (init == null)
{
HBCIUtils.log("have no dialog init, skip SCA request creation",HBCIUtils.LOG_DEBUG);
return null;
}
// Checken, ob es ein Dialog, in dem eine SCA gemacht werden soll
if (!KnownDialogTemplate.LIST_SEND_SCA.contains(init.getTemplate()))
{
HBCIUtils.log("dialog (" + init.getTemplate() + ") not in list of SCA dialogs, skip SCA request creation",HBCIUtils.LOG_DEBUG);
return null;
}
if (Feature.PINTAN_INIT_SKIPONESTEPSCA.isEnabled())
{
// Wenn wir ein Einschritt-TAN-Verfahren haben und es die autorisierte Initialisierung ist,
// dann senden wir das Init ohne HKTAN. Im anonymen Init haben wir ja schon per HKTAN mitgeteilt, dass
// wir SCA koennen. Jetzt gehts uns nur darum, die TAN-Verfahren per 3920 zu kriegen
// Ist nach Abstimmung mit einem HBCI-Server-Experten so legitim und wird von allen so gemacht:
// Bei Dialog-Init Verfahren 999 nehmen und ohne HKTAN senden
// Laut https://homebanking-hilfe.de/forum/topic.php?p=149751#real149751 akzeptiert die DKB kein Sync mit 999
//
// Dialog HKTAN weglassen?
// ---------------------------------------------------------
// DialogInitAnon nein
// DialogInit mit Einschritt-TAN ja
// DialogInit mit Zweischritt-TAN nein
// Sync nein
// Sync mit aktiviertem Init-Flip ja
final KnownDialogTemplate tpl = init.getTemplate();
final String currentTanMethod = this.getCurrentTANMethod(false);
if (!ctx.isAnonymous() && Objects.equals(TanMethod.ONESTEP.getId(),currentTanMethod) &&
(tpl == KnownDialogTemplate.INIT || (Feature.INIT_FLIP_USER_INST.isEnabled() && tpl == KnownDialogTemplate.SYNC)))
{
HBCIUtils.log("skipping HKTAN for dialog init [anon: " + ctx.isAnonymous() + ", current tan method: " + currentTanMethod + ", tpl: " + tpl + "]",HBCIUtils.LOG_DEBUG);
return null;
}
}
// HKTAN-Version und Prozessvariante ermitteln - kann NULL sein
final int segversionDefault = 6;
final Properties secmechInfo = this.getCurrentSecMechInfo();
final int hktanVersion = secmechInfo != null ? NumberUtil.parseInt(secmechInfo.getProperty("segversion"),segversionDefault) : segversionDefault;
// Erst ab HKTAN 6 noetig. Die Bank unterstuetzt es scheinbar noch nicht
// Siehe B.4.3.1 - Wenn die Bank HITAN < 6 geschickt hat, dann kann sie keine SCA
if (hktanVersion < 6)
{
HBCIUtils.log("HKTAN version < 6, skip SCA request creation",HBCIUtils.LOG_DEBUG);
return null;
}
final SCARequest r = init.createSCARequest(secmechInfo,hktanVersion);
if (r == null)
{
HBCIUtils.log("have no SCA request, skip SCA request creation",HBCIUtils.LOG_DEBUG);
return null;
}
if (r.getTanReference() == null)
{
// Beim Bezug auf das Segment schicken wir per Default "HKIDN". Gemaess Kapitel B.4.3.1 muss das Bezugssegment aber
// bei PIN/TAN-Management-Geschaeftsvorfaellen mit dem GV des jeweiligen Geschaeftsvorfalls belegt werden.
// Daher muessen wir im Payload schauen, ob ein entsprechender Geschaeftsvorfall enthalten ist.
// Wird muessen nur nach HKPAE, HKTAB schauen - das sind die einzigen beiden, die wir unterstuetzen
String segcode = "HKIDN";
HBCIDialog payload = ctx.getDialog();
if (payload != null)
{
final HBCIMessageQueue queue = payload.getMessageQueue();
for (String code:Arrays.asList("HKPAE","HKTAB")) // Das sind GVChangePIN und GVTANMediaList
{
if (queue.findTask(code) != null)
{
segcode = code;
break;
}
}
}
r.setTanReference(segcode);
}
if (r.getTanMedia() == null)
r.setTanMedia(this.getTanMedia(hktanVersion));
return r;
}
/**
* Prueft das Response auf Vorhandensein eines HITAN bzw Code.
* Hinweis: Wir haben das ganze HKTAN-Handling derzeit leider doppelt. Einmal fuer die Dialog-Initialisierung und einmal fuer
* die Nachrichten mit den eigentlichen Geschaeftsvorfaellen (in patchMessagesFor2StepMethods). Wenn auch HBCIDialog#doJobs irgendwann
* auf die neuen RawHBCIDialoge umgestellt ist, kann eigentlich patchMessagesFor2StepMethods entfallen.
* @param ctx der Kontext.
*/
private void checkSCAResponse(DialogContext ctx)
{
HBCIUtils.log("check SCA response",HBCIUtils.LOG_DEBUG);
final RawHBCIDialog init = ctx.getDialogInit();
if (init == null)
{
HBCIUtils.log("no init dialog, skip SCA response analysis",HBCIUtils.LOG_DEBUG);
return;
}
// Checken, ob es ein Dialog, in dem eine SCA gemacht werden soll
if (!KnownDialogTemplate.LIST_SEND_SCA.contains(init.getTemplate()))
{
HBCIUtils.log("dialog (" + init.getTemplate() + ") not in list of SCA dialogs, skip SCA response analysis",HBCIUtils.LOG_DEBUG);
return;
}
// Wenn wir noch in der anonymen Dialog-Initialisierung sind, interessiert uns das nicht.
if (ctx.isAnonymous() || this.isAnonymous())
{
HBCIUtils.log("anonymous dialog, skip SCA response analysis",HBCIUtils.LOG_DEBUG);
ctx.getMeta().remove(CACHE_KEY_SCA_STEP);
return;
}
Integer scaStep = (Integer) ctx.getMeta().get(CACHE_KEY_SCA_STEP);
// Wenn wir keinen SCA-Request gesendet haben, brauchen wir auch nicht nach dem Response suchen
if (scaStep == null)
{
HBCIUtils.log("no sca request sent, skip SCA response analysis",HBCIUtils.LOG_DEBUG);
return;
}
// Ohne Status brauchen wir es gar nicht erst versuchen
final HBCIMsgStatus status = ctx.getMsgStatus();
if (status == null)
{
HBCIUtils.log("no message status received, skip SCA response analysis",HBCIUtils.LOG_DEBUG);
return;
}
// Bank hat uns eine Ausnahme erteilt - wir brauchen keine TAN
if (status.segStatus != null && (KnownReturncode.W3076.searchReturnValue(status.segStatus.getWarnings()) != null || KnownReturncode.W3076.searchReturnValue(status.globStatus.getWarnings()) != null))
{
HBCIUtils.log("found status code 3076, no SCA required",HBCIUtils.LOG_DEBUG);
ctx.getMeta().remove(CACHE_KEY_SCA_STEP);
return;
}
// Schritt 1: Wir haben eine HKTAN-Anfrage gesendet. Mal schauen, ob die Bank tatsaechlich eine TAN will
if (scaStep.intValue() == 1)
{
HBCIUtils.log("HKTAN step 1 for SCA sent, checking for HITAN response [step: " + scaStep + "]",HBCIUtils.LOG_DEBUG);
Properties props = ParameterFinder.find(status.getData(),"TAN2StepRes*.");
if (props == null || props.size() == 0)
{
HBCIUtils.log("no hitan reponse data found",HBCIUtils.LOG_DEBUG);
return; // Wir haben kein HITAN
}
// HITAN erhalten - Daten uebernehmen
HBCIUtils.log("SCA HITAN response found, triggering TAN request",HBCIUtils.LOG_DEBUG);
final String challenge = props.getProperty("challenge");
if (challenge != null && challenge.length() > 0)
this.setPersistentData(KEY_PD_CHALLENGE,challenge);
final String hhdUc = props.getProperty("challenge_hhd_uc");
if (hhdUc != null && hhdUc.length() > 0)
this.setPersistentData(KEY_PD_HHDUC,hhdUc);
final String orderref = props.getProperty("orderref");
if (orderref != null && orderref.length() > 0)
this.setPersistentData(KEY_PD_ORDERREF,orderref);
/////////////////////////////////////////////////////
// Dialog-Init wiederholen, um den zweiten HKTAN-Schritt durchzufuehren
// OK, wir senden jetzt das finale HKTAN. Die Message darf nichts anderes enthalten. Daher aendern wir das Template.
ctx.getMeta().put(CACHE_KEY_SCA_STEP,2);
ctx.getDialogInit().setTemplate(KnownDialogTemplate.INIT_SCA);
ctx.setRepeat(true);
//
/////////////////////////////////////////////////////
return;
}
if (scaStep.intValue() == 2)
{
ctx.getMeta().remove(CACHE_KEY_SCA_STEP); // Geschafft
HBCIUtils.log("HKTAN step 2 for SCA sent, checking for HITAN response [step: " + scaStep + "]",HBCIUtils.LOG_DEBUG);
Properties props = ParameterFinder.find(status.getData(),"TAN2StepRes*.");
if (props.size() > 0)
HBCIUtils.log("final SCA HITAN response found",HBCIUtils.LOG_DEBUG);
}
}
/**
* @see org.kapott.hbci.passport.AbstractHBCIPassport#getCommInstance()
*/
public Comm getCommInstance()
{
return Comm.getInstance("PinTan",this);
}
/**
* @see org.kapott.hbci.passport.HBCIPassport#isSupported()
*/
public boolean isSupported()
{
final Properties bpd = this.getBPD();
if (bpd == null)
return true;
// Wir triggern hier nur einmal die Auswahl des TAN-Verfahrens
this.getCurrentTANMethod(true);
return true;
}
/**
* Liefert true, wenn das TAN-Einschritt-Verfahren unterstuetzt wird.
* @return true, wenn das TAN-Einschritt-Verfahren unterstuetzt wird.
*/
private boolean isOneStepAllowed()
{
final Properties bpd = this.getBPD();
if (bpd == null)
return true;
return ParameterFinder.findAll(bpd,ParameterFinder.Query.BPD_PINTAN_CAN1STEP).containsValue("J");
}
/**
* Für das Decoupled Verfahren, liefert die minimale Zeit vor dem ersten refresh.
* @return Die minimale Zeit vor dem ersten Decoupled refresh.
*/
public Integer getMinimumTimeBeforeFirstDecoupledRefresh() {
final Properties bpd = this.getBPD();
if (bpd == null)
return null;
return HBCIUtilsInternal.getIntegerProperty(bpd, Query.BPD_DECOUPLED_TIME_BEFORE_FIRST_STATUS_REQUEST, false);
}
/**
* Für das Decoupled Verfahren, liefert die minimale Zeit vor weiteren refreshes.
* @return Die minimale Zeit vor weiteren Decoupled refreshes.
*/
public Integer getMinimumTimeBeforeNextDecoupledRefresh() {
final Properties bpd = this.getBPD();
if (bpd == null)
return null;
return HBCIUtilsInternal.getIntegerProperty(bpd, Query.BPD_DECOUPLED_TIME_BEFORE_NEXT_STATUS_REQUEST, false);
}
/**
* Für das Decoupled Verfahren, liefert die maximale Anzahl von refreshes.
* @return Die maximale Anzahl von Decoupled refreshes.
*/
public Integer getDecoupledMaxRefreshes() {
final Properties bpd = this.getBPD();
if (bpd == null)
return null;
return HBCIUtilsInternal.getIntegerProperty(bpd, Query.BPD_DECOUPLED_MAX_STATUS_REQUESTS, true);
}
/** Kann vor <code>new HBCIHandler()</code> aufgerufen werden, um zu
* erzwingen, dass die Liste der unterstützten PIN/TAN-Sicherheitsverfahren
* neu vom Server abgeholt wird und evtl. neu vom Nutzer abgefragt wird. */
public void resetSecMechs()
{
this.tanMethodsUser=new ArrayList<String>();
this.tanMethod=null;
this.tanMethodAutoSelected=false;
}
/**
* Legt das aktuelle TAN-Verfahren fest.
* @param method das aktuelle TAN-Verfahren.
*/
public void setCurrentTANMethod(String method)
{
this.tanMethod=method;
}
/**
* Liefert das aktuelle TAN-Verfahren.
* @param recheck true, wenn die gespeicherte Auswahl auf Aktualitaet und Verfuegbarkeit geprueft werden soll.
* Die Funktion kann in dem Fall einen Callback ausloesen, wenn mehrere Optionen zur Wahl stehen.
* @return das TAN-Verfahren.
*/
public String getCurrentTANMethod(boolean recheck)
{
// Wir haben ein aktuelles TAN-Verfahren und eine Neupruefung ist nicht noetig
if (this.tanMethod != null && !recheck)
return this.tanMethod;
boolean auto = Feature.PINTAN_INIT_AUTOMETHOD.isEnabled();
HBCIUtils.log("(re)checking selected pintan method using " + (auto ? "auto-determine" : "ask") + " strategy", HBCIUtils.LOG_DEBUG);
if (auto)
return this.determineTanMethod();
return this.askForTanMethod();
}
/**
* Liefert das aktuelle TAN-Verfahren.
* Hierbei versucht HBCI4Java das Verfahren erst automatisch zu ermitteln, bevor es den User fragt.
* @return das TAN-Verfahren.
*/
private String determineTanMethod()
{
// Wenn der User noch keine TAN-Verfahren hat, bleibt und als Option nur 999 - also Einschritt-Verfahren, um an den 3920
// mit den zulaessigen Verfahren zu kommen. Wir pruefen hier gar nicht erst per "isOneStepAllowed", ob die Bank ein
// Einschritt-Verfahren anbietet, weil wir gar keine andere Option haben
// Update 2019-11-02: Geht bei der Postbank leider nicht. Die erlauben kein Einschritt-Vefahren und wollen daher
// tatsaechlich bereits beim Abruf der verfuegbaren TAN-Verfahren ein Zweischritt-Verfahren haben. Siehe
// https://homebanking-hilfe.de/forum/topic.php?p=151725#real151725
if (this.tanMethodsUser.size() == 0 && this.isOneStepAllowed())
return TanMethod.ONESTEP.getId();
/////////////////////////////////////////
// Die Liste der verfuegbaren Optionen ermitteln
final List<TanMethod> userList = new ArrayList<TanMethod>();
final List<TanMethod> bankList = new ArrayList<TanMethod>();
String[] secfuncs= this.tanMethodsBank.keySet().toArray(new String[this.tanMethodsBank.size()]);
Arrays.sort(secfuncs);
for (String secfunc:secfuncs)
{
final Properties entry = this.tanMethodsBank.get(secfunc);
final TanMethod m = new TanMethod(secfunc,entry.getProperty("name"));
if (this.tanMethodsUser.contains(secfunc))
userList.add(m);
bankList.add(m);
}
//
/////////////////////////////////////////
HBCIUtils.log("tan methods of institute: " + bankList, HBCIUtils.LOG_DEBUG);
HBCIUtils.log("tan methods for user: " + userList, HBCIUtils.LOG_DEBUG);
/////////////////////////////////////////
// Auswahl treffen
if (userList.size() == 0)
{
if (this.isOneStepAllowed())
{
final TanMethod m = TanMethod.ONESTEP;
HBCIUtils.log("no tan method available for user, using: " + m,HBCIUtils.LOG_DEBUG);
// Wir speichern das TAN-Verfahren nicht, das kann unmoeglich das finale Verfahren sein.
return m.getId();
}
else
{
// Sonderfall HBCI4Java Testserver. Der liefert gar keine TAN-Verfahren
if (bankList.size() == 0)
{
final TanMethod m = TanMethod.ONESTEP;
HBCIUtils.log("no tan method available for bank, using: " + m,HBCIUtils.LOG_DEBUG);
// Wir speichern das TAN-Verfahren nicht, das kann unmoeglich das finale Verfahren sein.
return m.getId();
}
// Das ist sicher die Postbank. Wir haben noch kein Verfahren per 3920 erhalten, die Bank erlaubt
// aber nicht, diese per Einschritt-Verfahren abzurufen. Also muessen wir den User bitten, die Auswahl
// aus der in den BPD verfuegbaren Verfahren zu treffen. Auch wenn diese Liste dann Eintraege enthaelt,
// die fuer den User u.U. gar nicht verfuegbar sind.
HBCIUtils.log("have no methods for user and institute doesn't allow one step method - asking user. available methods on institute: " + bankList,HBCIUtils.LOG_DEBUG);
this.setCurrentTANMethod(this.chooseTANMethod(bankList));
HBCIUtils.log("selected pintan method by user: " + tanMethod, HBCIUtils.LOG_INFO);
return this.tanMethod;
}
}
if (userList.size() == 1)
{
final TanMethod m = userList.get(0);
HBCIUtils.log("only one tan method available for user: " + m,HBCIUtils.LOG_DEBUG);
this.setCurrentTANMethod(m.getId()); // Ueberschreibt bei der Gelegenheit gleich die letzte Version
return this.tanMethod;
}
// Wir haben mehrere zur Auswahl. Checken, ob wir schon eins hatten. Und wenn ja, ob es
// immer noch verfuegbar ist. Wenn ja, liefern wir einfach das zurueck. Wenn es nicht
// mehr verfuegbar ist, muessen wir den User neu fragen.
boolean reuse = this.tanMethod != null && userList.stream().anyMatch(m -> Objects.equals(m.getId(),this.tanMethod));
if (reuse)
return this.tanMethod;
// User fragen
HBCIUtils.log("asking user what tan method to use. available methods: " + userList,HBCIUtils.LOG_DEBUG);
this.setCurrentTANMethod(this.chooseTANMethod(userList));
HBCIUtils.log("selected pintan method by user: " + tanMethod, HBCIUtils.LOG_INFO);
return this.tanMethod;
}
/**
* Liefert das aktuelle TAN-Verfahren.
* Fragt hierbei im Zweifelsfall eher den User anstatt es selbst herauszufinden.
* @return das TAN-Verfahren.
*/
private String askForTanMethod()
{
/////////////////////////////////////////
// Die Liste der verfuegbaren Optionen ermitteln
final List<TanMethod> options = new ArrayList<TanMethod>();
final List<TanMethod> fallback = new ArrayList<TanMethod>();
// Einschritt-Verfahren optional hinzufuegen
if (this.isOneStepAllowed())
{
TanMethod m = TanMethod.ONESTEP;
// Nur hinzufuegen, wenn wir entweder gar keine erlaubten haben oder es in der Liste der erlaubten drin ist
if (this.tanMethodsUser.size() == 0 || this.tanMethodsUser.contains(m.getId()))
options.add(m);
}
// Die Zweischritt-Verfahren hinzufuegen
String[] secfuncs= this.tanMethodsBank.keySet().toArray(new String[this.tanMethodsBank.size()]);
Arrays.sort(secfuncs);
for (String secfunc:secfuncs)
{
final Properties entry = this.tanMethodsBank.get(secfunc);
final TanMethod m = new TanMethod(secfunc,entry.getProperty("name"));
if (this.tanMethodsUser.size() == 0 || this.tanMethodsUser.contains(secfunc))
{
options.add(m);
}
fallback.add(m);
}
//
/////////////////////////////////////////
/////////////////////////////////////////
// 0 Optionen verfuegbar
// Wir haben keine Optionen gefunden
if (options.size() == 0)
{
// wir lassen das hier mal noch auf true stehen, weil das bestimmt noch nicht final war. Schliesslich basierte die
// Auswahl des Verfahrens nicht auf den fuer den User freigeschalteten Verfahren sondern nur den allgemein von der
// Bank unterstuetzten
this.tanMethodAutoSelected = true;
HBCIUtils.log("autosecfunc: no information about allowed pintan methods available", HBCIUtils.LOG_INFO);
// Wir haben keine TAN-Verfahren, die fuer den User per 3920 zugelassen sind.
// Wir schauen mal, ob die Bank wenigstens welche in HIPINS gemeldet hat. Wenn ja, dann soll der
// User eins von dort auswaehlen. Ob das dann aber ein erlaubtes ist, wissen wir nicht.
if (fallback.size() > 0)
{
HBCIUtils.log("autosecfunc: have some pintan methods in HIPINS, asking user, what to use from: " + fallback, HBCIUtils.LOG_INFO);
final String selected = this.chooseTANMethod(fallback);
this.setCurrentTANMethod(selected);
HBCIUtils.log("autosecfunc: manually selected pintan method from HIPINS " + tanMethod, HBCIUtils.LOG_DEBUG);
}
else
{
TanMethod m = TanMethod.ONESTEP;
HBCIUtils.log("autosecfunc: absolutly no information about allowed pintan methods available, fallback to " + m, HBCIUtils.LOG_WARN);
this.setCurrentTANMethod(m.getId());
}
return this.tanMethod;
}
//
/////////////////////////////////////////
/////////////////////////////////////////
// 1 Option verfuegbar
if (options.size() == 1)
{
final TanMethod m = options.get(0);
HBCIUtils.log("autosecfunc: there is only one pintan method supported - choosing this automatically: " + m,HBCIUtils.LOG_DEBUG);
if (this.tanMethod != null && !this.tanMethod.equals(m.getId()))
HBCIUtils.log("autosecfunc: auto-selected method differs from current: " + this.tanMethod, HBCIUtils.LOG_DEBUG);
this.setCurrentTANMethod(m.getId());
this.tanMethodAutoSelected = true;
return this.tanMethod;
}
//
/////////////////////////////////////////
/////////////////////////////////////////
// Mehrere Optionen verfuegbar
// Checken, was gerade eingestellt ist.
if (this.tanMethod != null)
{