forked from jruby/jruby-openssl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathX509Cert.java
More file actions
859 lines (726 loc) · 33.1 KB
/
X509Cert.java
File metadata and controls
859 lines (726 loc) · 33.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
/***** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 1.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.eclipse.org/legal/epl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006, 2007 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ext.openssl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DLSequence;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.joda.time.DateTime;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyFixnum;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.RubyTime;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.openssl.impl.ASN1Registry;
import org.jruby.ext.openssl.x509store.PEMInputOutput;
import org.jruby.ext.openssl.x509store.X509AuxCertificate;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.util.ByteList;
import static org.jruby.ext.openssl.X509._X509;
import static org.jruby.ext.openssl.X509Extension.newExtension;
import static org.jruby.ext.openssl.X509CRL.extensions_to_text;
import static org.jruby.ext.openssl.StringHelper.appendGMTDateTime;
import static org.jruby.ext.openssl.StringHelper.appendLowerHexValue;
import static org.jruby.ext.openssl.StringHelper.lowerHexBytes;
import static org.jruby.ext.openssl.OpenSSL.debug;
import static org.jruby.ext.openssl.OpenSSL.debugStackTrace;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
public class X509Cert extends RubyObject {
private static final long serialVersionUID = -6524431607032364369L;
static void createX509Cert(final Ruby runtime, final RubyModule X509, final RubyClass OpenSSLError) {
RubyClass Certificate = X509.defineClassUnder("Certificate", runtime.getObject(), (r, klass) -> new X509Cert(r, klass));
X509.defineClassUnder("CertificateError", OpenSSLError, OpenSSLError.getAllocator());
Certificate.defineAnnotatedMethods(X509Cert.class);
}
public X509Cert(Ruby runtime, RubyClass type) {
super(runtime, type);
}
private X509Cert(Ruby runtime) {
super(runtime, _Certificate(runtime));
}
private IRubyObject subject;
private IRubyObject issuer;
private BigInteger serial = BigInteger.ZERO;
private RubyTime not_before;
private RubyTime not_after;
private IRubyObject sig_alg;
private IRubyObject version;
private X509Certificate cert;
private transient PKey public_key; // lazy initialized
private final List<X509Extension> extensions = new ArrayList<>(4);
private boolean changed = true;
final X509AuxCertificate getAuxCert() {
if ( cert == null ) return null;
if ( cert instanceof X509AuxCertificate ) {
return (X509AuxCertificate) cert;
}
return new X509AuxCertificate(cert);
}
public static IRubyObject wrap(Ruby runtime, Certificate cert)
throws CertificateEncodingException {
return wrap(runtime.getCurrentContext(), cert);
}
static X509Cert wrap(ThreadContext context, Certificate cert)
throws CertificateEncodingException {
if (cert instanceof X509Certificate) {
final X509Cert c = new X509Cert(context.runtime);
c.initialize(context, (X509Certificate) cert);
return c;
}
return wrap(context, cert.getEncoded());
}
// this is the javax.security counterpart of the previous wrap method
public static IRubyObject wrap(Ruby runtime, javax.security.cert.Certificate cert)
throws javax.security.cert.CertificateEncodingException {
return wrap(runtime.getCurrentContext(), cert.getEncoded());
}
static X509Cert wrap(final ThreadContext context, final byte[] encoded) {
final X509Cert cert = new X509Cert(context.runtime);
cert.initialize(context, encoded);
return cert;
}
@JRubyMethod(name="initialize", optional = 1, visibility = Visibility.PRIVATE)
public IRubyObject initialize(final ThreadContext context, final IRubyObject[] args, final Block unusedBlock) {
if ( args.length == 0 ) {
this.subject = X509Name.newName(context.runtime);
this.issuer = X509Name.newName(context.runtime);
return this;
}
final RubyString str = StringHelper.readPossibleDERInput(context, args[0]);
final ByteList bytes = str.getByteList();
initialize(context, bytes.unsafeBytes(), bytes.getBegin(), bytes.getRealSize());
return this;
}
private void initialize(final ThreadContext context, final byte[] encoded) {
initialize(context, encoded, 0, encoded.length);
}
private void initialize(final ThreadContext context, final byte[] encoded, final int offset, final int length) {
byte[] bytes = StringHelper.readX509PEM(encoded, offset, length);
final X509Certificate cert;
try {
final ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
cert = (X509Certificate) SecurityHelper.getCertificateFactory("X.509").generateCertificate(bis);
}
catch (CertificateException e) {
throw newCertificateError(context.runtime, e);
}
initialize(context, cert);
}
private void initialize(final ThreadContext context, final X509Certificate cert) {
final Ruby runtime = context.runtime;
if ( cert == null ) {
throw newCertificateError(runtime, (String) null);
}
this.cert = cert;
set_serial( RubyNumeric.str2inum(runtime, runtime.newString(cert.getSerialNumber().toString()), 10) );
set_not_before( context, RubyTime.newTime( runtime, cert.getNotBefore().getTime() ) );
set_not_after( context, RubyTime.newTime( runtime, cert.getNotAfter().getTime() ) );
this.subject = X509Name.newName(runtime, cert.getSubjectX500Principal());
this.issuer = X509Name.newName(runtime, cert.getIssuerX500Principal());
this.version = RubyFixnum.newFixnum(runtime, cert.getVersion() - 1);
String sigAlgorithm = cert.getSigAlgOID();
if ( sigAlgorithm == null ) sigAlgorithm = cert.getSigAlgName(); // e.g. SHA256withRSA
else {
sigAlgorithm = ASN1.oid2name(runtime, new ASN1ObjectIdentifier(sigAlgorithm), true);
if (sigAlgorithm == null) {
sigAlgorithm = "0.0"; // "NULL";
// for some certificates that MRI parses,
// we get getSigAlgOID() == getSigAlgName() == "0.0"
if ( cert.getSigAlgName() != null && ! cert.getSigAlgOID().equals(cert.getSigAlgName()) ) {
sigAlgorithm = cert.getSigAlgName(); // not sure if it makes any sense
}
}
} // "hot" path e.g. sha256WithRSAEncryption
this.sig_alg = RubyString.newString(runtime, sigAlgorithm);
final Set<String> criticalExtOIDs = cert.getCriticalExtensionOIDs();
if ( criticalExtOIDs != null ) {
for ( final String extOID : criticalExtOIDs ) {
addExtension(context, extOID, true);
}
}
final Set<String> nonCriticalExtOIDs = cert.getNonCriticalExtensionOIDs();
if ( nonCriticalExtOIDs != null ) {
for ( final String extOID : nonCriticalExtOIDs ) {
addExtension(context, extOID, false);
}
}
changed = false;
}
private void addExtension(final ThreadContext context,
final String extOID, final boolean critical) {
try {
final byte[] extValue = cert.getExtensionValue(extOID);
if ( extValue == null ) return;
final X509Extension[] extension = newExtension(context, extOID, extValue, critical);
for ( int i = 0; i < extension.length; i++ ) this.extensions.add( extension[i] );
}
catch (IOException e) { throw newCertificateError(context.runtime, e); }
}
private static RubyClass _CertificateError(final Ruby runtime) {
return _X509(runtime).getClass("CertificateError");
}
static RubyClass _Certificate(final Ruby runtime) {
return _X509(runtime).getClass("Certificate");
}
public static RaiseException newCertificateError(final Ruby runtime, Exception e) {
return Utils.newError(runtime, _CertificateError(runtime), e);
}
static RaiseException newCertificateError(final Ruby runtime, String msg) {
return Utils.newError(runtime, _CertificateError(runtime), msg);
}
static RaiseException newCertificateError(final Ruby runtime, String msg, Exception e) {
return Utils.newError(runtime, _CertificateError(runtime), msg, e);
}
@Override
@JRubyMethod(visibility = Visibility.PRIVATE)
public IRubyObject initialize_copy(IRubyObject obj) {
if ( this == obj ) return this;
checkFrozen();
super.initialize_copy(obj);
final Ruby runtime = getRuntime();
final X509Cert other = (X509Cert) obj;
this.subject = copyName(runtime, other.subject);
this.issuer = copyName(runtime, other.issuer);
this.serial = other.serial;
this.not_before = copyTime(runtime, other.not_before);
this.not_after = copyTime(runtime, other.not_after);
this.sig_alg = other.sig_alg == null ? null : other.sig_alg.dup();
this.version = other.version;
this.cert = copyCertificate(runtime, other.cert);
this.public_key = other.public_key == null ? null : (PKey) other.public_key.dup();
this.extensions.clear();
for ( X509Extension ext : other.extensions ) {
this.extensions.add( (X509Extension) ext.dup() );
}
this.changed = other.changed;
return this;
}
private static IRubyObject copyName(final Ruby runtime, final IRubyObject name) {
if ( name == null || name.isNil() ) return name;
return X509Name.newName(runtime, ((X509Name) name).getX500Name());
}
private static RubyTime copyTime(final Ruby runtime, final RubyTime time) {
return time == null ? null : RubyTime.newTime(runtime, time.getJavaDate().getTime());
}
private static X509Certificate copyCertificate(final Ruby runtime, final X509Certificate cert) {
if ( cert == null ) return null;
try {
final ByteArrayInputStream bis = new ByteArrayInputStream(cert.getEncoded());
return (X509Certificate) SecurityHelper.getCertificateFactory("X.509").generateCertificate(bis);
}
catch (CertificateException e) {
throw newCertificateError(runtime, e);
}
}
@JRubyMethod
public IRubyObject to_der() {
try {
return StringHelper.newString(getRuntime(), cert.getEncoded());
}
catch (CertificateEncodingException ex) {
throw newCertificateError(getRuntime(), ex);
}
}
@JRubyMethod
public IRubyObject tbs_bytes() {
if ( cert == null ) {
throw newCertificateError(getRuntime(), "no certificate");
}
try {
return StringHelper.newString(getRuntime(), cert.getTBSCertificate());
}
catch (CertificateEncodingException ex) {
throw newCertificateError(getRuntime(), ex);
}
}
@Override
@JRubyMethod(name = "==")
public IRubyObject op_equal(ThreadContext context, IRubyObject obj) {
return equalImpl(context.runtime, obj);
}
private IRubyObject equalImpl(final Ruby runtime, IRubyObject obj) {
if ( this == obj ) return runtime.getTrue();
if ( obj instanceof X509Cert ) {
final X509Certificate cert = this.cert;
final X509Certificate otherCert = ((X509Cert) obj).cert;
if ( cert == null || otherCert == null ) return runtime.getFalse();
final boolean equal;
try {
equal = Arrays.equals(cert.getEncoded(), otherCert.getEncoded());
}
catch (CertificateEncodingException e) {
throw newCertificateError(runtime, e);
}
return runtime.newBoolean(equal);
}
return runtime.getFalse();
}
@Override
public IRubyObject eql_p(IRubyObject obj) {
return equalImpl(getRuntime(), obj);
}
@JRubyMethod(name = {"to_pem", "to_s"})
public IRubyObject to_pem() {
final StringWriter str = new StringWriter();
try {
PEMInputOutput.writeX509Certificate(str, getAuxCert());
return getRuntime().newString( str.toString() );
}
catch (IOException ex) {
throw getRuntime().newIOErrorFromException(ex);
}
}
@JRubyMethod
public IRubyObject to_text(final ThreadContext context) {
final Ruby runtime = context.runtime;
final char[] S20 = StringHelper.S20;
final StringBuilder text = new StringBuilder(240);
text.append("Certificate:\n");
text.append(S20,0,4).append("Data:\n");
final int version = this.version == null ? 0 : RubyNumeric.fix2int(this.version);
text.append(S20,0,8).append("Version: ").append( version + 1 ).
append(" (0x").append( Integer.toString( version, 16 ) ).append(")\n");
// <= 0x1122334455667788 printed on same line as :
// Serial Number: 1234605616436508552 (0x1122334455667788)
// but 0x112233445566778899 ends up :
// Serial Number:
// 11:22:33:44:55:66:77:88:99
text.append(S20,0,8).append("Serial Number:");
if ( serial.compareTo( new BigInteger("FFFFFFFFFFFFFFFF", 16) ) > 0 ) {
text.append('\n');
text.append(S20,0,12).append( lowerHexBytes(serial.toByteArray(), 1) ).append('\n');
}
else {
text.append(' ').append(serial.toString(10)).append(' ');
text.append('(').append("0x").append(serial.toString(16)).append(')').append('\n');
}
text.append(S20,0,4).append("Signature Algorithm: ").append( signature_algorithm() ).append('\n');
//final RubyString issuer = issuer().asString(); ByteList bytes = issuer.getByteList();
//StringHelper.gsub(runtime, bytes, (byte) '/', (byte) ' ');
//if ( bytes.charAt(0) == ' ' ) bytes.setBegin(bytes.getBegin() + 1);
text.append(S20,0,8).append("Issuer: ").append( issuer ).append('\n');
text.append(S20,0,8).append("Validity\n");
text.append(S20,0,12).append("Not Before: ");
appendGMTDateTime( text, getNotBefore() ).append('\n');
text.append(S20,0,12).append("Not After : ");
appendGMTDateTime( text, getNotAfter() ).append('\n');
text.append(S20,0,8).append("Subject: ").append( subject() ).append('\n');
text.append(S20,0,8).append("Subject Public Key Info:\n");
final PublicKey publicKey = getPublicKey();
text.append(S20,0,12).append("Public Key Algorithm: ").append(publicKey.getAlgorithm()).append('\n');
if (publicKey instanceof RSAPublicKey) {
final RSAPublicKey rsaKey = ((RSAPublicKey) publicKey);
text.append(S20,0,16).append("Public-Key: (").append( rsaKey.getModulus().bitLength() ).append(" bit)\n");
text.append(S20,0,16).append("Modulus:\n");
appendLowerHexValue(text, rsaKey.getModulus().toByteArray(), 20, 45);
final BigInteger exponent = rsaKey.getPublicExponent();
text.append(S20,0,16).append("Exponent: ").append(exponent).
append(" (0x").append( exponent.toString(16) ).append(")\n");
}
else if (publicKey instanceof DSAPublicKey) {
final DSAPublicKey dsaKey = ((DSAPublicKey) publicKey);
text.append(S20,0,16).append("Public-Key: (").append( dsaKey.getY().bitLength() ).append(" bit)\n");
text.append(S20,0,16).append("TODO: not-implemented (PR HOME-WORK)").append('\n'); // left-TODO
}
else { // "EC" or "ECDSA"
text.append(S20,0,16).append("TODO: not-implemented (PRs WELCOME!)").append('\n'); // left-TODO
}
if ( extensions != null && extensions.size() > 0 ) {
text.append(S20,0,8).append("X509v3 extensions:\n");
extensions_to_text(context, extensions, text, 12);
}
text.append(S20,0,4).append("Signature Algorithm: ").append( signature_algorithm() ).append('\n');
appendLowerHexValue(text, getSignature(), 9, 54);
return RubyString.newString( runtime, text );
}
@Override
@JRubyMethod
@SuppressWarnings("unchecked")
public IRubyObject inspect() {
final ArrayList<Variable<String>> varList = new ArrayList<Variable<String>>(5);
varList.add(new VariableEntry<String>( "subject", subject().isNil() ? "nil" : subject().asString().toString() ));
varList.add(new VariableEntry<String>( "issuer", issuer().isNil() ? "nil" : issuer().asString().toString() ));
varList.add(new VariableEntry<String>( "serial", serial().isNil() ? "nil" : serial().asString().toString() ));
varList.add(new VariableEntry<String>( "not_before", not_before().isNil() ? "nil" : not_before().toString() ));
varList.add(new VariableEntry<String>( "not_after", not_after().isNil() ? "nil" : not_after().toString() ));
return ObjectSupport.inspect(this, (List) varList);
}
@JRubyMethod
public IRubyObject version() {
return version != null ? version : ( version = getRuntime().newFixnum(0) );
}
@JRubyMethod(name = "version=")
public IRubyObject set_version(final IRubyObject version) {
if ( ! version().equals(version) ) {
this.changed = true;
}
return this.version = version;
}
@JRubyMethod
public IRubyObject signature_algorithm() {
return sig_alg;
}
private byte[] getSignature() {
return cert.getSignature();
}
BigInteger getSerial() { return serial; }
@JRubyMethod
public IRubyObject serial() {
return BN.newBN(getRuntime(), serial);
}
@JRubyMethod(name = "serial=")
public IRubyObject set_serial(final IRubyObject serial) {
final String serialStr = serial.asString().toString();
final BigInteger serialInt;
if ( serialStr.equals("0") ) { // MRI compatibility: allow 0 serial number
serialInt = BigInteger.ONE;
} else {
serialInt = new BigInteger(serialStr);
}
this.changed = ! serialInt.equals(this.serial);
//generator.setSerialNumber( serialInt.abs() );
this.serial = serialInt; return serial;
}
X509Name getSubject() { return ((X509Name) subject); }
@JRubyMethod
public IRubyObject subject() {
return subject;
}
@JRubyMethod(name = "subject=")
public IRubyObject set_subject(final IRubyObject subject) {
if ( ! subject.equals(this.subject) ) this.changed = true;
return this.subject = subject;
}
X509Name getIssuer() { return ((X509Name) issuer); }
@JRubyMethod
public IRubyObject issuer() {
return issuer;
}
@JRubyMethod(name = "issuer=")
public IRubyObject set_issuer(final IRubyObject issuer) {
if ( ! issuer.equals(this.issuer) ) this.changed = true;
return this.issuer = issuer;
}
@JRubyMethod
public IRubyObject not_before() {
return not_before == null ? getRuntime().getNil() : not_before;
}
@JRubyMethod(name = "not_before=")
public IRubyObject set_not_before(final ThreadContext context, final IRubyObject time) {
changed = true;
not_before = (RubyTime) time.callMethod(context, "getutc");
not_before.setMicroseconds(0);
return time;
}
DateTime getNotBefore() {
return not_before == null ? null : not_before.getDateTime();
}
@JRubyMethod
public IRubyObject not_after() {
return not_after == null ? getRuntime().getNil() : not_after;
}
@JRubyMethod(name = "not_after=")
public IRubyObject set_not_after(final ThreadContext context, final IRubyObject time) {
changed = true;
not_after = (RubyTime) time.callMethod(context, "getutc");
not_after.setMicroseconds(0);
return time;
}
DateTime getNotAfter() {
return not_after == null ? null : not_after.getDateTime();
}
@JRubyMethod
public IRubyObject public_key(final ThreadContext context) {
if ( public_key == null ) initializePublicKey();
return public_key;
}
@JRubyMethod(name = "public_key=")
public IRubyObject set_public_key(IRubyObject public_key) {
if ( ! ( public_key instanceof PKey ) ) {
throw getRuntime().newTypeError("OpenSSL::PKey::PKey expected but got " + public_key.getMetaClass().getName());
}
if ( ! public_key.equals(this.public_key) ) {
this.changed = true;
}
return this.public_key = (PKey) public_key;
}
private PublicKey getPublicKey() {
if ( public_key == null ) initializePublicKey();
return public_key.getPublicKey();
}
private void initializePublicKey() throws RaiseException {
final Ruby runtime = getRuntime();
final boolean changed = this.changed;
if ( cert == null ) {
throw newCertificateError(runtime, "no certificate");
}
set_public_key(PKey.newInstance(runtime, cert.getPublicKey()));
this.changed = changed;
}
@JRubyMethod
public IRubyObject sign(final ThreadContext context, final IRubyObject key, final IRubyObject digest) {
final Ruby runtime = context.runtime;
if (!(key instanceof PKey)) { // MRI: NoMethodError: undefined method `private?' for nil:NilClass
throw runtime.newTypeError(key, PKey._PKey(runtime).getClass("PKey"));
}
// Have to obey some artificial constraints of the OpenSSL implementation. Stupid.
final String keyAlg = ((PKey) key).getAlgorithm();
final String digAlg; final String digName;
if (digest instanceof Digest) {
digAlg = ((Digest) digest).getShortAlgorithm();
digName = ((Digest) digest).getName();
}
else if (digest instanceof RubyString) {
digAlg = digest.asJavaString(); digName = null;
}
else { // MRI: TypeError: wrong argument type nil (expected OpenSSL/Digest)
throw runtime.newTypeError(digest, Digest._Digest(runtime));
}
if( ( "DSA".equalsIgnoreCase(keyAlg) && "MD5".equalsIgnoreCase(digAlg) ) ||
( "RSA".equalsIgnoreCase(keyAlg) && "DSS1".equals(digName) ) ) {
throw newCertificateError(runtime, "signature_algorithm not supported");
}
final X509v3CertificateBuilder builder = newCertificateBuilder();
for ( X509Extension ext : uniqueExtensions() ) {
try {
final byte[] bytes = ext.getRealValueEncoded();
builder.addExtension(ext.getRealObjectID(), ext.isRealCritical(), bytes);
}
catch (IOException e) {
throw newCertificateError(runtime, "invalid extension (" + e.getMessage() + ")", e);
}
}
final X509CertificateHolder certHolder;
try {
ContentSigner signer =
new JcaContentSignerBuilder(digAlg + "WITH" + keyAlg).
build(((PKey) key).getPrivateKey());
certHolder = builder.build(signer);
} catch (OperatorCreationException e) {
Exception cause = (Exception) e.getCause(); // GeneralSecurityException
if (cause == null) cause = e;
throw newCertificateError(runtime, "cannot create signer: " + cause.getMessage(), cause);
} catch (IllegalStateException e) {
// e.g. "not all mandatory fields set in V3 TBScertificate generator"
throw newCertificateError(runtime, "could not generate certificate", e);
} catch (RuntimeException e) {
throw newCertificateError(runtime, e);
}
try {
this.cert = (X509Certificate)
SecurityHelper.getCertificateFactory("X.509").
generateCertificate(new ByteArrayInputStream(certHolder.getEncoded()));
} catch (IOException|CertificateException e) {
throw newCertificateError(runtime, "could not re-generate certificate", e);
}
String name = ASN1Registry.o2a(certHolder.getSignatureAlgorithm().getAlgorithm());
if ( name == null ) name = cert.getSigAlgOID();
this.sig_alg = runtime.newString(name);
this.changed = false;
return this;
}
private X509v3CertificateBuilder newCertificateBuilder() {
//if ( serial.equals(BigInteger.ZERO) ) { // NOTE: diversion from MRI (OpenSSL allows not setting serial)
// throw newCertificateError(getRuntime(), "Certificate#serial needs to be set (to > 0)");
//}
SubjectPublicKeyInfo publicKeyInfo;
try {
publicKeyInfo = SubjectPublicKeyInfo.getInstance(public_key.getPublicKey().getEncoded());
} catch (Exception e) {
throw newCertificateError(getRuntime(), "invalid public key data", e);
}
return new X509v3CertificateBuilder(
issuer == null ? null : ((X509Name) issuer).getX500Name(),
serial.abs(),
not_before != null ? not_before.getJavaDate() : new Date(0),
not_after != null ? not_after.getJavaDate() : new Date(0),
subject == null ? null : ((X509Name) subject).getX500Name(),
publicKeyInfo
);
}
@JRubyMethod
public RubyBoolean verify(final IRubyObject key) {
final Ruby runtime = getRuntime();
if ( changed ) return runtime.getFalse();
try {
cert.verify(((PKey) key).getPublicKey());
return runtime.getTrue();
}
catch (CertificateException e) {
debugStackTrace(runtime, "X509Cert#verify", e);
throw newCertificateError(runtime, e);
}
catch (NoSuchProviderException|NoSuchAlgorithmException e) {
debugStackTrace(runtime, e);
throw newCertificateError(runtime, e);
}
catch (SignatureException|InvalidKeyException e) {
debug(runtime, "X509Cert#verify failed", e);
return runtime.getFalse();
}
}
@JRubyMethod
public RubyBoolean check_private_key(final IRubyObject key) {
final PublicKey certPublicKey = cert.getPublicKey();
if ( certPublicKey.equals( ((PKey) key).getPublicKey() ) ) {
return getRuntime().getTrue();
}
return getRuntime().getFalse();
}
@JRubyMethod
public RubyArray extensions() {
@SuppressWarnings("unchecked")
final List<IRubyObject> extensions = (List) this.extensions;
return getRuntime().newArray( extensions );
}
@SuppressWarnings("unchecked")
@JRubyMethod(name = "extensions=")
public IRubyObject set_extensions(final IRubyObject array) {
changed = true;
extensions.clear(); // RubyArray is a List :
extensions.addAll( (List<X509Extension>) array );
return array;
}
@JRubyMethod
public IRubyObject add_extension(final IRubyObject ext) {
changed = true;
extensions.add((X509Extension) ext);
return ext;
}
private Collection<X509Extension> uniqueExtensions() {
final Map<ASN1ObjectIdentifier, X509Extension> unique =
new LinkedHashMap<ASN1ObjectIdentifier, X509Extension>();
for ( X509Extension current : this.extensions ) {
final ASN1ObjectIdentifier oid = current.getRealObjectID();
final X509Extension existing = unique.get( oid );
if ( existing == null ) {
unique.put( oid, current ); continue;
}
// NOTE: dealing with Java API limits here since it does not
// handle multiple OID mappings to a sequence out of the box
// commonly used e.g. with subjectAltName || issuserAltName :
if ( "2.5.29.17".equals( oid.getId() ) || "2.5.29.18".equals( oid.getId() ) ) {
final ASN1EncodableVector vec = new ASN1EncodableVector();
try {
GeneralName[] n1 = extRealNames(existing);
for ( int i = 0; i < n1.length; i++ ) vec.add( n1[i] );
GeneralName[] n2 = extRealNames(current);
for ( int i = 0; i < n2.length; i++ ) vec.add( n2[i] );
GeneralNames nn = GeneralNames.getInstance(new DLSequence(vec));
final X509Extension existingDup = existing.clone();
existingDup.setRealValue( nn );
unique.put( oid, existingDup );
}
catch (IOException ex) { throw getRuntime().newIOErrorFromException(ex); }
continue;
}
// TODO do we need special care for any others here ?!?
final ASN1EncodableVector vec = new ASN1EncodableVector();
try {
final ASN1Encodable existingValue = existing.getRealValue();
if ( existingValue instanceof ASN1Sequence ) {
final ASN1Sequence seq = (ASN1Sequence) existingValue;
for ( int i = 0; i < seq.size(); i++ ) {
vec.add( seq.getObjectAt(i) );
}
}
else {
vec.add(existingValue);
}
vec.add( current.getRealValue() );
// existing.setRealValue( new DLSequence(vec) );
final X509Extension existingDup = existing.clone();
existingDup.setRealValue( new DLSequence(vec) );
unique.put( oid, existingDup );
}
catch (IOException ex) { throw getRuntime().newIOErrorFromException(ex); }
}
return unique.values();
}
private static GeneralName[] extRealNames(final X509Extension extension) throws IOException {
final ASN1Encodable value = extension.getRealValue();
if ( value instanceof GeneralName ) {
return new GeneralName[] { (GeneralName) value };
}
return GeneralNames.getInstance( value ).getNames();
}
@Override
public Object toJava(Class target) {
if ( target.isAssignableFrom(X509Certificate.class) ) {
if ( target == X509AuxCertificate.class ) return getAuxCert();
return cert;
}
return super.toJava(target);
}
}// X509Cert