summaryrefslogtreecommitdiffstats
path: root/base/tks/src/org/dogtagpki/server/tks/rest/TPSConnectorService.java
blob: 36512690aef03882c6414cdeae0337663a916b92 (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
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
package org.dogtagpki.server.tks.rest;

import java.io.IOException;
import java.net.URI;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.jboss.resteasy.plugins.providers.atom.Link;
import org.mozilla.jss.CryptoManager.NotInitializedException;
import org.mozilla.jss.crypto.InvalidKeyFormatException;
import org.mozilla.jss.crypto.TokenException;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.BadRequestException;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.PKIException;
import com.netscape.certsrv.base.ResourceNotFoundException;
import com.netscape.certsrv.base.UnauthorizedException;
import com.netscape.certsrv.key.KeyData;
import com.netscape.certsrv.system.TPSConnectorCollection;
import com.netscape.certsrv.system.TPSConnectorData;
import com.netscape.certsrv.system.TPSConnectorResource;
import com.netscape.certsrv.tps.cert.TPSCertResource;
import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.cms.realm.PKIPrincipal;
import com.netscape.cms.servlet.base.PKIService;
import com.netscape.cmsutil.crypto.CryptoUtil;
import com.netscape.cmsutil.util.Utils;

public class TPSConnectorService extends PKIService implements TPSConnectorResource {

    private static final String TPS_LIST = "tps.list";

    IConfigStore cs = CMS.getConfigStore();

    @Context
    private UriInfo uriInfo;

    @Context
    private HttpServletRequest servletRequest;

    public final static int DEFAULT_SIZE = 20;

    public IUGSubsystem userGroupManager = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);

    @Override
    public Response findConnectors(Integer start, Integer size) {
        try {
            String tpsList = cs.getString(TPS_LIST, "");
            Iterator<String> entries = Arrays.asList(StringUtils.split(tpsList,",")).iterator();

            TPSConnectorCollection response = new TPSConnectorCollection();
            int i = 0;

            // skip to the start of the page
            for ( ; i<start && entries.hasNext(); i++) entries.next();

            // return entries up to the page size
            for ( ; i<start+size && entries.hasNext(); i++) {
                response.addEntry(createTPSConnectorData(entries.next()));
            }

            // count the total entries
            for ( ; entries.hasNext(); i++) entries.next();
            response.setTotal(i);

            if (start > 0) {
                URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
                response.addLink(new Link("prev", uri));
            }

            if (start+size < i) {
                URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
                response.addLink(new Link("next", uri));
            }

            return createOKResponse(response);

        } catch (EBaseException e) {
            e.printStackTrace();
            throw new PKIException("Unable to get TPS connection data: " + e);
        }
    }

    private TPSConnectorData createTPSConnectorData(String tpsID) throws EBaseException {
        TPSConnectorData data = new TPSConnectorData();
        data.setID(tpsID);
        data.setHost(cs.getString("tps." + tpsID + ".host", ""));
        data.setPort(cs.getString("tps." + tpsID + ".port", ""));
        data.setUserID(cs.getString("tps." + tpsID + ".userid", ""));
        data.setNickname(cs.getString("tps." + tpsID + ".nickname", ""));
        URI uri = uriInfo.getBaseUriBuilder().path(TPSCertResource.class).path("{id}").build(tpsID);
        data.setLink(new Link("self", uri));
        return data;
    }

    @Override
    public Response getConnector(String id) {
        return createOKResponse(getConnectorData(id));
    }

    public TPSConnectorData getConnectorData(String id) {

        if (id == null) throw new BadRequestException("TPS connector ID is null.");

        try {
            if (!connectorExists(id))
                throw new ResourceNotFoundException("Connector " + id + " not found.");

            return createTPSConnectorData(id);

        } catch (EBaseException e) {
            e.printStackTrace();
            throw new PKIException("Unable to get TPS connection data" + e);
        }
    }

    @Override
    public Response getConnector(String host, String port) {

        if (host == null) throw new BadRequestException("TPS connector host is null.");
        if (port == null) throw new BadRequestException("TPS connector port is null.");

        try {
            String id = getConnectorID(host, port);
            if (id == null)
                throw new ResourceNotFoundException(
                        "Connector not found for " + host + ":" + port);

            return createOKResponse(createTPSConnectorData(id));

        } catch (EBaseException e) {
            e.printStackTrace();
            throw new PKIException("Unable to get TPS connection data" + e);
        }
    }

    @Override
    public Response createConnector(String tpsHost, String tpsPort) {

        if (tpsHost == null) throw new BadRequestException("TPS connector host is null.");
        if (tpsPort == null) throw new BadRequestException("TPS connector port is null.");

        try {
            String id = getConnectorID(tpsHost, tpsPort);
            if (id != null) {
                URI uri = uriInfo.getBaseUriBuilder().path(TPSCertResource.class)
                        .path("{id}").build(id);
                throw new BadRequestException("TPS connection already exists at " + uri.toString());
            }
            String newID = findNextConnectorID();

            TPSConnectorData newData = new TPSConnectorData();
            newData.setID(newID);
            newData.setHost(tpsHost);
            newData.setPort(tpsPort);
            newData.setUserID("TPS-" + tpsHost + "-" + tpsPort);
            URI uri = uriInfo.getBaseUriBuilder().path(TPSCertResource.class).path("{id}").build(newID);
            newData.setLink(new Link("self", uri));
            saveClientData(newData);

            addToConnectorList(newID);
            cs.commit(true);

            return createCreatedResponse(newData, newData.getLink().getHref());

        } catch (EBaseException e) {
            CMS.debug("Unable to create new TPS Connector: " + e);
            e.printStackTrace();
            throw new PKIException("Unable to create  new TPS connector: " + e);
        }
    }

    @Override
    public Response modifyConnector(String id, TPSConnectorData data) {
        try {
            if (id == null) {
                throw new BadRequestException("Invalid connector ID");
            }

            if (data == null) {
                throw new BadRequestException("Invalid connector data");
            }

            if (!connectorExists(id)) {
                throw new ResourceNotFoundException("TPS connection does not exist");
            }

            // Note: we are deliberately NOT allowing the userid to be modified by the
            // admin here, because this is what maps to a user cert to retrieve the shared
            // secret
            if ((data.getUserID() != null) || (data.getNickname() != null)) {
                throw new UnauthorizedException("Cannot change userid or nickname using this interface");
            }
            TPSConnectorData curData = getConnectorData(id);
            curData.setHost(data.getHost());
            curData.setPort(data.getPort());

            saveClientData(curData);
            cs.commit(true);

            return createOKResponse(curData);

        } catch (EBaseException e) {
            CMS.debug("Unable to modify TPS Connector: " + e);
            e.printStackTrace();
            throw new PKIException("Unable to modify TPS Connector: " + e);
        }
    }

    private void saveClientData(TPSConnectorData newData) throws EBaseException {
        String id = newData.getID();
        if (StringUtils.isEmpty(id)) {
            CMS.debug("saveClientData: Attempt to save tps connection with null or empty id");
            return;
        }
        String prefix = "tps." + id + ".";

        if (newData.getHost() != null)
            cs.putString(prefix + "host", newData.getHost());
        if (newData.getPort() != null)
            cs.putString(prefix + "port", newData.getPort());
        if (newData.getUserID() != null)
            cs.putString(prefix + "userid", newData.getUserID());
        if (newData.getNickname() != null)
            cs.putString(prefix + "nickname", newData.getNickname());
    }

    @Override
    public Response deleteConnector(String id) {
        try {
            if (StringUtils.isEmpty(id))
                throw new BadRequestException("Attempt to delete TPS connection with null or empty id");

            if (!connectorExists(id)) return createNoContentResponse();

            deleteSharedSecret(id);
            cs.removeSubStore("tps." + id);
            removeFromConnectorList(id);
            cs.commit(true);

            return createNoContentResponse();

        } catch (EBaseException e) {
            e.printStackTrace();
            throw new PKIException("Failed to delete TPS connection" + e);
        }
    }

    @Override
    public Response deleteConnector(String host, String port) {

        if (host == null) throw new BadRequestException("TPS connector host is null.");
        if (port == null) throw new BadRequestException("TPS connector port is null.");

        String id;
        try {
            id = getConnectorID(host, port);
            deleteConnector(id);
        } catch (EBaseException e) {
            e.printStackTrace();
            throw new PKIException("Failed to delete TPS connector: " + e);
        }

        return createNoContentResponse();
    }

    @Override
    public Response createSharedSecret(String id) {

        if (id == null) throw new BadRequestException("TPS connector ID is null.");

        try {
            if (!connectorExists(id)) {
                throw new ResourceNotFoundException("TPS connection does not exist");
            }

            // get and validate user
            String userid = validateUser(id);

            // get user cert
            IUser user = userGroupManager.getUser(userid);
            X509Certificate[] certs = user.getX509Certificates();

            String nickname = userid + " sharedSecret";
            if (CryptoUtil.sharedSecretExists(nickname)) {
                throw new BadRequestException("Shared secret already exists");
            }

            CryptoUtil.createSharedSecret(nickname);

            cs.putString("tps." + id + ".nickname", nickname);
            cs.commit(true);

            byte[] wrappedKey = CryptoUtil.exportSharedSecret(nickname, certs[0]);
            KeyData keyData = new KeyData();
            keyData.setWrappedPrivateData(Utils.base64encode(wrappedKey));

            return createOKResponse(keyData);

        } catch (InvalidKeyException | IllegalStateException | NoSuchAlgorithmException
                | InvalidAlgorithmParameterException | EBaseException
                | NotInitializedException | TokenException | IOException | InvalidKeyFormatException e) {
            e.printStackTrace();
            CMS.debug("Error in generating and exporting shared secret: " + e);
            throw new PKIException("Error in generating and exporting shared secret: " + e);
        }
    }

    private String validateUser(String id) throws EBaseException {
        String userid = cs.getString("tps." + id + ".userid", "");
        if (userid.isEmpty()) {
            throw new PKIException("Bad TPS connection configuration: userid not defined");
        }

        PKIPrincipal principal = (PKIPrincipal) servletRequest.getUserPrincipal();
        if (principal == null) {
            throw new UnauthorizedException("User credentials not provided");
        }

        String uid = principal.getName();
        if (!uid.equals(userid)) {
            throw new UnauthorizedException("TPS Connection belongs to another user");
        }
        return userid;
    }

    @Override
    public Response replaceSharedSecret(String id) {

        if (id == null) throw new BadRequestException("TPS connector ID is null.");

        try {
            if (!connectorExists(id)) {
                throw new ResourceNotFoundException("TPS connection does not exist");
            }

            // get and validate user
            String userid = validateUser(id);

            String nickname = userid + " sharedSecret";
            if (!CryptoUtil.sharedSecretExists(nickname)) {
                throw new BadRequestException("Cannot replace. Shared secret does not exist");
            }

            // get user cert
            IUser user = userGroupManager.getUser(userid);
            X509Certificate[] certs = user.getX509Certificates();

            CryptoUtil.deleteSharedSecret(nickname);
            CryptoUtil.createSharedSecret(nickname);
            byte[] wrappedKey = CryptoUtil.exportSharedSecret(nickname, certs[0]);
            KeyData keyData = new KeyData();
            keyData.setWrappedPrivateData(Utils.base64encode(wrappedKey));

            return createOKResponse(keyData);

        } catch (InvalidKeyException | IllegalStateException | NoSuchAlgorithmException
                | InvalidAlgorithmParameterException | EBaseException
                | NotInitializedException | TokenException | IOException | InvalidKeyFormatException e) {
            e.printStackTrace();
            CMS.debug("Error in replacing shared secret: " + e);
            throw new PKIException("Error in replacing shared secret: " + e);
        }
    }

    @Override
    public Response deleteSharedSecret(String id) {

        if (id == null) throw new BadRequestException("TPS connector ID is null.");

        try {
            if (!connectorExists(id)) {
                throw new ResourceNotFoundException("TPS connection does not exist");
            }

            // get user
            String userid = cs.getString("tps." + id + ".userid", "");
            if (userid.isEmpty()) {
                throw new PKIException("Bad TPS connection configuration: userid not defined");
            }

            String nickname = userid + " sharedSecret";
            if (!CryptoUtil.sharedSecretExists(nickname)) {
                return createNoContentResponse();
            }
            CryptoUtil.deleteSharedSecret(nickname);

            cs.putString("tps." + id + ".nickname", "");
            cs.commit(true);

            return createNoContentResponse();

        } catch (InvalidKeyException | IllegalStateException | EBaseException
                | NotInitializedException | TokenException e) {
            e.printStackTrace();
            CMS.debug("Error in deleting shared secret: " + e);
            throw new PKIException("Error in deleting shared secret: " + e);
        }
    }

    @Override
    public Response getSharedSecret(String id) {

        if (id == null) throw new BadRequestException("TPS connector ID is null.");

        try {
            if (!connectorExists(id)) {
                throw new ResourceNotFoundException("TPS connection does not exist");
            }

            // get and validate user
            String userid = validateUser(id);

            String nickname = userid + " sharedSecret";
            if (!CryptoUtil.sharedSecretExists(nickname)) {
                return createNoContentResponse();
            }

            // get user cert
            IUser user = userGroupManager.getUser(userid);
            X509Certificate[] certs = user.getX509Certificates();

            byte[] wrappedKey = CryptoUtil.exportSharedSecret(nickname, certs[0]);
            KeyData keyData = new KeyData();
            keyData.setWrappedPrivateData(Utils.base64encode(wrappedKey));

            return createOKResponse(keyData);

        } catch (InvalidKeyException | IllegalStateException | NoSuchAlgorithmException
                | InvalidAlgorithmParameterException | EBaseException
                | NotInitializedException | TokenException | IOException | InvalidKeyFormatException e) {
            e.printStackTrace();
            CMS.debug("Error in obtaining shared secret: " + e);
            throw new PKIException("Error in obtaining shared secret: " + e);
        }
    }

    private boolean connectorExists(String id) throws EBaseException {
        String tpsList = cs.getString(TPS_LIST, "");
        return ArrayUtils.contains(StringUtils.split(tpsList, ","), id);
    }

    private String getConnectorID(String host, String port) throws EBaseException {
        String tpsList = cs.getString(TPS_LIST, "");
        for (String tpsID : StringUtils.split(tpsList,",")) {
            TPSConnectorData data = createTPSConnectorData(tpsID);
            if (data.getHost().equals(host) && data.getPort().equals(port))
                return tpsID;
        }
        return null;
    }

    private void addToConnectorList(String id) throws EBaseException {
        String tpsList = cs.getString(TPS_LIST, "");
        Collection<String> sorted = new TreeSet<String>();
        sorted.addAll(Arrays.asList(StringUtils.split(tpsList, ",")));
        sorted.add(id);
        cs.putString(TPS_LIST, StringUtils.join(sorted, ","));
    }

    private void removeFromConnectorList(String id) throws EBaseException {
        String tpsList = cs.getString(TPS_LIST, "");
        Collection<String> sorted = new TreeSet<String>();
        sorted.addAll(Arrays.asList(StringUtils.split(tpsList, ",")));
        sorted.remove(id);
        cs.putString(TPS_LIST, StringUtils.join(sorted, ","));
    }

    private String findNextConnectorID() throws EBaseException {
        String tpsList = cs.getString(TPS_LIST, "");
        Collection<String> sorted = new TreeSet<String>();
        sorted.addAll(Arrays.asList(StringUtils.split(tpsList, ",")));

        int index = 0;
        while (sorted.contains(Integer.toString(index))) index++;
        return Integer.toString(index);
    }
}