8abbea2f36ec8dfb6fbeee8ec56db411d49272fb
[platform/upstream/iotivity.git] / cloud / account / src / main / java / org / iotivity / cloud / accountserver / resources / certificate / CertificateResource.java
1 /*
2  * //******************************************************************
3  * //
4  * // Copyright 2016 Samsung Electronics All Rights Reserved.
5  * //
6  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  * //
8  * // Licensed under the Apache License, Version 2.0 (the "License");
9  * // you may not use this file except in compliance with the License.
10  * // You may obtain a copy of the License at
11  * //
12  * //      http://www.apache.org/licenses/LICENSE-2.0
13  * //
14  * // Unless required by applicable law or agreed to in writing, software
15  * // distributed under the License is distributed on an "AS IS" BASIS,
16  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * // See the License for the specific language governing permissions and
18  * // limitations under the License.
19  * //
20  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22 package org.iotivity.cloud.accountserver.resources.certificate;
23
24 import java.security.PublicKey;
25 import java.util.Arrays;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.Map;
29
30 import org.iotivity.cloud.accountserver.Constants;
31 import org.iotivity.cloud.accountserver.x509.cert.CSRParser;
32 import org.iotivity.cloud.accountserver.x509.cert.CertificateBuilder;
33 import org.iotivity.cloud.accountserver.x509.cert.CertificateIssuerConfig;
34 import org.iotivity.cloud.accountserver.x509.cert.CertificatePrivateKeyPair;
35 import org.iotivity.cloud.base.device.Device;
36 import org.iotivity.cloud.base.exception.ServerException;
37 import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
38 import org.iotivity.cloud.base.protocols.IRequest;
39 import org.iotivity.cloud.base.protocols.IResponse;
40 import org.iotivity.cloud.base.protocols.MessageBuilder;
41 import org.iotivity.cloud.base.protocols.enums.ContentFormat;
42 import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
43 import org.iotivity.cloud.base.resource.Resource;
44 import org.iotivity.cloud.util.Cbor;
45
46 public class CertificateResource extends Resource {
47     /* resource uri for certificate issuer */
48     private Cbor<HashMap<String, Object>> mCbor               = new Cbor<>();
49     private CertificateManager            mCertificateManager = new CertificateManager();
50     private static String                 DEVICE_OU           = "OCF Device";
51
52     public CertificateResource() {
53         super(Arrays.asList(Constants.PREFIX_OIC, Constants.CREDPROV_URI,
54                 Constants.CERT_URI));
55     }
56
57     @Override
58     public void onDefaultRequestReceived(Device srcDevice, IRequest request)
59             throws ServerException {
60         IResponse response = null;
61
62         switch (request.getMethod()) {
63             case POST:
64                 response = handlePutRequest(request);
65                 break;
66
67             default:
68                 throw new BadRequestException(
69                         request.getMethod() + " request type is not support");
70         }
71
72         srcDevice.sendResponse(response);
73     }
74
75     private IResponse handlePutRequest(IRequest request)
76             throws ServerException {
77
78         Map<String, Object> payloadData = mCbor
79                 .parsePayloadFromCbor(request.getPayload(), HashMap.class);
80
81         if (payloadData == null) {
82             throw new BadRequestException("CBOR parsing failed");
83         }
84
85         Map<String, Object> responsePayload = null;
86
87         if (payloadData.containsKey(Constants.REQ_CSR)) {
88
89             byte[] csrDer = (byte[]) payloadData.get(Constants.REQ_CSR);
90             CSRParser parser = null;
91             PublicKey pubKey = null;
92
93             try {
94                 parser = new CSRParser(csrDer);
95                 if (!parser.verify()) {
96                     throw new Exception();
97                 }
98                 pubKey = parser.getPublicKey();
99             } catch (Exception e) {
100                 throw new BadRequestException("Bad CSR");
101             }
102
103             CertificateIssuerConfig ciConfig = CertificateIssuerConfig
104                     .getInstance();
105
106             Date notBefore = ciConfig.getNotBeforeDate();
107             Date notAfter = ciConfig.getNotAfterDate();
108
109             CertificateBuilder certBuilder = new CertificateBuilder(
110                     parser.getCommonName(), pubKey, notBefore, notAfter,
111                     ciConfig.getNextSerialNumber(),
112                     ciConfig.getRootCertificate());
113
114             certBuilder.setSubjectC(parser.getCountry());
115
116             certBuilder.setSubjectO(parser.getOrganizational());
117
118             certBuilder.setSubjectOU(DEVICE_OU);
119
120             CertificatePrivateKeyPair devCert = null;
121
122             try {
123                 devCert = certBuilder.build();
124                 // System.out.println("============================== DEV CERT
125                 // ===========================");
126                 // System.out.println();
127                 // System.out.println(devCert.getCertificate().toString());
128                 // System.out.println("===================================================================");
129
130                 if (payloadData.containsKey(Constants.REQ_DEVICE_ID)) {
131                     mCertificateManager.addDeviceId(
132                             (String) payloadData.get(Constants.RESP_DEVICE_ID));
133                 }
134
135                 responsePayload = mCertificateManager.createPayload(
136                         devCert.getCertificate().getEncoded(),
137                         ciConfig.getRootCertificate().getCertificate()
138                                 .getEncoded());
139
140             } catch (Exception e) {
141                 throw new BadRequestException("Certificate generation error");
142             }
143
144         } else {
145             throw new BadRequestException("CSR is null");
146         }
147
148         return MessageBuilder.createResponse(request, ResponseStatus.CONTENT,
149                 ContentFormat.APPLICATION_CBOR,
150                 mCbor.encodingPayloadToCbor(responsePayload));
151     }
152 }