-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEsteidAPI.cpp
1019 lines (858 loc) · 29 KB
/
EsteidAPI.cpp
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
/*
* esteid-browser-plugin - a browser plugin for Estonian EID card
*
* Copyright (C) 2010 Estonian Informatics Centre
* Copyright (C) 2010 Smartlink OÜ
*
* 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
*/
#include <iomanip>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#ifdef USE_OPENSSL
#include <openssl/sha.h>
#endif
#ifdef SUPPORT_OLD_APIS
#include "Base64.h"
#include "converter.h"
#include "CompatAPIs.h"
#endif
#include "JSObject.h"
#include "variant_list.h"
#include "DOM/Document.h"
#include "DOM/Window.h"
#include "global/config.h"
#ifdef _WIN32
#include "Win/WindowsUI.h"
#else
#ifdef __APPLE__
#include "Mac/MacUI.h"
#else
#include "X11/GtkUI.h"
#endif
#endif
#include "EsteidAPI.h"
#include "CertificateAPI.h"
#include "PersonalDataAPI.h"
#include "JSUtil.h"
#include "debug.h"
#include "esteid-config.h"
#include "urlparser.h"
/* UI Messages */
#define MSG_SETTINGS _("Allow")
#define MSG_SITEACCESS _("This site is trying to obtain access to your ID card.")
#define MSG_INSECURE _("Access to ID card was denied because the connection to the server is not secure.")
#define REGISTER_METHOD(a) JS_REGISTER_METHOD(EsteidAPI, a)
#define REGISTER_RO_PROPERTY(a) JS_REGISTER_RO_PROPERTY(EsteidAPI, a)
using namespace Converter;
EsteidAPI::EsteidAPI(FB::BrowserHostPtr host, const std::string& mimetype) :
m_host(host),
m_pageURL(pageURL()),
m_settingsCallback(new SettingsCallback(host, *this)),
m_closeCallback(new CloseCallback(host, *this)),
m_service(CardService::getInstance()),
m_mimeType(mimetype),
m_uiCallback(new UICallback(*this))
{
ESTEID_DEBUG("MIME type: %s", m_mimeType.c_str());
#ifdef HAVE_LIBINTL_H
bindtextdomain("esteid-browser-plugin", ESTEID_LOCALEDIR);
textdomain("esteid-browser-plugin");
#endif
/* Load JavaScript code to be evaluated in browser */
#include "EstEIDNotificationBar.js"
REGISTER_METHOD(getVersion);
REGISTER_METHOD(signAsync);
REGISTER_METHOD(showSettings);
registerEvent("onCardInserted");
registerEvent("onCardRemoved");
registerEvent("onReadersChanged");
/* FIXME: Those will be catched by firebreath itself for
NPAPI plugins, but how about ActiveX?
REGISTER_METHOD(addEventListener);
REGISTER_METHOD(removeEventListener);
*/
REGISTER_RO_PROPERTY(authCert);
REGISTER_RO_PROPERTY(signCert);
REGISTER_RO_PROPERTY(personalData);
REGISTER_RO_PROPERTY(errorCode);
REGISTER_RO_PROPERTY(errorMessage);
#ifdef SUPPORT_OLD_APIS
if(m_mimeType == "application/x-digidoc") {
registerMethod("getCertificates",
make_method(this, &EsteidAPI::getCertificatesSK));
registerMethod("sign", make_method(this, &EsteidAPI::signSK));
} else if(m_mimeType == "application/x-idcard-plugin") {
registerMethod("getCertificates",
make_method(this, &EsteidAPI::getCertificatesMoz));
registerMethod("sign", make_method(this, &EsteidAPI::sign));
}
else {
REGISTER_METHOD(getCertificates);
registerMethod("sign", boost::bind(sign_method_wrapper(), this, _1));
}
REGISTER_RO_PROPERTY(version); // SK betaplugin
REGISTER_METHOD(getCertificate); // SK betaplugin
REGISTER_METHOD(getInfo);
REGISTER_METHOD(getSigningCertificate);
REGISTER_METHOD(getSignedHash);
REGISTER_RO_PROPERTY(selectedCertNumber);
REGISTER_METHOD(prepare);
REGISTER_METHOD(finalize);
REGISTER_METHOD(isActive);
#endif
/* Use platform specific UI */
#ifdef _WIN32
ESTEID_DEBUG("Trying to load WindowsUI");
m_UI = boost::shared_ptr<PluginUI>(new WindowsUI(m_uiCallback));
#else
#ifdef __APPLE__
ESTEID_DEBUG("Trying to load MacUI");
m_UI = boost::shared_ptr<PluginUI>(new MacUI(m_uiCallback));
#else
ESTEID_DEBUG("Trying to load GtkUI");
m_UI = boost::shared_ptr<PluginUI>(new GtkUI(m_uiCallback));
#endif
#endif
#if 0
/* Die if UI initialization fails */
if(!m_UI)
throw FB::script_error("Unable to load plugin user interface");
#endif
m_service->addObserver(this);
}
EsteidAPI::~EsteidAPI()
{
ESTEID_DEBUG_SCOPE();
m_service->removeObserver(this);
}
void EsteidAPI::setWindow(FB::PluginWindow* win)
{
m_UI->setWindow(win);
}
bool EsteidAPI::IsLocal()
{
if (!m_settings.allowLocal())
return false;
if (m_pageURL.protocol() == "file" ||
m_pageURL.hostname() == "localhost") {
return true;
}
return false;
}
bool EsteidAPI::IsSecure()
{
if (IsLocal() || m_pageURL.protocol() == "https")
return true;
return false;
}
bool EsteidAPI::IsWhiteListed()
{
if (IsLocal() || m_settings.inWhitelist(m_pageURL.hostname()))
return true;
return false;
}
void EsteidAPI::whitelistRequired()
{
if (!IsSecure()) {
DisplayNotification(MSG_INSECURE);
throw FB::script_error("No cards found");
} else if (!IsWhiteListed()) {
DisplayNotification(MSG_SITEACCESS);
throw FB::script_error("No cards found");
}
}
std::string EsteidAPI::pageURL()
{
return m_host->getDOMWindow()->getLocation();
}
void EsteidAPI::CreateNotificationBar()
{
const std::string label = MSG_SETTINGS;
m_host->evaluateJavaScript(EstEIDNotificationBarScript);
m_barJSO = m_host->getDOMDocument()
->getProperty<FB::JSObjectPtr>("EstEIDNotificationBar");
m_barJSO->Invoke("create",
FB::variant_list_of(label)(m_settingsCallback));
}
void EsteidAPI::DisplayNotification(const std::string& msg)
{
try {
OpenNotificationBar();
m_barJSO->Invoke("show", FB::variant_list_of(msg));
} catch(const std::exception& e) {
ESTEID_DEBUG("Unable to display notification: %s", e.what());
}
}
void EsteidAPI::OpenNotificationBar()
{
if(!m_barJSO) {
CreateNotificationBar();
}
}
void EsteidAPI::CloseNotificationBar()
{
if(!m_barJSO) return;
m_barJSO->Invoke("close", FB::variant_list_of(0));
}
// JS method exposed to browser to show preferences window
// Direct access to this method will be exposed to a very few selected URL-s
void EsteidAPI::showSettings()
{
if (m_pageURL.protocol() == "file" ||
m_pageURL.protocol() == "chrome") {
try {
m_UI->settingsDialog(m_settings);
} catch(const std::exception& e) {
ESTEID_DEBUG("Unable to display whitelist editor: %s", e.what());
}
} else {
throw FB::script_error("No such method");
}
}
void EsteidAPI::settingsDialog()
{
try {
if (IsSecure())
m_UI->settingsDialog(m_settings, m_pageURL.hostname());
else
m_UI->settingsDialog(m_settings);
} catch(const std::exception& e) {
ESTEID_DEBUG("Unable to display whitelist editor: %s", e.what());
}
CloseNotificationBar();
}
void EsteidAPI::onMessage(CardService::MsgType e, ReaderID i)
{
//const char *evtname;
std::string evtname;
switch(e) {
case CardService::CARD_INSERTED: evtname = "CardInserted"; break;
case CardService::CARD_REMOVED: evtname = "CardRemoved"; break;
case CardService::READERS_CHANGED: evtname = "ReadersChanged";break;
default: throw std::runtime_error("Invalid message type"); break;
}
ESTEID_DEBUG("onMessage: %s %d", evtname.c_str(), i);
if(!IsWhiteListed()) return;
/* FIXME: Prefixing every event name with an additional "on" is a bloody
hack. We either need to fix firebreath or our JS API spec. */
FireEvent("on" + evtname, FB::variant_list_of(i));
}
// TODO: Optimize memory usage. Don't create new object if cert hasn't changed.
FB::JSAPIPtr EsteidAPI::get_authCert()
{
whitelistRequired();
RTERROR_TO_SCRIPT(
return FB::JSAPIPtr(new CertificateAPI(m_host, m_service->getAuthCert())));
}
FB::JSAPIPtr EsteidAPI::get_signCert()
{
whitelistRequired();
RTERROR_TO_SCRIPT(
return FB::JSAPIPtr(new CertificateAPI(m_host, m_service->getSignCert())));
}
FB::JSAPIPtr EsteidAPI::get_personalData()
{
whitelistRequired();
RTERROR_TO_SCRIPT(
std::vector<std::string> pData;
m_service->readPersonalData(pData);
return FB::JSAPIPtr(new PersonalDataAPI(m_host, pData))
);
}
std::string EsteidAPI::getVersion()
{
return FBSTRING_PLUGIN_VERSION;
}
int EsteidAPI::get_errorCode()
{
try {
whitelistRequired();
return 0;
} catch(...) {
return 0;
}
}
std::string EsteidAPI::get_errorMessage()
{
try {
whitelistRequired();
return "";
} catch(...) {
return "No cards found"; // FIXME: Use translatable messages
}
}
/*
* Ask for PIN and return; the signed hash is later asynchronously returned
* through callback.
*/
void EsteidAPI::signAsync(const std::string& hash, const std::string& url, const FB::JSObjectPtr& callback)
{
m_signCallback = callback;
try {
whitelistRequired();
prepareSign(hash, url);
askPin();
} catch(const std::exception& e) {
returnSignFailure(e.what());
return;
}
}
void EsteidAPI::prepareSign(const std::string& hash, const std::string& url)
{
if (hash.length() != 40)
throw std::runtime_error("Invalid hash");
if (url.empty())
throw std::runtime_error("Partial document URL must be specified");
/* Extract subject line from Certificate */
std::string subjectRaw = FB::ptr_cast<CertificateAPI>(get_signCert())->get_CN();
if (subjectRaw.empty())
throw std::runtime_error("Empty subject");
m_subject = subjectToHumanReadable(subjectRaw);
m_hash = hash;
m_url = url;
m_pinpad = m_service->hasSecurePinEntry();
}
void EsteidAPI::pinDialog(bool retrying, int triesLeft)
{
if (retrying)
m_UI->retryPinDialog(triesLeft);
else
m_UI->pinDialog(m_subject, m_url, m_hash);
}
void EsteidAPI::pinpadDialog(bool retrying, int triesLeft)
{
if (retrying)
m_UI->retryPinpadDialog(triesLeft);
else
m_UI->pinpadDialog(m_subject, m_url, m_hash, 30);
}
void EsteidAPI::askPin(bool retrying)
{
int triesLeft = getPin2RetryCount();
if (triesLeft <= 0) {
m_UI->pinBlockedMessage(2);
throw std::runtime_error("PIN2 locked");
}
if (m_pinpad) {
pinpadDialog(retrying, triesLeft);
pinpadSignSHA1(m_hash);
} else {
pinDialog(retrying, triesLeft);
}
}
void EsteidAPI::on_pinpadSignCompletedWrapper(const std::string& data)
{
try {
m_host->CallOnMainThread(boost::bind(&EsteidAPI::on_pinpadSignCompleted, this, data));
} catch (const FB::script_error&) {
// The call will throw this exception if the browser is shutting down and it cannot
// be completed.
}
}
void EsteidAPI::on_pinpadSignFailedWrapper(SignError error, const std::string& msg)
{
try {
m_host->CallOnMainThread(boost::bind(&EsteidAPI::on_pinpadSignFailed, this, error, msg));
} catch (const FB::script_error&) {
// The call will throw this exception if the browser is shutting down and it cannot
// be completed.
}
}
void EsteidAPI::on_pinpadSignCompleted(const std::string& data)
{
returnSignedData(data);
}
void EsteidAPI::on_pinpadSignFailed(SignError error, const std::string& msg)
{
switch (error) {
case SIGN_ERROR_WRONG_PIN:
try {
// ask again for PIN
askPin(true);
} catch(const std::exception& e) {
returnSignFailure(e.what());
}
break;
case SIGN_ERROR_BLOCKED:
m_UI->pinBlockedMessage(2);
returnSignFailure("PIN2 locked");
break;
case SIGN_ERROR_ABORTED:
returnSignFailure(CANCEL_MSG);
break;
default:
returnSignFailure(msg);
}
}
void EsteidAPI::pinpadSignSHA1(std::string hash)
{
filterWhitespace(hash);
m_service->setSignCompletedCallback(boost::bind(&EsteidAPI::on_pinpadSignCompletedWrapper, this, _1));
m_service->setSignFailedCallback(boost::bind(&EsteidAPI::on_pinpadSignFailedWrapper, this, _1, _2));
m_service->signSHA1Async(m_hash, EstEidCard::SIGN, "");
}
std::string EsteidAPI::signSHA1(std::string hash, const std::string& pin)
{
if (pin.empty()) // shouldn't happen
throw std::runtime_error("empty PIN");
filterWhitespace(hash);
std::string signedHash = m_service->signSHA1(hash, EstEidCard::SIGN, pin);
if (signedHash.empty()) // shouldn't happen
throw std::runtime_error("empty hash");
return signedHash;
}
/*
* Callback from UI code.
*
* Make sure the function doesn't throw to avoid
* unwinding through foreign frames.
*/
void EsteidAPI::onPinEntered(const std::string& pin)
{
try {
std::string signedHash = signSHA1(m_hash, pin);
returnSignedData(signedHash);
} catch(const AuthError& e) {
try {
// ask again for PIN
askPin(true);
} catch(const std::exception& e) {
returnSignFailure(e.what());
}
} catch(const std::exception& e) {
returnSignFailure(e.what());
}
}
void EsteidAPI::invokeSignCallback(const std::string& callback, const std::string& data)
{
if (!m_signCallback)
return;
try {
m_signCallback->Invoke(callback, FB::variant_list_of(data));
} catch(const FB::script_error&) {
// can't really do anything useful here
}
// release the callback object
m_signCallback.reset();
}
void EsteidAPI::returnSignedData(const std::string& data)
{
m_UI->closePinDialog();
m_UI->closePinpadDialog();
if (m_signCallback) {
// in case of async signing API, invoke the JS callback
invokeSignCallback("onSuccess", data);
} else {
// in case of sync signing API, signal for the blocking
// function to return
m_stoprequested = true;
m_signedHash = data;
}
}
void EsteidAPI::returnSignFailure(const std::string& msg)
{
m_UI->closePinDialog();
m_UI->closePinpadDialog();
if (m_signCallback) {
// in case of async signing API, invoke the JS callback
invokeSignCallback("onError", msg);
} else {
// in case of sync signing API, signal for the blocking
// function to return
m_stoprequested = true;
m_signFailure = msg;
}
}
#ifdef SUPPORT_OLD_APIS
#define COMPAT_URL "http://code.google.com/p/esteid/wiki/OldPluginCompatibilityMode"
void EsteidAPI::throwIfSignFailure()
{
if (m_signFailure.empty())
return;
std::string errorMsg = m_signFailure;
m_signFailure.clear();
throw std::runtime_error(errorMsg);
}
std::string EsteidAPI::askPinAndSign(const std::string& hash, const std::string& url)
{
prepareSign(hash, url);
askPin();
m_stoprequested = false;
do {
m_UI->iteration();
} while (!m_stoprequested);
throwIfSignFailure();
return m_signedHash;
}
/* Old Mozilla plugin */
std::string EsteidAPI::getCertificatesMoz()
{
whitelistRequired();
try { RTERROR_TO_SCRIPT(
ByteVec bv = m_service->getSignCert();
X509Certificate cert(bv);
std::ostringstream buf;
/* Return "compatible" JSON */
buf << "({certificates:[{";
buf << "id:'" << MAGIC_ID << "',";
buf << "cert:'";
for(ByteVec::const_iterator it = bv.begin(); it!=bv.end();it++)
buf << std::setfill('0') << std::setw(2) << std::hex << (short)*it;
buf << "',";
buf << "CN:'" << cert.getSubjectCN() << "',";
buf << "issuerCN:'" << cert.getIssuerCN() << "',";
// JS using this old API expects the exact string "Non-Repudiation"
buf << "keyUsage:'Non-Repudiation',";
buf << "validFrom: new Date(),"; // TODO: Date(YYYY,MM,DD,HH,mm,SS)
buf << "validTo: new Date()}],"; // TODO: Date(YYYY,MM,DD,HH,mm,SS)
buf << "returnCode:0})";
return buf.str();
// TODO: Return proper error code from plugin (when it's implemented)
)} catch(...) { return "({returnCode: 12})"; }
}
std::string EsteidAPI::sign(const std::string& a, const std::string& b)
{
whitelistRequired();
std::string signedHash;
if(!a.compare(MAGIC_ID2)) { // SK leakplugin compat mode
return signSK(a, b);
} else if(!a.compare(MAGIC_ID)) { // Old Mozilla Plugin compat mode
try {
signedHash = askPinAndSign(b, std::string(COMPAT_URL));
return "({signature:'" + signedHash + "', returnCode: 0})";
} catch(const std::runtime_error& e) {
// TODO: Return proper error code from plugin (when it's implemented)
return "({returnCode: 12})";
}
} else { // New plugin blocking API compatibility mode
try {
signedHash = askPinAndSign(a , (b.empty()) ? std::string(COMPAT_URL) : b);
} catch(const std::runtime_error& e) {
throw FB::script_error(e.what());
}
return signedHash;
}
}
/* Emulate SK leakplugin AND the old Mozilla plugin in one function */
FB::variant EsteidAPI::getCertificates() {
try {
return getCertificatesSK();
} catch(...) {
// TODO: Return proper error code from plugin (when it's implemented)
return "({returnCode: 12})";
}
}
/* Emulate SK leakplugin (application/x-digidoc) */
std::string EsteidAPI::get_version()
{
return getVersion();
}
FB::JSAPIPtr EsteidAPI::getCertificate() {
whitelistRequired();
RTERROR_TO_SCRIPT(
FB::VariantList outVar;
ByteVec bv = m_service->getSignCert();
return FB::JSAPIPtr(new SKCertificateAPI(m_host, bv));
);
}
FB::VariantList EsteidAPI::getCertificatesSK() {
whitelistRequired();
RTERROR_TO_SCRIPT(
FB::VariantList outVar;
ByteVec bv = m_service->getSignCert();
outVar.push_back(FB::JSAPIPtr(new SKCertificateAPI(m_host, bv)));
return outVar;
);
}
std::string EsteidAPI::signSK(const std::string& id,
const std::string& hash, FB::variant crap)
{
whitelistRequired();
RTERROR_TO_SCRIPT(
return askPinAndSign(hash, std::string(COMPAT_URL)));
}
/* This emulates old Java XMLSignApplet behaviour.
* XML manipulations done here are butt ugly, just like the "real solution",
* that was originally written by Mr. Veiko Sinivee.
*
* NB! This is a compatibility mode function and should
* NEVER be used in any new code.
*/
#ifdef USE_OPENSSL
/* Calculate SHA1 from ByteVec and encode it to Base64 */
static std::string B64SHA1(const ByteVec& in) {
std::string out(20, '\0');
SHA1(reinterpret_cast<const unsigned char *>(&in[0]), in.size(),
reinterpret_cast<unsigned char *>(&out[0]));
return base64_encode(out);
}
/* Calculate SHA1 from string and encode it to Base64 */
static std::string B64SHA1(const std::string& in) {
std::string out(20, '\0');
SHA1(reinterpret_cast<const unsigned char *>(&in[0]), in.size(),
reinterpret_cast<unsigned char *>(&out[0]));
return base64_encode(out);
}
/* Calculate SHA1 from string and encode it to Hex */
std::string HEXSHA1(const std::string& in) {
ByteVec bv(20, '\0');
SHA1(reinterpret_cast<const unsigned char *>(in.data()), in.size(),
&bv[0]);
std::ostringstream buf;
for(ByteVec::const_iterator it = bv.begin(); it!=bv.end();it++)
buf << std::setfill('0') << std::setw(2) << std::hex << (short)*it;
return buf.str();
}
#endif
void EsteidAPI::signXML(
const std::string& data,
const std::string& onSuccess,
const std::string& lang,
const std::string& charset,
const std::string& encoding,
const std::string& onCancel)
{
ESTEID_DEBUG("signXML('%s','%s','%s','%s','%s','%s')\n", data.c_str(),
onSuccess.c_str(), lang.c_str(), charset.c_str(),
encoding.c_str(), onCancel.c_str());
#ifdef USE_OPENSSL
/* SHA1 Digest URL used in XML generation */
const std::string sha1Url = "http://www.w3.org/2000/09/xmldsig#sha1";
std::string decoded_data = data;
if(encoding == "EMBEDDED_BASE64") {
decoded_data = base64_decode(data);
}
std::string dataLen = boost::lexical_cast<std::string>(decoded_data.length());
/* FIXME: Old XMLSignApplet recodes character data to UTF-8,
* replaces newlines (\n and \r) with spaces and re-encodes
* back to Base64, but is this actually needed? I don't think so.
*/
//recode_from_charset_to_UTF8(data);
//std::replace(decoded_data.begin(), decoded_data.end(), '\n', ' ');
//std::replace(decoded_data.begin(), decoded_data.end(), '\r', ' ');
//if(encoding == "EMBEDDED_BASE64") {
// data = base64_encode(decoded_data);
//}
/* Get required info from certificate */
std::string certDigest;
std::string certSerial;
std::string certData;
try { RTERROR_TO_SCRIPT(
ByteVec bv = m_service->getSignCert();
X509Certificate cert(bv);
certSerial = cert.getSerial();
certDigest = B64SHA1(bv);
certData = base64_encode(bv);
)} catch(...) {
m_host->evaluateJavaScript(onCancel + "();");
return;
}
/* Make current time
* Please note that this is NOT valid XML date format.
* XML Date format is %Y-%m-%dT%H:%M:%SZ, where
* Z denotes universal time. However XMLSignApplet
* separates date components with dots and uses local time
* so we implement it incorrectly too in order to maintain
* bug-for-bug compatibility */
boost::posix_time::time_facet* tf =
new boost::posix_time::time_facet("%Y.%m.%dT%H:%M:%SZ");
std::stringstream tmp;
tmp.imbue(std::locale(tmp.getloc(), tf));
tmp << boost::posix_time::second_clock::local_time();
std::string sigTime = tmp.str();
/* Start constructing XML */
// <DataFile>
std::string dataFileXml =
"<DataFile ContentType=\"" + encoding + "\" "
"Filename=\"msg.xml\" Id=\"D0\" MimeType=\"text/xml\" "
"Size=\"" + dataLen + "\">" + data +
"</DataFile>";
// <SignedProperties>
std::string sigPropXml =
"<SignedProperties xmlns=\"http://www.w3.org/2000/09/xmldsig#\" "
"Id=\"S0-SignedProperties\" Target=\"#S0\">"
"<SignedSignatureProperties>"
"<SigningTime>" + sigTime + "</SigningTime>"
"<SigningCertificate><Cert Id=\"S0-CERTINFO\">"
"<CertDigest>"
"<DigestMethod Algorithm=\"" + sha1Url + "\"></DigestMethod>"
"<DigestValue>" + certDigest + "</DigestValue>"
"</CertDigest>"
"<IssuerSerial>" + certSerial + "</IssuerSerial>"
"</Cert></SigningCertificate>"
"<SignaturePolicyIdentifier>"
"<SignaturePolicyImplied></SignaturePolicyImplied>"
"</SignaturePolicyIdentifier>"
"<SignatureProductionPlace></SignatureProductionPlace>"
"<SignerRole></SignerRole>"
"</SignedSignatureProperties>"
"<SignedDataObjectProperties></SignedDataObjectProperties>"
"</SignedProperties>";
// <SignedInfo>
std::string sigInfoXml =
"<SignedInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\">"
"<CanonicalizationMethod "
"Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\">"
"</CanonicalizationMethod>"
"<SignatureMethod "
"Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\">"
"</SignatureMethod>"
"<Reference URI=\"#D0\">"
"<DigestMethod Algorithm=\"" + sha1Url + "\"></DigestMethod>"
"<DigestValue>" + B64SHA1(dataFileXml) + "</DigestValue>"
"</Reference>"
"<Reference URI=\"#S0-SignedProperties\">"
"<DigestMethod Algorithm=\"" + sha1Url + "\"></DigestMethod>"
"<DigestValue>" + B64SHA1(sigPropXml) + "</DigestValue>"
"</Reference>"
"</SignedInfo>";
/* Perform signing operation */
/* FIXME: The original API is non-blocking, but the callbacks
are so braindead (callback function name is passed as a string)
so we implement the compatibility version as a blocking call for now */
std::string sigValue;
try {
std::string signedHash =
askPinAndSign(HEXSHA1(sigInfoXml), std::string(COMPAT_URL));
sigValue = base64_encode(hex_to_bytes(signedHash));
} catch(const std::runtime_error& e) {
m_host->evaluateJavaScript(onCancel + "();");
return;
}
// <Signature>
std::string sigXml =
"<Signature Id=\"S0\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\">"
/* <SignedInfo> */ + sigInfoXml +
"<SignatureValue Id=\"S0-SIG\">" + sigValue + "</SignatureValue>"
"<KeyInfo>"
"<X509Data>"
"<X509Certificate Id=\"S0-CERT\">" + certData + "</X509Certificate>"
"</X509Data>"
"</KeyInfo>"
"<Object>"
"<QualifyingProperties>" + sigPropXml + "</QualifyingProperties>"
"</Object>"
"</Signature>";
std::string finalXml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<SignedDoc format=\"DIGIDOC-XML\" version=\"1.1\">"
/* <DataFile> */ + dataFileXml
/* <Signature> */ + sigXml +
"</SignedDoc>";
ESTEID_DEBUG("\n%s\n", finalXml.c_str());
m_host->evaluateJavaScript(onSuccess + "('" + finalXml + "');");
#else
throw FB::script_error("XML Signer requires OpenSSL-enabled build");
#endif
}
std::string EsteidAPI::getInfo()
{
return getVersion();
}
std::string EsteidAPI::getSigningCertificate()
{
whitelistRequired();
try {
ByteVec bv = m_service->getSignCert();
std::ostringstream buf;
for(ByteVec::const_iterator it = bv.begin(); it!=bv.end();it++)
buf << std::setfill('0') << std::setw(2) << std::hex << (short)*it;
return buf.str();
} catch(...) { return ""; } // This API returns nothing on Error
}
std::string EsteidAPI::getSignedHash(const std::string& hash, const std::string& slot)
{
whitelistRequired();
try {
std::string signedHash = askPinAndSign(hash, std::string(COMPAT_URL));
return signedHash;
} catch(const std::runtime_error& e) {
// This API returns nothing on error
return "";
}
}
std::string EsteidAPI::get_selectedCertNumber()
{
whitelistRequired();
return "10"; // Dummy number
}
void EsteidAPI::prepare(const std::string& onSuccess,
const std::string& onCancel,
const std::string& onError)
{
whitelistRequired();
try {
ByteVec bv = m_service->getSignCert();
std::ostringstream buf;
for(ByteVec::const_iterator it = bv.begin(); it!=bv.end();it++)
buf << std::setfill('0') << std::setw(2) << std::hex << (short)*it;
m_host->evaluateJavaScript(onSuccess + "(10, '" + buf.str() + "');");
} catch(const std::runtime_error& e) {
m_host->evaluateJavaScript(onError + "(12, '" + e.what() + "');");
}
}
void EsteidAPI::finalize(const std::string& slot,
const std::string& hash,
const std::string& onSuccess,
const std::string& onCancel,
const std::string& onError)
{
whitelistRequired();
/* FIXME: The original API is non-blocking, but the callbacks
are so braindead (callback function name is passed as a string)
so we implement the compatibility version as a blocking call for now */
try {
std::string signedHash = askPinAndSign(hash, std::string(COMPAT_URL));
m_host->evaluateJavaScript(onSuccess + "('" + signedHash + "');");
} catch(const std::runtime_error& e) {
m_host->evaluateJavaScript(onCancel + "();");
}
}
bool EsteidAPI::isActive()
{
return true;
}
#endif
int EsteidAPI::getPin2RetryCount()
{
byte puk, pin1, pin2;
m_service->getRetryCounts(puk, pin1, pin2);
return pin2;
}
void EsteidAPI::filterWhitespace(std::string& s)
{
// Strip spaces and newlines
s.erase(std::remove(s.begin(), s.end(), '\n'), s.end());
s.erase(std::remove(s.begin(), s.end(), '\r'), s.end());
s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
}
std::string EsteidAPI::subjectToHumanReadable(const std::string& subject)