summaryrefslogtreecommitdiffstats
path: root/pki/base/silent/src/common/Con2Agent.java
blob: bbf7a12b28d8bdf2825b74366e179fa3b83e4df6 (plain)
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
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---

import java.net.*;
import java.io.*;
import java.util.*;
import java.math.*;

import org.mozilla.jss.*;
import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.util.*;
import org.mozilla.jss.ssl.*;
import org.mozilla.jss.crypto.*;
import org.mozilla.jss.CertDatabaseException;
import org.mozilla.jss.pkcs11.*;
import org.mozilla.jss.pkcs11.PK11Token;

import sun.misc.*;
import java.lang.Exception;
import java.security.*;
import java.net.URLEncoder;


/**
 * CMS Test framework .
 * Submits a requests to agent port with sslclient authentication.
 */

public class Con2Agent implements SSLClientCertificateSelectionCallback,
        SSLCertificateApprovalCallback {

    private int i, port;
    private String host, certdir, certnickname, tokenpwd, certname, query;
    private String ACTIONURL;

    private BufferedReader stdin = null;
    private StringBuffer stdout = new StringBuffer();

    public Con2Agent() {}

    /**
     *Constructor. Takes hostname , portnumber , certificate nickname, token password ,client certdb directory 
     * @param        hostname
     * @param portnumber
     * @param agent cert nickname
     * @param token password 
     * @param certdb directory
     */


    public Con2Agent(String hs, int p, String cname, String tpwd, String cdir) {
        host = hs;
        port = p;
        certnickname = cname;
        tokenpwd = tpwd;
        certdir = cdir;
    }

    public boolean approve(X509Certificate x509, SSLCertificateApprovalCallback.ValidityStatus status) {
        return true;
    }

    public String select(Vector nicknames) {
        Enumeration e = nicknames.elements();

        System.out.println("nicknames size = " + nicknames.size());
        int i = 0;

        while (e.hasMoreElements()) {
            String s = (String) e.nextElement();

            i++;
        }

        if (i > 0) {
            return (String) nicknames.elementAt(0);
        } else {
            return null;
        }

    }

    // Get and Set methods 

    /*
     * Get the page returned by the server 
     */

    public StringBuffer getPage() {
        return stdout;
    }

    /*
     * Set the query string to be submitted to the server 
     */

    public void setQueryString(String qu) {
        query = qu;
    }

    /*
     *Set token password 
     */

    public void setTokenPassword(String pwd) {
        tokenpwd = pwd;
    }

    /*
     * Set Client cert database
     */

    public void setCertDBDir(String cdir) {
        certdir = cdir;
    }

    /*
     * Set host name
     */

    public void setHost(String hs) {
        host = hs;
    }

    /*
     * set Agent port number 
     */

    public void setPort(int p) {
        port = p;
    }

    /*
     * Set Agent cert nickname 
     */

    public void setCertNickName(String cname) {
        certnickname = cname;
    }

    /*
     * Set action URL 
     */

    public void setActionURL(String url) {
        ACTIONURL = url;
    }

    // Submit requests 

    public boolean Send() {
        boolean st = false;

        try {

            if (!loginCertDB()) { 
                return false;
            }

            SSLSocket socket = new SSLSocket(host, port, null, 0, this, null);

            System.out.println("Con2Agent.java: host = " + host);
            System.out.println("Con2Agent.java: port = " + port);
            System.out.println("Con2Agent.java: certnickname = " + certnickname);

            socket.setClientCertNickname(certnickname);
            System.out.println("Connected to the socket");

            OutputStream rawos = socket.getOutputStream();
            BufferedOutputStream os = new BufferedOutputStream(rawos);
            PrintStream ps = new PrintStream(os);
	
            System.out.println(ACTIONURL);
            System.out.println("Query :" + query);
            ps.println("POST " + ACTIONURL + " HTTP/1.0");
            ps.println("Connection: Keep-Alive");
            ps.println("Content-type: application/x-www-form-urlencoded");
            ps.println("Content-length: " + query.length());
            ps.println("");
            ps.println(query);
            ps.println("\r");
            ps.flush();
            os.flush();
            BufferedReader stdin1 = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            String line;

            while ((line = stdin1.readLine()) != null) {
                stdout.append(line + "\n");
                System.out.println(line);
            }

            // Send Connection: close to let the server close the connection. 
            // Else the socket on the server side continues to remain in TIME_WAIT state

            ps.println("Connection: close");
            ps.flush();
            os.flush();
            os.close();
            rawos.close();
            ps.close();
            stdin1.close();
            socket.close();

            if (socket.isClosed()) {
                System.out.println("Con2Agent.java : Socket is Closed");
            } else {
                System.out.println("Con2Agent.java : Socket not Closed");
            }

        } catch (Exception e) {
            System.out.println("some exception: in Send routine" + e);
            return false;
        }

        return true;

    }

    private boolean loginCertDB() {
        CryptoManager manager;
        Password pass1 = null, pass2 = null;

        try {
            System.out.println("Step 1: Initializing CryptoManager");
            CryptoManager.initialize(certdir);
	
            System.out.println("Step 2: Login to Cert Database");	
            manager = CryptoManager.getInstance();
            CryptoToken token = (PK11Token) manager.getInternalKeyStorageToken();

            if (token.isLoggedIn()) { 
                System.out.println("Con2Agent: Logged in incorrect");
            }

            System.out.println("tokenpwd:" + tokenpwd);
            char[] passchar1 = new char[tokenpwd.length()];

            tokenpwd.getChars(0, tokenpwd.length(), passchar1, 0);

            pass1 = new Password((char[]) passchar1.clone());
            token.login(pass1);

            X509Certificate cert2 = manager.findCertByNickname(certnickname);	

            certname = cert2.getNickname();
            return true;

        } catch (AlreadyInitializedException  e) {
            System.out.println("Crypto manager already initialized");
            return true;
        } catch (NumberFormatException e) {
            System.err.println("Invalid key size: " + e);
            return false;
        } catch (java.security.InvalidParameterException e) {
            System.err.println("Invalid key size: " + e);
            return false;

        } catch (Exception e) {
            System.err.println("some exception:" + e);
            e.printStackTrace();
            return false;
        }
		
    }

    public boolean Send_withGET() {

        boolean st = false;

        try {

            if (!loginCertDB()) { 
                return false;
            }

            SSLSocket socket = new SSLSocket(host, port, null, 0, this, null);

            socket.setClientCertNickname(certnickname);
            System.out.println("Connected to the socket");

            OutputStream rawos = socket.getOutputStream();
            BufferedOutputStream os = new BufferedOutputStream(rawos);
            PrintStream ps = new PrintStream(os);
	
            System.out.println("Query in con2agent :" + query);
            System.out.println("ACTIONURL in con2agent : " + ACTIONURL);

            ps.println("GET " + ACTIONURL + query + " HTTP/1.0");
            ps.println("");
            ps.println("\r");
            ps.flush();
            os.flush();
            BufferedReader stdin2 = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            String line;

            while ((line = stdin2.readLine()) != null) {
                stdout.append(line + "\n");
            }
            stdin2.close();

            socket.close();

        } catch (Exception e) {
            System.err.println("some exception: in Send routine" + e);
            return false;
        }

        return true;

    }

} // end of class