/
Request.java
328 lines (293 loc) · 12.2 KB
/
Request.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
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common 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/cpl-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 CPL, 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 CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ext.openssl;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.io.IOException;
import java.io.StringWriter;
import java.security.GeneralSecurityException;
import java.security.PublicKey;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.DERString;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.openssl.x509store.PEMInputOutput;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.builtin.IRubyObject;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
public class Request extends RubyObject {
private static final long serialVersionUID = -5551557929791764918L;
private static ObjectAllocator REQUEST_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new Request(runtime, klass);
}
};
public static void createRequest(Ruby runtime, RubyModule mX509) {
RubyClass cRequest = mX509.defineClassUnder("Request",runtime.getObject(),REQUEST_ALLOCATOR);
RubyClass openSSLError = runtime.getModule("OpenSSL").getClass("OpenSSLError");
mX509.defineClassUnder("RequestError",openSSLError,openSSLError.getAllocator());
cRequest.defineAnnotatedMethods(Request.class);
}
private IRubyObject version;
private IRubyObject subject;
private IRubyObject public_key;
private boolean valid = false;
private List<IRubyObject> attrs;
private PKCS10CertificationRequestExt req;
public Request(Ruby runtime, RubyClass type) {
super(runtime,type);
attrs = new ArrayList<IRubyObject>();
}
@JRubyMethod(name="initialize", frame=true, rest=true)
public IRubyObject _initialize(IRubyObject[] args, Block block) {
if(org.jruby.runtime.Arity.checkArgumentCount(getRuntime(),args,0,1) == 0) {
return this;
}
byte[] req_bytes = OpenSSLImpl.readX509PEM(args[0]);
req = new PKCS10CertificationRequestExt(req_bytes);
version = getRuntime().newFixnum(req.getVersion());
String algo = null;
byte[] enc = null;
try {
PublicKey pkey = (PublicKey) OpenSSLReal.getWithBCProvider(new OpenSSLReal.Callable() {
public Object call() throws GeneralSecurityException {
return req.getPublicKey("BC");
}
});
algo = pkey.getAlgorithm();
enc = pkey.getEncoded();
} catch (GeneralSecurityException gse) {
throw newX509ReqError(getRuntime(), gse.getMessage());
}
if("RSA".equalsIgnoreCase(algo)) {
this.public_key = Utils.newRubyInstance(getRuntime(), "OpenSSL::PKey::RSA", RubyString.newString(getRuntime(), enc));
} else if("DSA".equalsIgnoreCase(algo)) {
this.public_key = Utils.newRubyInstance(getRuntime(), "OpenSSL::PKey::DSA", RubyString.newString(getRuntime(), enc));
} else {
throw getRuntime().newLoadError("not implemented algo for public key: " + algo);
}
org.bouncycastle.asn1.x509.X509Name subName = req.getCertificationRequestInfo().getSubject();
subject = Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Name");
DERSequence subNameD = (DERSequence)subName.toASN1Object();
for(int i=0;i<subNameD.size();i++) {
DERSequence internal = (DERSequence)((DERSet)subNameD.getObjectAt(i)).getObjectAt(0);
Object oid = internal.getObjectAt(0);
Object v = null;
if(internal.getObjectAt(1) instanceof DERString) {
v = ((DERString)internal.getObjectAt(1)).getString();
}
Object t = getRuntime().newFixnum(ASN1.idForClass(internal.getObjectAt(1).getClass()));
((X509Name)subject).addEntry(oid,v,t);
}
ASN1Set in_attrs = req.getCertificationRequestInfo().getAttributes();
for(Enumeration enm = in_attrs.getObjects();enm.hasMoreElements();) {
DERSet obj = (DERSet)enm.nextElement();
for(Enumeration enm2 = obj.getObjects();enm2.hasMoreElements();) {
DERSequence val = (DERSequence)enm2.nextElement();
DERObjectIdentifier v0 = (DERObjectIdentifier)val.getObjectAt(0);
DERObject v1 = (DERObject)val.getObjectAt(1);
IRubyObject a1 = getRuntime().newString(ASN1.getSymLookup(getRuntime()).get(v0));
IRubyObject a2 = ASN1.decode(getRuntime().getClassFromPath("OpenSSL::ASN1"), RubyString.newString(getRuntime(), v1.getDEREncoded()));
add_attribute(Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Attribute", new IRubyObject[] { a1, a2 }));
}
}
this.valid = true;
return this;
}
@Override
@JRubyMethod
public IRubyObject initialize_copy(IRubyObject obj) {
System.err.println("WARNING: unimplemented method called: init_copy");
if(this == obj) {
return this;
}
checkFrozen();
version = getRuntime().getNil();
subject = getRuntime().getNil();
public_key = getRuntime().getNil();
return this;
}
@JRubyMethod(name={"to_pem","to_s"})
public IRubyObject to_pem() {
StringWriter w = new StringWriter();
try {
PEMInputOutput.writeX509Request(w, req);
return getRuntime().newString(w.toString());
} catch (IOException ex) {
throw getRuntime().newIOErrorFromException(ex);
}
finally {
try { w.close(); } catch( Exception e ) {}
}
}
@JRubyMethod
public IRubyObject to_der() {
return RubyString.newString(getRuntime(), req.getDEREncoded());
}
@JRubyMethod
public IRubyObject to_text() {
System.err.println("WARNING: unimplemented method called: to_text");
return getRuntime().getNil();
}
@JRubyMethod
public IRubyObject version() {
return this.version;
}
@JRubyMethod(name="version=")
public IRubyObject set_version(IRubyObject val) {
if(val != version) {
valid = false;
}
this.version = val;
if(!val.isNil() && req != null) {
req.setVersion(RubyNumeric.fix2int(val));
}
return val;
}
@JRubyMethod
public IRubyObject subject() {
return this.subject;
}
@JRubyMethod(name="subject=")
public IRubyObject set_subject(IRubyObject val) {
if(val != subject) {
valid = false;
}
this.subject = val;
return val;
}
@JRubyMethod
public IRubyObject signature_algorithm() {
System.err.println("WARNING: unimplemented method called: signature_algorithm");
return getRuntime().getNil();
}
@JRubyMethod
public IRubyObject public_key() {
return this.public_key;
}
@JRubyMethod(name="public_key=")
public IRubyObject set_public_key(IRubyObject val) {
if(val != public_key) {
valid = false;
}
this.public_key = val;
return val;
}
@JRubyMethod
public IRubyObject sign(final IRubyObject key, final IRubyObject digest) {
final String keyAlg = ((PKey)public_key).getAlgorithm();
final String digAlg = ((Digest)digest).getShortAlgorithm();
if(("DSA".equalsIgnoreCase(keyAlg) && "MD5".equalsIgnoreCase(digAlg)) ||
("RSA".equalsIgnoreCase(keyAlg) && "DSS1".equals(((Digest)digest).name().toString())) ||
("DSA".equalsIgnoreCase(keyAlg) && "SHA1".equals(((Digest)digest).name().toString()))) {
throw newX509ReqError(getRuntime(), null);
}
final ASN1EncodableVector v1 = new ASN1EncodableVector();
for(Iterator<IRubyObject> iter = attrs.iterator();iter.hasNext();) {
v1.add(((Attribute)iter.next()).toASN1());
}
try {
// PKCS10CertificationRequestExt depends BC.
OpenSSLReal.doWithBCProvider(new OpenSSLReal.Runnable() {
public void run() throws GeneralSecurityException {
req = new PKCS10CertificationRequestExt(digAlg + "WITH" + keyAlg,
((X509Name) subject).getRealName(),
((PKey) public_key).getPublicKey(),
new DERSet(v1),
((PKey) key).getPrivateKey(),
"BC");
}
});
} catch (GeneralSecurityException gse) {
throw newX509ReqError(getRuntime(), gse.getMessage());
}
req.setVersion(RubyNumeric.fix2int(version));
valid = true;
return this;
}
@JRubyMethod
public IRubyObject verify(IRubyObject key) {
try {
return valid && req.verify(((PKey)(key.callMethod(getRuntime().getCurrentContext(),"public_key"))).getPublicKey()) ? getRuntime().getTrue() : getRuntime().getFalse();
} catch(Exception e) {
return getRuntime().getFalse();
}
}
@JRubyMethod
public IRubyObject attributes() {
return getRuntime().newArray(attrs);
}
@SuppressWarnings("unchecked")
@JRubyMethod(name="attributes=")
public IRubyObject set_attributes(IRubyObject val) {
valid = false;
attrs.clear();
attrs.addAll(((RubyArray)val).getList());
if(req != null) {
ASN1EncodableVector v1 = new ASN1EncodableVector();
for(Iterator<IRubyObject> iter = attrs.iterator();iter.hasNext();) {
v1.add(((Attribute)iter.next()).toASN1());
}
req.setAttributes(new DERSet(v1));
}
return val;
}
@JRubyMethod
public IRubyObject add_attribute(IRubyObject val) {
valid = false;
attrs.add(val);
if(req != null) {
ASN1EncodableVector v1 = new ASN1EncodableVector();
for(Iterator<IRubyObject> iter = attrs.iterator();iter.hasNext();) {
v1.add(((Attribute)iter.next()).toASN1());
}
req.setAttributes(new DERSet(v1));
}
return getRuntime().getNil();
}
private static RaiseException newX509ReqError(Ruby runtime, String message) {
return Utils.newError(runtime, "OpenSSL::X509::RequestError", message);
}
}// Request