-
Notifications
You must be signed in to change notification settings - Fork 710
/
HFCAClient.java
1776 lines (1462 loc) · 72.4 KB
/
HFCAClient.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
/*
* Copyright 2016, 2017 DTCC, Fujitsu Australia Software Technology, IBM - All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperledger.fabric_ca.sdk;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.KeyManagementException;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.json.JsonWriter;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.xml.bind.DatatypeConverter;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.apache.milagro.amcl.FP256BN.BIG;
import org.apache.milagro.amcl.RAND;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.util.io.pem.PemReader;
import org.hyperledger.fabric.protos.idemix.Idemix;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.NetworkConfig;
import org.hyperledger.fabric.sdk.User;
import org.hyperledger.fabric.sdk.helper.Utils;
import org.hyperledger.fabric.sdk.idemix.IdemixCredRequest;
import org.hyperledger.fabric.sdk.idemix.IdemixCredential;
import org.hyperledger.fabric.sdk.idemix.IdemixIssuerPublicKey;
import org.hyperledger.fabric.sdk.idemix.IdemixUtils;
import org.hyperledger.fabric.sdk.identity.IdemixEnrollment;
import org.hyperledger.fabric.sdk.identity.X509Enrollment;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric_ca.sdk.exception.AffiliationException;
import org.hyperledger.fabric_ca.sdk.exception.EnrollmentException;
import org.hyperledger.fabric_ca.sdk.exception.GenerateCRLException;
import org.hyperledger.fabric_ca.sdk.exception.HFCACertificateException;
import org.hyperledger.fabric_ca.sdk.exception.HTTPException;
import org.hyperledger.fabric_ca.sdk.exception.IdentityException;
import org.hyperledger.fabric_ca.sdk.exception.InfoException;
import org.hyperledger.fabric_ca.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric_ca.sdk.exception.RegistrationException;
import org.hyperledger.fabric_ca.sdk.exception.RevocationException;
import org.hyperledger.fabric_ca.sdk.helper.Config;
import org.hyperledger.fabric_ca.sdk.helper.Util;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* HFCAClient Hyperledger Fabric Certificate Authority Client.
*/
public class HFCAClient {
private static final Config config = Config.getConfig(); // DO NOT REMOVE THIS IS NEEDED TO MAKE SURE WE FIRST LOAD CONFIG!!!
/**
* Default profile name.
*/
public static final String DEFAULT_PROFILE_NAME = "";
/**
* HFCA_TYPE_PEER indicates that an identity is acting as a peer
*/
public static final String HFCA_TYPE_PEER = "peer";
/**
* HFCA_TYPE_ORDERER indicates that an identity is acting as an orderer
*/
public static final String HFCA_TYPE_ORDERER = "orderer";
/**
* HFCA_TYPE_CLIENT indicates that an identity is acting as a client
*/
public static final String HFCA_TYPE_CLIENT = "client";
/**
* HFCA_TYPE_USER indicates that an identity is acting as a user
*/
public static final String HFCA_TYPE_USER = "user";
/**
* HFCA_ATTRIBUTE_HFREGISTRARROLES is an attribute that allows a registrar to manage identities of the specified roles
*/
public static final String HFCA_ATTRIBUTE_HFREGISTRARROLES = "hf.Registrar.Roles";
/**
* HFCA_ATTRIBUTE_HFREGISTRARDELEGATEROLES is an attribute that allows a registrar to give the roles specified
* to a registree for its 'hf.Registrar.Roles' attribute
*/
public static final String HFCA_ATTRIBUTE_HFREGISTRARDELEGATEROLES = "hf.Registrar.DelegateRoles";
/**
* HFCA_ATTRIBUTE_HFREGISTRARATTRIBUTES is an attribute that has a list of attributes that the registrar is allowed to register
* for an identity
*/
public static final String HFCA_ATTRIBUTE_HFREGISTRARATTRIBUTES = "hf.Registrar.Attributes";
/**
* HFCA_ATTRIBUTE_HFINTERMEDIATECA is a boolean attribute that allows an identity to enroll as an intermediate CA
*/
public static final String HFCA_ATTRIBUTE_HFINTERMEDIATECA = "hf.IntermediateCA";
/**
* HFCA_ATTRIBUTE_HFREVOKER is a boolean attribute that allows an identity to revoker a user and/or certificates
*/
public static final String HFCA_ATTRIBUTE_HFREVOKER = "hf.Revoker";
/**
* HFCA_ATTRIBUTE_HFAFFILIATIONMGR is a boolean attribute that allows an identity to manage affiliations
*/
public static final String HFCA_ATTRIBUTE_HFAFFILIATIONMGR = "hf.AffiliationMgr";
/**
* HFCA_ATTRIBUTE_HFGENCRL is an attribute that allows an identity to generate a CRL
*/
public static final String HFCA_ATTRIBUTE_HFGENCRL = "hf.GenCRL";
private static final int CONNECTION_REQUEST_TIMEOUT = config.getConnectionRequestTimeout();
private static final int CONNECT_TIMEOUT = config.getConnectTimeout();
private static final int SOCKET_TIMEOUT = config.getSocketTimeout();
private static final Log logger = LogFactory.getLog(HFCAClient.class);
static final String FABRIC_CA_REQPROP = "caname";
static final String HFCA_CONTEXT_ROOT = "/api/v1/";
private static final String HFCA_ENROLL = HFCA_CONTEXT_ROOT + "enroll";
private static final String HFCA_REGISTER = HFCA_CONTEXT_ROOT + "register";
private static final String HFCA_REENROLL = HFCA_CONTEXT_ROOT + "reenroll";
private static final String HFCA_REVOKE = HFCA_CONTEXT_ROOT + "revoke";
private static final String HFCA_INFO = HFCA_CONTEXT_ROOT + "cainfo";
private static final String HFCA_GENCRL = HFCA_CONTEXT_ROOT + "gencrl";
private static final String HFCA_CERTIFICATE = HFCAClient.HFCA_CONTEXT_ROOT + "certificates";
private static final String HFCA_IDEMIXCRED = HFCA_CONTEXT_ROOT + "idemix/credential";
private final String url;
private final boolean isSSL;
private final Properties properties;
// Cache the payload type, so don't need to make get cainfo call everytime
private Boolean newPayloadType;
/**
* The Certificate Authority name.
*
* @return May return null or empty string for default certificate authority.
*/
public String getCAName() {
return caName;
}
private final String caName;
private CryptoSuite cryptoSuite;
private int statusCode = 400;
/**
* The Status Code level of client, HTTP status codes above this value will return in a
* exception, otherwise, the status code will be return the status code and appropriate error
* will be logged.
*
* @return statusCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* HFCAClient constructor
*
* @param url Http URL for the Fabric's certificate authority services endpoint
* @param properties PEM used for SSL .. not implemented.
* <p>
* Supported properties
* <ul>
* <li>pemFile - File location for x509 pem certificate for SSL.</li>
* <li>allowAllHostNames - boolen(true/false) override certificates CN Host matching -- for development only.</li>
* </ul>
* @throws MalformedURLException
*/
HFCAClient(String caName, String url, Properties properties) throws MalformedURLException {
logger.debug(format("new HFCAClient %s", url));
this.url = url;
this.caName = caName; //name may be null
URL purl = new URL(url);
final String proto = purl.getProtocol();
if (!"http".equals(proto) && !"https".equals(proto)) {
throw new IllegalArgumentException("HFCAClient only supports http or https not " + proto);
}
final String host = purl.getHost();
if (Utils.isNullOrEmpty(host)) {
throw new IllegalArgumentException("HFCAClient url needs host");
}
final String path = purl.getPath();
if (!Utils.isNullOrEmpty(path)) {
throw new IllegalArgumentException("HFCAClient url does not support path portion in url remove path: '" + path + "'.");
}
final String query = purl.getQuery();
if (!Utils.isNullOrEmpty(query)) {
throw new IllegalArgumentException("HFCAClient url does not support query portion in url remove query: '" + query + "'.");
}
isSSL = "https".equals(proto);
if (properties != null) {
this.properties = (Properties) properties.clone(); //keep our own copy.
} else {
this.properties = null;
}
}
public static HFCAClient createNewInstance(String url, Properties properties) throws MalformedURLException {
return new HFCAClient(null, url, properties);
}
public static HFCAClient createNewInstance(String name, String url, Properties properties) throws MalformedURLException, InvalidArgumentException {
if (name == null || name.isEmpty()) {
throw new InvalidArgumentException("name must not be null or an empty string.");
}
return new HFCAClient(name, url, properties);
}
/**
* Create HFCAClient from a NetworkConfig.CAInfo using default crypto suite.
*
* @param caInfo created from NetworkConfig.getOrganizationInfo("org_name").getCertificateAuthorities()
* @return HFCAClient
* @throws MalformedURLException
* @throws InvalidArgumentException
*/
public static HFCAClient createNewInstance(NetworkConfig.CAInfo caInfo) throws MalformedURLException, InvalidArgumentException {
try {
return createNewInstance(caInfo, CryptoSuite.Factory.getCryptoSuite());
} catch (MalformedURLException e) {
throw e;
} catch (Exception e) {
throw new InvalidArgumentException(e);
}
}
/**
* Create HFCAClient from a NetworkConfig.CAInfo
*
* @param caInfo created from NetworkConfig.getOrganizationInfo("org_name").getCertificateAuthorities()
* @param cryptoSuite the specific cryptosuite to use.
* @return HFCAClient
* @throws MalformedURLException
* @throws InvalidArgumentException
*/
public static HFCAClient createNewInstance(NetworkConfig.CAInfo caInfo, CryptoSuite cryptoSuite) throws MalformedURLException, InvalidArgumentException {
if (null == caInfo) {
throw new InvalidArgumentException("The caInfo parameter can not be null.");
}
if (null == cryptoSuite) {
throw new InvalidArgumentException("The cryptoSuite parameter can not be null.");
}
HFCAClient ret = new HFCAClient(caInfo.getCAName(), caInfo.getUrl(), caInfo.getProperties());
ret.setCryptoSuite(cryptoSuite);
return ret;
}
public void setCryptoSuite(CryptoSuite cryptoSuite) {
this.cryptoSuite = cryptoSuite;
}
public CryptoSuite getCryptoSuite() {
return cryptoSuite;
}
/**
* Register a user.
*
* @param request Registration request with the following fields: name, role.
* @param registrar The identity of the registrar (i.e. who is performing the registration).
* @return the enrollment secret.
* @throws RegistrationException if registration fails.
* @throws InvalidArgumentException
*/
public String register(RegistrationRequest request, User registrar) throws RegistrationException, InvalidArgumentException {
if (cryptoSuite == null) {
throw new InvalidArgumentException("Crypto primitives not set.");
}
if (Utils.isNullOrEmpty(request.getEnrollmentID())) {
throw new InvalidArgumentException("EntrollmentID cannot be null or empty");
}
if (registrar == null) {
throw new InvalidArgumentException("Registrar should be a valid member");
}
logger.debug(format("register url: %s, registrar: %s", url, registrar.getName()));
setUpSSL();
try {
String body = request.toJson();
JsonObject resp = httpPost(url + HFCA_REGISTER, body, registrar);
String secret = resp.getString("secret");
if (secret == null) {
throw new Exception("secret was not found in response");
}
logger.debug(format("register url: %s, registrar: %s done.", url, registrar));
return secret;
} catch (Exception e) {
RegistrationException registrationException = new RegistrationException(format("Error while registering the user %s url: %s %s ", registrar, url, e.getMessage()), e);
logger.error(registrar);
throw registrationException;
}
}
/**
* Enroll the user with member service
*
* @param user Identity name to enroll
* @param secret Secret returned via registration
* @return enrollment
* @throws EnrollmentException
* @throws InvalidArgumentException
*/
public Enrollment enroll(String user, String secret) throws EnrollmentException, InvalidArgumentException {
return enroll(user, secret, new EnrollmentRequest());
}
/**
* Enroll the user with member service
*
* @param user Identity name to enroll
* @param secret Secret returned via registration
* @param req Enrollment request with the following fields: hosts, profile, csr, label, keypair
* @return enrollment
* @throws EnrollmentException
* @throws InvalidArgumentException
*/
public Enrollment enroll(String user, String secret, EnrollmentRequest req) throws EnrollmentException, InvalidArgumentException {
logger.debug(format("url:%s enroll user: %s", url, user));
if (Utils.isNullOrEmpty(user)) {
throw new InvalidArgumentException("enrollment user is not set");
}
if (Utils.isNullOrEmpty(secret)) {
throw new InvalidArgumentException("enrollment secret is not set");
}
if (cryptoSuite == null) {
throw new InvalidArgumentException("Crypto primitives not set.");
}
setUpSSL();
try {
String pem = req.getCsr();
KeyPair keypair = req.getKeyPair();
if (null != pem && keypair == null) {
throw new InvalidArgumentException("If certificate signing request is supplied the key pair needs to be supplied too.");
}
if (keypair == null) {
logger.debug("[HFCAClient.enroll] Generating keys...");
// generate ECDSA keys: signing and encryption keys
keypair = cryptoSuite.keyGen();
logger.debug("[HFCAClient.enroll] Generating keys...done!");
}
if (pem == null) {
String csr = cryptoSuite.generateCertificationRequest(user, keypair);
req.setCSR(csr);
}
if (caName != null && !caName.isEmpty()) {
req.setCAName(caName);
}
String body = req.toJson();
String responseBody = httpPost(getURL(HFCA_ENROLL), body,
new UsernamePasswordCredentials(user, secret));
logger.debug("response:" + responseBody);
JsonReader reader = Json.createReader(new StringReader(responseBody));
JsonObject jsonst = (JsonObject) reader.read();
boolean success = jsonst.getBoolean("success");
logger.debug(format("[HFCAClient] enroll success:[%s]", success));
if (!success) {
throw new EnrollmentException(format("FabricCA failed enrollment for user %s response success is false.", user));
}
JsonObject result = jsonst.getJsonObject("result");
if (result == null) {
throw new EnrollmentException(format("FabricCA failed enrollment for user %s - response did not contain a result", user));
}
Base64.Decoder b64dec = Base64.getDecoder();
String signedPem = new String(b64dec.decode(result.getString("Cert").getBytes(UTF_8)));
logger.debug(format("[HFCAClient] enroll returned pem:[%s]", signedPem));
JsonArray messages = jsonst.getJsonArray("messages");
if (messages != null && !messages.isEmpty()) {
JsonObject jo = messages.getJsonObject(0);
String message = format("Enroll request response message [code %d]: %s", jo.getInt("code"), jo.getString("message"));
logger.info(message);
}
logger.debug("Enrollment done.");
return new X509Enrollment(keypair, signedPem);
} catch (EnrollmentException ee) {
logger.error(format("url:%s, user:%s error:%s", url, user, ee.getMessage()), ee);
throw ee;
} catch (Exception e) {
EnrollmentException ee = new EnrollmentException(format("Url:%s, Failed to enroll user %s ", url, user), e);
logger.error(e.getMessage(), e);
throw ee;
}
}
/**
* Return information on the Fabric Certificate Authority.
* No credentials are needed for this API.
*
* @return {@link HFCAInfo}
* @throws InfoException
* @throws InvalidArgumentException
*/
public HFCAInfo info() throws InfoException, InvalidArgumentException {
String infoURL;
try {
infoURL = getURL(HFCA_INFO);
} catch (Exception e) {
throw new InvalidArgumentException(e);
}
logger.debug(format("info url:%s", infoURL));
if (cryptoSuite == null) {
throw new InvalidArgumentException("Crypto primitives not set.");
}
setUpSSL();
try {
JsonObjectBuilder factory = Json.createObjectBuilder();
if (caName != null) {
factory.add(HFCAClient.FABRIC_CA_REQPROP, caName);
}
JsonObject body = factory.build();
String responseBody = httpPost(infoURL, body.toString(),
(UsernamePasswordCredentials) null);
logger.debug("response:" + responseBody);
JsonReader reader = Json.createReader(new StringReader(responseBody));
JsonObject jsonst = (JsonObject) reader.read();
boolean success = jsonst.getBoolean("success");
logger.debug(format("[HFCAClient] enroll success:[%s]", success));
if (!success) {
throw new EnrollmentException(format("FabricCA failed info %s", infoURL));
}
JsonObject result = jsonst.getJsonObject("result");
if (result == null) {
throw new InfoException(format("FabricCA info error - response did not contain a result url %s", infoURL));
}
String caName = result.getString("CAName");
String caChain = result.getString("CAChain");
String version = null;
if (result.containsKey("Version")) {
version = result.getString("Version");
}
String issuerPublicKey = null;
if (result.containsKey("IssuerPublicKey")) {
issuerPublicKey = result.getString("IssuerPublicKey");
}
String issuerRevocationPublicKey = null;
if (result.containsKey("IssuerRevocationPublicKey")) {
issuerRevocationPublicKey = result.getString("IssuerRevocationPublicKey");
}
logger.info(format("CA Name: %s, Version: %s, issuerPublicKey: %s, issuerRevocationPublicKey: %s", caName, caChain, issuerPublicKey, issuerRevocationPublicKey));
return new HFCAInfo(caName, caChain, version, issuerPublicKey, issuerRevocationPublicKey);
} catch (Exception e) {
InfoException ee = new InfoException(format("Url:%s, Failed to get info", infoURL), e);
logger.error(e.getMessage(), e);
throw ee;
}
}
/**
* Re-Enroll the user with member service
*
* @param user User to be re-enrolled
* @return enrollment
* @throws EnrollmentException
* @throws InvalidArgumentException
*/
public Enrollment reenroll(User user) throws EnrollmentException, InvalidArgumentException {
return reenroll(user, new EnrollmentRequest());
}
/**
* Re-Enroll the user with member service
*
* @param user User to be re-enrolled
* @param req Enrollment request with the following fields: hosts, profile, csr, label
* @return enrollment
* @throws EnrollmentException
* @throws InvalidArgumentException
*/
public Enrollment reenroll(User user, EnrollmentRequest req) throws EnrollmentException, InvalidArgumentException {
if (cryptoSuite == null) {
throw new InvalidArgumentException("Crypto primitives not set.");
}
if (user == null) {
throw new InvalidArgumentException("reenrollment user is missing");
}
if (user.getEnrollment() == null) {
throw new InvalidArgumentException("reenrollment user is not a valid user object");
}
logger.debug(format("re-enroll user: %s, url: %s", user.getName(), url));
try {
setUpSSL();
PublicKey publicKey = cryptoSuite.bytesToCertificate(user.getEnrollment().getCert()
.getBytes(StandardCharsets.UTF_8)).getPublicKey();
KeyPair keypair = new KeyPair(publicKey, user.getEnrollment().getKey());
// generate CSR
String pem = cryptoSuite.generateCertificationRequest(user.getName(), keypair);
// build request body
req.setCSR(pem);
if (caName != null && !caName.isEmpty()) {
req.setCAName(caName);
}
String body = req.toJson();
// build authentication header
JsonObject result = httpPost(url + HFCA_REENROLL, body, user);
// get new cert from response
Base64.Decoder b64dec = Base64.getDecoder();
String signedPem = new String(b64dec.decode(result.getString("Cert").getBytes(UTF_8)));
logger.debug(format("[HFCAClient] re-enroll returned pem:[%s]", signedPem));
logger.debug(format("reenroll user %s done.", user.getName()));
return new X509Enrollment(keypair, signedPem);
} catch (EnrollmentException ee) {
logger.error(ee.getMessage(), ee);
throw ee;
} catch (Exception e) {
EnrollmentException ee = new EnrollmentException(format("Failed to re-enroll user %s", user), e);
logger.error(e.getMessage(), e);
throw ee;
}
}
/**
* revoke one enrollment of user
*
* @param revoker admin user who has revoker attribute configured in CA-server
* @param enrollment the user enrollment to be revoked
* @param reason revoke reason, see RFC 5280
* @throws RevocationException
* @throws InvalidArgumentException
*/
public void revoke(User revoker, Enrollment enrollment, String reason) throws RevocationException, InvalidArgumentException {
revokeInternal(revoker, enrollment, reason, false);
}
/**
* revoke one enrollment of user
*
* @param revoker admin user who has revoker attribute configured in CA-server
* @param enrollment the user enrollment to be revoked
* @param reason revoke reason, see RFC 5280
* @param genCRL generate CRL list
* @throws RevocationException
* @throws InvalidArgumentException
*/
public String revoke(User revoker, Enrollment enrollment, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException {
return revokeInternal(revoker, enrollment, reason, genCRL);
}
private String revokeInternal(User revoker, Enrollment enrollment, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException {
if (cryptoSuite == null) {
throw new InvalidArgumentException("Crypto primitives not set.");
}
if (enrollment == null) {
throw new InvalidArgumentException("revokee enrollment is not set");
}
if (revoker == null) {
throw new InvalidArgumentException("revoker is not set");
}
logger.debug(format("revoke revoker: %s, reason: %s, url: %s", revoker.getName(), reason, url));
try {
setUpSSL();
// get cert from to-be-revoked enrollment
BufferedInputStream pem = new BufferedInputStream(new ByteArrayInputStream(enrollment.getCert().getBytes()));
CertificateFactory certFactory = CertificateFactory.getInstance(Config.getConfig().getCertificateFormat());
X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem);
// get its serial number
String serial = DatatypeConverter.printHexBinary(certificate.getSerialNumber().toByteArray());
// get its aki
// 2.5.29.35 : AuthorityKeyIdentifier
byte[] extensionValue = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId());
ASN1OctetString akiOc = ASN1OctetString.getInstance(extensionValue);
String aki = DatatypeConverter.printHexBinary(AuthorityKeyIdentifier.getInstance(akiOc.getOctets()).getKeyIdentifier());
// build request body
RevocationRequest req = new RevocationRequest(caName, null, serial, aki, reason, genCRL);
String body = req.toJson();
// send revoke request
JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker);
logger.debug("revoke done");
if (genCRL) {
if (resp.isEmpty()) {
throw new RevocationException("Failed to return CRL, revoke response is empty");
}
if (resp.isNull("CRL")) {
throw new RevocationException("Failed to return CRL");
}
return resp.getString("CRL");
}
return null;
} catch (CertificateException e) {
logger.error("Cannot validate certificate. Error is: " + e.getMessage());
throw new RevocationException("Error while revoking cert. " + e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RevocationException("Error while revoking the user. " + e.getMessage(), e);
}
}
/**
* revoke one user (including his all enrollments)
*
* @param revoker admin user who has revoker attribute configured in CA-server
* @param revokee user who is to be revoked
* @param reason revoke reason, see RFC 5280
* @throws RevocationException
* @throws InvalidArgumentException
*/
public void revoke(User revoker, String revokee, String reason) throws RevocationException, InvalidArgumentException {
revokeInternal(revoker, revokee, reason, false);
}
/**
* revoke one user (including his all enrollments)
*
* @param revoker admin user who has revoker attribute configured in CA-server
* @param revokee user who is to be revoked
* @param reason revoke reason, see RFC 5280
* @param genCRL generate CRL
* @throws RevocationException
* @throws InvalidArgumentException
*/
public String revoke(User revoker, String revokee, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException {
return revokeInternal(revoker, revokee, reason, genCRL);
}
private String revokeInternal(User revoker, String revokee, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException {
if (cryptoSuite == null) {
throw new InvalidArgumentException("Crypto primitives not set.");
}
logger.debug(format("revoke revoker: %s, revokee: %s, reason: %s", revoker, revokee, reason));
if (Utils.isNullOrEmpty(revokee)) {
throw new InvalidArgumentException("revokee user is not set");
}
if (revoker == null) {
throw new InvalidArgumentException("revoker is not set");
}
try {
setUpSSL();
// build request body
RevocationRequest req = new RevocationRequest(caName, revokee, null, null, reason, genCRL);
String body = req.toJson();
// send revoke request
JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker);
logger.debug(format("revoke revokee: %s done.", revokee));
if (genCRL) {
if (resp.isEmpty()) {
throw new RevocationException("Failed to return CRL, revoke response is empty");
}
if (resp.isNull("CRL")) {
throw new RevocationException("Failed to return CRL");
}
return resp.getString("CRL");
}
return null;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RevocationException("Error while revoking the user. " + e.getMessage(), e);
}
}
/**
* revoke one certificate
*
* @param revoker admin user who has revoker attribute configured in CA-server
* @param serial serial number of the certificate to be revoked
* @param aki aki of the certificate to be revoke
* @param reason revoke reason, see RFC 5280
* @throws RevocationException
* @throws InvalidArgumentException
*/
public void revoke(User revoker, String serial, String aki, String reason) throws RevocationException, InvalidArgumentException {
revokeInternal(revoker, serial, aki, reason, false);
}
/**
* revoke one enrollment of user
*
* @param revoker admin user who has revoker attribute configured in CA-server
* @param serial serial number of the certificate to be revoked
* @param aki aki of the certificate to be revoke
* @param reason revoke reason, see RFC 5280
* @param genCRL generate CRL list
* @throws RevocationException
* @throws InvalidArgumentException
*/
public String revoke(User revoker, String serial, String aki, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException {
return revokeInternal(revoker, serial, aki, reason, genCRL);
}
private String revokeInternal(User revoker, String serial, String aki, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException {
if (cryptoSuite == null) {
throw new InvalidArgumentException("Crypto primitives not set.");
}
if (Utils.isNullOrEmpty(serial)) {
throw new IllegalArgumentException("Serial number id required to revoke ceritificate");
}
if (Utils.isNullOrEmpty(aki)) {
throw new IllegalArgumentException("AKI is required to revoke certificate");
}
if (revoker == null) {
throw new InvalidArgumentException("revoker is not set");
}
logger.debug(format("revoke revoker: %s, reason: %s, url: %s", revoker.getName(), reason, url));
try {
setUpSSL();
// build request body
RevocationRequest req = new RevocationRequest(caName, null, serial, aki, reason, genCRL);
String body = req.toJson();
// send revoke request
JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker);
logger.debug("revoke done");
if (genCRL) {
if (resp.isEmpty()) {
throw new RevocationException("Failed to return CRL, revoke response is empty");
}
if (resp.isNull("CRL")) {
throw new RevocationException("Failed to return CRL");
}
return resp.getString("CRL");
}
return null;
} catch (CertificateException e) {
logger.error("Cannot validate certificate. Error is: " + e.getMessage());
throw new RevocationException("Error while revoking cert. " + e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RevocationException("Error while revoking the user. " + e.getMessage(), e);
}
}
/**
* Generate certificate revocation list.
*
* @param registrar admin user configured in CA-server
* @param revokedBefore Restrict certificates returned to revoked before this date if not null.
* @param revokedAfter Restrict certificates returned to revoked after this date if not null.
* @param expireBefore Restrict certificates returned to expired before this date if not null.
* @param expireAfter Restrict certificates returned to expired after this date if not null.
* @throws InvalidArgumentException
*/
public String generateCRL(User registrar, Date revokedBefore, Date revokedAfter, Date expireBefore, Date expireAfter)
throws InvalidArgumentException, GenerateCRLException {
if (cryptoSuite == null) {
throw new InvalidArgumentException("Crypto primitives not set.");
}
if (registrar == null) {
throw new InvalidArgumentException("registrar is not set");
}
try {
setUpSSL();
//---------------------------------------
JsonObjectBuilder factory = Json.createObjectBuilder();
if (revokedBefore != null) {
factory.add("revokedBefore", Util.dateToString(revokedBefore));
}
if (revokedAfter != null) {
factory.add("revokedAfter", Util.dateToString(revokedAfter));
}
if (expireBefore != null) {
factory.add("expireBefore", Util.dateToString(expireBefore));
}
if (expireAfter != null) {
factory.add("expireAfter", Util.dateToString(expireAfter));
}
if (caName != null) {
factory.add(HFCAClient.FABRIC_CA_REQPROP, caName);
}
JsonObject jsonObject = factory.build();
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
jsonWriter.writeObject(jsonObject);
jsonWriter.close();
String body = stringWriter.toString();
//---------------------------------------
// send revoke request
JsonObject ret = httpPost(url + HFCA_GENCRL, body, registrar);
return ret.getString("CRL");
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new GenerateCRLException(e.getMessage(), e);
}
}
/**
* Creates a new HFCA Identity object
*
* @param enrollmentID The enrollment ID associated for this identity
* @return HFCAIdentity object
* @throws InvalidArgumentException Invalid (null) argument specified
*/
public HFCAIdentity newHFCAIdentity(String enrollmentID) throws InvalidArgumentException {
return new HFCAIdentity(enrollmentID, this);
}