diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/RegisterActivity.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/RegisterActivity.java index a7e069757..e9f56a8b1 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/RegisterActivity.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/RegisterActivity.java @@ -140,6 +140,7 @@ public class RegisterActivity extends Activity { }); if (registerStatus.isRegistered()) { + LocalRegistry.setEnrolled(getApplicationContext(), true); LocalRegistry.addUsername(getApplicationContext(), username); LocalRegistry.addDeviceId(getApplicationContext(), deviceId); LocalRegistry.addMqttPort(getApplicationContext(), mqttPortNo); diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/data/publisher/DataPublisherService.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/data/publisher/DataPublisherService.java index 0f852fd6c..d1ae9ad03 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/data/publisher/DataPublisherService.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/data/publisher/DataPublisherService.java @@ -143,7 +143,7 @@ public class DataPublisherService extends Service { } SenseDataHolder.resetWordDataHolder(); //publish the data - if (events.size() > 0) { + if (events.size() > 0 && LocalRegistry.isEnrolled(context)) { String user = LocalRegistry.getUsername(context); String deviceId = LocalRegistry.getDeviceId(context); JSONArray jsonArray = new JSONArray(); diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/event/streams/Location/LocationDataReader.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/event/streams/Location/LocationDataReader.java index 3504a1245..ca97f2120 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/event/streams/Location/LocationDataReader.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/event/streams/Location/LocationDataReader.java @@ -165,5 +165,4 @@ public class LocationDataReader extends DataReader implements LocationListener { } } - } diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/realtimeviewer/ActivitySelectSensor.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/realtimeviewer/ActivitySelectSensor.java index b93a3a627..2ceeba026 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/realtimeviewer/ActivitySelectSensor.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/realtimeviewer/ActivitySelectSensor.java @@ -176,7 +176,7 @@ public class ActivitySelectSensor extends AppCompatActivity Intent activity = new Intent(getApplicationContext(), RegisterActivity.class); startActivity(activity); } - + LocalRegistry.setEnrolled(getApplicationContext(), false); LocalRegistry.removeUsername(getApplicationContext()); LocalRegistry.removeDeviceId(getApplicationContext()); LocalRegistry.removeServerURL(getApplicationContext()); diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/LocalRegistry.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/LocalRegistry.java index e9d3d430f..be6af804f 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/LocalRegistry.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/LocalRegistry.java @@ -35,6 +35,7 @@ public class LocalRegistry { private static final String ACCESS_TOKEN_KEY = "accessTokenKey"; private static final String REFRESH_TOKEN_KEY = "refreshTokenKey"; private static final String MQTT_PORT_KEY = "mqttPort"; + private static final String IS_ENROLLED_KEY = "enrolled"; private static boolean exists = false; private static String username; private static String deviceId; @@ -43,6 +44,7 @@ public class LocalRegistry { private static String accessToken; private static String refreshToken; private static int mqttPort; + private static boolean enrolled; public static boolean isExist(Context context) { if (!exists) { @@ -209,6 +211,22 @@ public class LocalRegistry { return LocalRegistry.mqttPort; } + public static void setEnrolled(Context context, boolean enrolled) { + SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putBoolean(IS_ENROLLED_KEY, enrolled); + editor.commit(); + LocalRegistry.enrolled = enrolled; + } + + public static boolean isEnrolled(Context context) { + if (!LocalRegistry.enrolled) { + SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE); + return LocalRegistry.enrolled = sharedpreferences.getBoolean(IS_ENROLLED_KEY, false); + } + return LocalRegistry.enrolled; + } + public static String getServerHost(Context context) { URL url = null; diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/res/layout/activity_register.xml b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/res/layout/activity_register.xml index 157502339..42c37ab25 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/res/layout/activity_register.xml +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/res/layout/activity_register.xml @@ -27,13 +27,13 @@ android:id="@+id/username" android:inputType="text" android:maxLines="1" android:singleLine="true" - android:text="admin"/> + /> + /> - wso2/android_sense/# + wso2/android_sense/+/data admin device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2 default https://localhost:9443/dynamic-client-web/register tcp://localhost:1883 - false + true diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseControllerService.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseControllerService.java index 2a574f8e6..2e9c407d2 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseControllerService.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseControllerService.java @@ -46,9 +46,8 @@ public interface AndroidSenseControllerService { */ @Path("device/{deviceId}/words") @POST - @Feature(code = "keywords", name = "Add Keywords", description = "Send keywords to the device", - type = "operation") - Response sendKeyWords(@PathParam("deviceId") String deviceId, @FormParam("keywords") String keywords); + @Feature(code = "keywords", name = "Add Keywords", description = "Send keywords to the device", type = "operation") + Response sendKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("keywords") String keywords); /** * End point to send the key words to the device @@ -60,7 +59,7 @@ public interface AndroidSenseControllerService { @POST @Feature(code = "threshold", name = "Add a Threshold", description = "Set a threshold for word in the device", type = "operation") - Response sendThreshold(@PathParam("deviceId") String deviceId, @FormParam("threshold") String threshold); + Response sendThreshold(@PathParam("deviceId") String deviceId, @QueryParam("threshold") String threshold); @Path("device/{deviceId}/words") @DELETE @@ -71,7 +70,6 @@ public interface AndroidSenseControllerService { /** * Retrieve Sensor data for the device type */ - @Path("stats/{deviceId}/sensors/{sensorName}") @GET @Consumes("application/json") diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseControllerServiceImpl.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseControllerServiceImpl.java index b6f43c669..61e0cacff 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseControllerServiceImpl.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseControllerServiceImpl.java @@ -24,6 +24,8 @@ import org.wso2.carbon.analytics.dataservice.commons.SORT; import org.wso2.carbon.analytics.dataservice.commons.SortByField; import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.transport.AndroidSenseMQTTConnector; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.SensorRecord; @@ -57,9 +59,17 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController @POST public Response sendKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("keywords") String keywords) { try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + AndroidSenseConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } androidSenseMQTTConnector.publishDeviceData(deviceId, "add", keywords); return Response.ok().build(); } catch (TransportHandlerException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } } @@ -68,9 +78,16 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController @POST public Response sendThreshold(@PathParam("deviceId") String deviceId, @QueryParam("threshold") String threshold) { try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + AndroidSenseConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } androidSenseMQTTConnector.publishDeviceData(deviceId, "threshold", threshold); return Response.ok().build(); } catch (TransportHandlerException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } } @@ -79,9 +96,17 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController @DELETE public Response removeKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("words") String words) { try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + AndroidSenseConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } androidSenseMQTTConnector.publishDeviceData(deviceId, "remove", words); return Response.ok().build(); } catch (TransportHandlerException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } } @@ -96,13 +121,18 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController String toDate = String.valueOf(to); String user = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String query = "owner:" + user + " AND deviceId:" + deviceId + " AND deviceType:" + - AndroidSenseConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]"; + AndroidSenseConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]"; if (sensor.equals(AndroidSenseConstants.SENSOR_WORDCOUNT)) { query = "owner:" + user + " AND deviceId:" + deviceId; } String sensorTableName = getSensorEventTableName(sensor); - List sensorDatas; + try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + AndroidSenseConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + List sensorDatas; if (sensor.equals(AndroidSenseConstants.SENSOR_WORDCOUNT)) { List sortByFields = new ArrayList<>(); SortByField sortByField = new SortByField("time", SORT.ASC, false); @@ -116,6 +146,9 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; log.error(errorMsg); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } } diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseManagerService.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseManagerService.java index 5cb401d13..68e48074a 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseManagerService.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseManagerService.java @@ -31,7 +31,6 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("enrollment") -@DeviceType(value = "android_sense") @API(name = "android_sense_mgt", version = "1.0.0", context = "/android_sense_mgt", tags = {"android_sense"}) public interface AndroidSenseManagerService { @@ -53,10 +52,5 @@ public interface AndroidSenseManagerService { @Produces("application/json") Response getDevice(@PathParam("device_id") String deviceId); - @Path("/devices/download") - @GET - @Produces("application/octet-stream") - Response downloadSketch(); - } diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseManagerServiceImpl.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseManagerServiceImpl.java index 45420f31c..51b0c19e0 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseManagerServiceImpl.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseManagerServiceImpl.java @@ -24,9 +24,9 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants; -import org.wso2.carbon.utils.CarbonUtils; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -38,7 +38,6 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; -import java.io.File; import java.util.Date; @Path("enrollment") @@ -56,7 +55,6 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { return Response.status(Response.Status.CONFLICT.getStatusCode()).build(); } - Device device = new Device(); device.setDeviceIdentifier(deviceId); EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); @@ -76,6 +74,7 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).entity(false).build(); } } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(false).build(); } } @@ -87,6 +86,9 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic deviceIdentifier.setId(deviceId); deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE); try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier); if (removed) { return Response.ok().build(); @@ -94,6 +96,10 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); } } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } } @@ -105,6 +111,9 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic deviceIdentifier.setId(deviceId); deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE); try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); device.setDeviceIdentifier(deviceId); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); @@ -117,6 +126,10 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); } } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } } @@ -130,26 +143,17 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic deviceIdentifier.setId(deviceId); deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE); try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); return Response.ok().entity(device).build(); } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - } - - @Path("/devices/download") - @GET - @Produces("application/octet-stream") - public Response downloadSketch() { - try { - String sep = File.separator; - String sketchFolder = "repository" + sep + "resources" + sep + "sketches" + sep + "android_sense" + sep; - String archivesPath = CarbonUtils.getCarbonHome() + sep + sketchFolder; - Response.ResponseBuilder rb = Response.ok(new File(archivesPath + sep + "androidsense.apk")); - rb.header("Content-Disposition", "attachment; filename=\"" + "androidsense.apk" + "\""); - return rb.build(); - } catch (IllegalArgumentException ex) { - return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build(); } } diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/transport/AndroidSenseMQTTConnector.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/transport/AndroidSenseMQTTConnector.java index a9e62aefb..21e35475f 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/transport/AndroidSenseMQTTConnector.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/transport/AndroidSenseMQTTConnector.java @@ -45,7 +45,7 @@ public class AndroidSenseMQTTConnector extends MQTTTransportHandler { private static String subscribeTopic = AndroidSenseConstants.MQTT_SUBSCRIBE_WORDS_TOPIC; private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5); private static final String KEY_TYPE = "PRODUCTION"; - private static final String EMPTY_STRING = ""; + private static final String DEFAULT_PASSWORD = ""; private AndroidSenseMQTTConnector() { super(iotServerSubscriber, AndroidSenseConstants.DEVICE_TYPE, @@ -75,9 +75,8 @@ public class AndroidSenseMQTTConnector extends MQTTTransportHandler { apiApplicationKey.getConsumerSecret(), applicationUsername, scopes); //create token String accessToken = accessTokenInfo.getAccessToken(); - setUsernameAndPassword(accessToken, EMPTY_STRING); + setUsernameAndPassword(accessToken, DEFAULT_PASSWORD); connectToQueue(); - subscribeToQueue(); } catch (TransportHandlerException e) { log.warn("Connection/Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed"); try { diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/util/APIUtil.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/util/APIUtil.java index fd74ca1f3..86685e217 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/util/APIUtil.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/util/APIUtil.java @@ -13,8 +13,14 @@ import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException; +import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; +import org.wso2.carbon.registry.api.Resource; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; @@ -30,7 +36,6 @@ import java.util.Map; public class APIUtil { private static Log log = LogFactory.getLog(APIUtil.class); - private static Object lock = new Object(); public static String getAuthenticatedUser() { PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); @@ -66,7 +71,8 @@ public class APIUtil { return analyticsDataAPI; } - public static List getAllEventsForDevice(String tableName, String query, List sortByFields) throws AnalyticsException { + public static List getAllEventsForDevice(String tableName, String query, + List sortByFields) throws AnalyticsException { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI(); int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); @@ -158,37 +164,52 @@ public class APIUtil { return jwtClientManagerService; } + public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceAccessAuthorizationService deviceAccessAuthorizationService = + (DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null); + if (deviceAccessAuthorizationService == null) { + String msg = "Device Authorization service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return deviceAccessAuthorizationService; + } + + public static void registerApiAccessRoles(String user) { UserStoreManager userStoreManager = null; try { userStoreManager = getUserStoreManager(); if (userStoreManager != null) { - synchronized (lock) { - String[] userList = new String[]{user}; - if (!userStoreManager.isExistingRole(Constants.DEFAULT_ROLE_NAME)) { - userStoreManager.addRole(Constants.DEFAULT_ROLE_NAME, userList, Constants.DEFAULT_PERMISSION); - } + String[] userList = new String[]{user}; + if (!userStoreManager.isExistingRole(Constants.DEFAULT_ROLE_NAME)) { + userStoreManager.addRole(Constants.DEFAULT_ROLE_NAME, userList, Constants.DEFAULT_PERMISSION); } } } catch (UserStoreException e) { - log.error("error on wso2 user component"); + log.error("Error while creating a role and adding a user for android_sense.", e); } } - private static UserStoreManager getUserStoreManager() throws UserStoreException { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - return getRealmService().getTenantUserRealm(tenantId).getUserStoreManager(); - } - - public static RealmService getRealmService() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - RealmService realmService = - (RealmService) ctx.getOSGiService(RealmService.class, null); - if (realmService == null) { - String msg = "JWT Client manager service has not initialized."; - log.error(msg); + public static UserStoreManager getUserStoreManager() { + RealmService realmService; + UserStoreManager userStoreManager; + try { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); + if (realmService == null) { + String msg = "Realm service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + int tenantId = ctx.getTenantId(); + userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager(); + } catch (UserStoreException e) { + String msg = "Error occurred while retrieving current user store manager"; + log.error(msg, e); throw new IllegalStateException(msg); } - return realmService; + return userStoreManager; } } diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/util/Constants.java b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/util/Constants.java index c6b2c5b1a..acc8ba6e5 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/util/Constants.java +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/util/Constants.java @@ -19,15 +19,14 @@ package org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util; import org.wso2.carbon.user.core.Permission; -import org.wso2.carbon.user.core.authorization.TreeNode; /** - * This hold the constants related to android sense. + * This hold the constants related to the device type. */ public class Constants { - private static final String DEFAULT_PERMISSION_RESOURCE = "/_system/governance/permission/admin/device-mgt/android_sense/user"; + public static final String DEFAULT_PERMISSION_RESOURCE = "/permission/admin/device-mgt/android_sense/user"; public static final String DEFAULT_ROLE_NAME = "android_sense_user"; public static final Permission DEFAULT_PERMISSION[] = new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE, - TreeNode.Permission.UI_EXECUTE.toString())}; + "ui.execute")}; } diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/webapp/META-INF/permissions.xml b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/webapp/META-INF/permissions.xml index e81d61e59..059e10d54 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/webapp/META-INF/permissions.xml +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/webapp/META-INF/permissions.xml @@ -77,13 +77,6 @@ DELETE android_sense_user - - Download device - /device-mgt/android_sense/user - /enrollment/devices/download - GET - android_sense_user - Update device /device-mgt/android_sense/user diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.type-view/public/asset/androidsense.apk b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.type-view/public/asset/androidsense.apk index d556c72d6..b1d1f0fbb 100644 Binary files a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.type-view/public/asset/androidsense.apk and b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.type-view/public/asset/androidsense.apk differ diff --git a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.type-view/type-view.hbs b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.type-view/type-view.hbs index 09c98431b..b04584407 100644 --- a/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.type-view/type-view.hbs +++ b/components/iot-plugins/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.type-view/type-view.hbs @@ -1,68 +1,230 @@
-

Android Mobile

+

Android Sense


+
- +
- +
-

What it Does


-

Connect and manage your Android device with WSO2 IoT Server.

+

Connect an Android device to WSO2 IoT Server and visualize sensor + data.


-

What You Need


+

You should have an Android Device to get started.

    -
  • STEP 01   Android - Mobile. +
  • + STEP 01 +    Go ahead and click [Enroll Device].
  • -
  • STEP 02   Go ahead - and click [Enroll Device]. +
  • + STEP 02 +    You can either scan the QR code or directly download Android agent.
  • -
  • STEP 03   Proceed - to the [Prepare] section. +
  • + STEP 03 +    Install Android agent into your Android Device.
  • +
  • STEP 04 +    Proceed to [Prepare] section.

+ + Enroll Device +

- Enroll Device + +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +


-
-

Prepare


+
+

Prepare

+
    -
  • 01 Download Device Agent into your Android Mobile.
  • -
  • 02 Install Agent APK file.
  • -
  • 03 Configure Agent App
  • +
  • + 01 +    Connect Android device to network. +
  • +
  • + 02 +    Start Android Sense app in your device. +
  • +
  • + 03 +    Fill login form with the credentials. + (Use server URL as [ https://<WSO2_IoT_SERVER_HOST>:< + HTTPS_SERVER_PORT> ] and click on + Register Device button.) +
  • +
  • + + + +
  • + +
  • + 04 +    Once the device is enrolled, click on [+] button to + select the sensors. + + + +
  • +
  • + 05 +    Click on [Publish data] button to publish sensor readings to + IoT server. + + + +

-
+

Try Out

+
+
    +
  • + + + + +    You can view all your connected devices + [Device Management] page. +
  • +
  • + + + + +    You can select any one of your connected devices for available + operations and Real-Time data monitoring. +
  • +
  • + + + +    For historical analytics of sensor data navigate to device + analytics page. +
  • +
+

Click on the image to zoom

- - + +
-
- - +
+
-{{#zone "topCss"}} - -{{/zone}} + .padding-double { + padding: 20px; + } + + .grey { + color: #333; + } + + hr { + display: block; + height: 1px; + border: 0; + border-top: 1px solid #7f7f7f; + margin: 1em 0; + padding: 0; + opacity: 0.2; + } + + .light-grey { + color: #7c7c7c; + } + + .uppercase { + text-transform: uppercase; + } + + .grey-bg { + background-color: #f6f4f4; + } + + .doc-link { + background: #11375B; + padding: 20px; + color: white; + margin-top: 0; + } + + .doc-link a { + color: white; + } + {{#zone "bottomJs"}} + {{js "/js/download.js"}} -{{/zone}} \ No newline at end of file + {{js "/js/jquery.validate.js"}} +{{/zone}} diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java index 50e7f384e..11944cba2 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java @@ -69,6 +69,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler { public void run() { while (!isConnected()) { try { + connectToQueue(); agentManager.updateAgentStatus("Connected to MQTT Queue"); } catch (TransportHandlerException e) { @@ -142,8 +143,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler { String replyTemperature = "Current temperature was read as: '" + currentTemperature + "C'"; log.info(AgentConstants.LOG_APPENDER + replyTemperature); - String tempPublishTopic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC, - serverName, deviceOwner, deviceID); + String tempPublishTopic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC, deviceID); replyMessage = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature; securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage); @@ -157,7 +157,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler { log.info(AgentConstants.LOG_APPENDER + replyHumidity); String humidPublishTopic = String.format( - AgentConstants.MQTT_PUBLISH_TOPIC, serverName, deviceOwner, deviceID); + AgentConstants.MQTT_PUBLISH_TOPIC, deviceID); replyMessage = AgentConstants.HUMIDITY_CONTROL + ":" + currentHumidity; securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage); @@ -202,8 +202,6 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler { pushMessage.setRetained(false); String topic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC, - agentManager.getAgentConfigs().getServerName(), - agentManager.getAgentConfigs().getDeviceOwner(), agentManager.getAgentConfigs().getDeviceId()); publishToQueue(topic, pushMessage); diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConfiguration.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConfiguration.java index 49e437cc1..f886a179a 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConfiguration.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConfiguration.java @@ -29,6 +29,7 @@ public class AgentConfiguration { private String deviceId; private String deviceName; private String controllerContext; + private String scepContext; private String HTTPS_ServerEndpoint; private String HTTP_ServerEndpoint; private String apimGatewayEndpoint; @@ -150,6 +151,14 @@ public class AgentConfiguration { public void setDataPushInterval(int dataPushInterval) { this.dataPushInterval = dataPushInterval; } + + public String getScepContext() { + return scepContext; + } + + public void setScepContext(String scepContext) { + this.scepContext = scepContext; + } } diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java index 038a52240..d0584bcf3 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java @@ -26,7 +26,8 @@ public class AgentConstants { /* --------------------------------------------------------------------------------------- IoT-Server specific information --------------------------------------------------------------------------------------- */ - public static final String DEVICE_CONTROLLER_API_EP = "/virtual_firealarm/controller"; + public static final String DEVICE_CONTROLLER_API_EP = "/virtual_firealarm/device"; + public static final String DEVICE_SCEP_API_EP = "/virtual_firealarm_scep"; public static final String DEVICE_ENROLLMENT_API_EP = "/scep"; public static final String DEVICE_REGISTER_API_EP = "/register"; public static final String DEVICE_PUSH_TEMPERATURE_API_EP = "/push_temperature"; @@ -56,8 +57,8 @@ public class AgentConstants { --------------------------------------------------------------------------------------- */ public static final int DEFAULT_MQTT_RECONNECTION_INTERVAL = 2; // time in seconds public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; - public static final String MQTT_SUBSCRIBE_TOPIC = "%s/%s/" + DEVICE_TYPE + "/%s"; - public static final String MQTT_PUBLISH_TOPIC = "%s/%s/" + DEVICE_TYPE + "/%s/publisher"; + public static final String MQTT_SUBSCRIBE_TOPIC = "wso2/" + DEVICE_TYPE + "/%s"; + public static final String MQTT_PUBLISH_TOPIC = "wso2/" + DEVICE_TYPE + "/%s/publisher"; /* --------------------------------------------------------------------------------------- XMPP Connection specific information --------------------------------------------------------------------------------------- */ @@ -71,6 +72,7 @@ public class AgentConstants { public static final String DEVICE_ID_PROPERTY = "deviceId"; public static final String DEVICE_NAME_PROPERTY = "device-name"; public static final String DEVICE_CONTROLLER_CONTEXT_PROPERTY = "controller-context"; + public static final String DEVICE_SCEP_CONTEXT_PROPERTY = "scep-context"; public static final String SERVER_HTTPS_EP_PROPERTY = "https-ep"; public static final String SERVER_HTTP_EP_PROPERTY = "http-ep"; public static final String APIM_GATEWAY_EP_PROPERTY = "apim-ep"; diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java index aba3809c3..cd09219ee 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java @@ -133,10 +133,7 @@ public class AgentManager { log.error("XMPP Endpoint String - " + agentConfigs.getXmppServerEndpoint() + ", provided in the configuration file is invalid."); } - String mqttTopic = String.format(AgentConstants.MQTT_SUBSCRIBE_TOPIC, - agentConfigs.getServerName(), - agentConfigs.getDeviceOwner(), - agentConfigs.getDeviceId()); + String mqttTopic = String.format(AgentConstants.MQTT_SUBSCRIBE_TOPIC, agentConfigs.getDeviceId()); // TransportHandler httpCommunicator = new FireAlarmHTTPCommunicator(); TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(agentConfigs.getDeviceOwner(), diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java index cb2dbf4d1..fd4220e83 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core; +import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONObject; @@ -45,6 +46,8 @@ public class AgentUtilOperations { private static final Log log = LogFactory.getLog(AgentUtilOperations.class); private static final String JSON_MESSAGE_KEY = "Msg"; private static final String JSON_SIGNATURE_KEY = "Sig"; + private static final String JSON_SERIAL_KEY = "SerialNumber"; + private static final String JSON_TENANT_KEY = "Tenant"; /** * This method reads the agent specific configurations for the device from the @@ -88,6 +91,8 @@ public class AgentUtilOperations { AgentConstants.DEVICE_NAME_PROPERTY)); iotServerConfigs.setControllerContext(properties.getProperty( AgentConstants.DEVICE_CONTROLLER_CONTEXT_PROPERTY)); + iotServerConfigs.setScepContext(properties.getProperty( + AgentConstants.DEVICE_SCEP_CONTEXT_PROPERTY)); iotServerConfigs.setHTTPS_ServerEndpoint(properties.getProperty( AgentConstants.SERVER_HTTPS_EP_PROPERTY)); iotServerConfigs.setHTTP_ServerEndpoint(properties.getProperty( @@ -176,6 +181,7 @@ public class AgentUtilOperations { iotServerConfigs.setDeviceId(AgentConstants.DEFAULT_DEVICE_ID); iotServerConfigs.setDeviceName(AgentConstants.DEFAULT_DEVICE_NAME); iotServerConfigs.setControllerContext(AgentConstants.DEVICE_CONTROLLER_API_EP); + iotServerConfigs.setScepContext(AgentConstants.DEVICE_SCEP_API_EP); iotServerConfigs.setHTTPS_ServerEndpoint(AgentConstants.DEFAULT_HTTPS_SERVER_EP); iotServerConfigs.setHTTP_ServerEndpoint(AgentConstants.DEFAULT_HTTP_SERVER_EP); iotServerConfigs.setApimGatewayEndpoint(AgentConstants.DEFAULT_APIM_GATEWAY_EP); @@ -203,11 +209,11 @@ public class AgentUtilOperations { String serverSecureEndpoint = agentManager.getAgentConfigs().getHTTPS_ServerEndpoint(); String serverUnSecureEndpoint = agentManager.getAgentConfigs().getHTTP_ServerEndpoint(); String backEndContext = agentManager.getAgentConfigs().getControllerContext(); - + String scepBackEndContext = agentManager.getAgentConfigs().getScepContext(); String deviceControllerAPIEndpoint = serverSecureEndpoint + backEndContext; String deviceEnrollmentEndpoint = - serverUnSecureEndpoint + backEndContext + AgentConstants.DEVICE_ENROLLMENT_API_EP; + serverUnSecureEndpoint + scepBackEndContext + AgentConstants.DEVICE_ENROLLMENT_API_EP; agentManager.setEnrollmentEP(deviceEnrollmentEndpoint); String registerEndpointURL = @@ -229,21 +235,11 @@ public class AgentUtilOperations { public static String prepareSecurePayLoad(String message) throws AgentCoreOperationException { - PublicKey serverPublicKey = EnrollmentManager.getInstance().getServerPublicKey(); PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey(); - - String encryptedMsg; - try { - encryptedMsg = CommunicationUtils.encryptMessage(message, serverPublicKey); - } catch (TransportHandlerException e) { - String errorMsg = "Error occurred whilst trying to encryptMessage: [" + message + "]"; - log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg, e); - } - + String encodedMessage = Base64.encodeBase64String(message.getBytes()); String signedPayload; try { - signedPayload = CommunicationUtils.signMessage(encryptedMsg, devicePrivateKey); + signedPayload = CommunicationUtils.signMessage(encodedMessage, devicePrivateKey); } catch (TransportHandlerException e) { String errorMsg = "Error occurred whilst trying to sign encrypted message of: [" + message + "]"; log.error(errorMsg); @@ -251,8 +247,11 @@ public class AgentUtilOperations { } JSONObject jsonPayload = new JSONObject(); - jsonPayload.put(JSON_MESSAGE_KEY, encryptedMsg); + jsonPayload.put(JSON_MESSAGE_KEY, encodedMessage); jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload); + //below statements are temporary fix. + jsonPayload.put(JSON_SERIAL_KEY, EnrollmentManager.getInstance().getSCEPCertificate().getSerialNumber()); + jsonPayload.put(JSON_TENANT_KEY, "carbon.super"); return jsonPayload.toString(); } @@ -262,17 +261,15 @@ public class AgentUtilOperations { String actualMessage; PublicKey serverPublicKey = EnrollmentManager.getInstance().getServerPublicKey(); - PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey(); - JSONObject jsonPayload = new JSONObject(message); - Object encryptedMessage = jsonPayload.get(JSON_MESSAGE_KEY); + Object encodedMessage = jsonPayload.get(JSON_MESSAGE_KEY); Object signedPayload = jsonPayload.get(JSON_SIGNATURE_KEY); boolean verification; - if (encryptedMessage != null && signedPayload != null) { + if (encodedMessage != null && signedPayload != null) { try { verification = CommunicationUtils.verifySignature( - encryptedMessage.toString(), signedPayload.toString(), serverPublicKey); + encodedMessage.toString(), signedPayload.toString(), serverPublicKey); } catch (TransportHandlerException e) { String errorMsg = "Error occurred whilst trying to verify signature on received message: [" + message + "]"; @@ -284,21 +281,13 @@ public class AgentUtilOperations { "Need to be JSON - {\"Msg\":\"\", \"Sig\":\"\"}."; throw new AgentCoreOperationException(errorMsg); } - - try { - if (verification) { - actualMessage = CommunicationUtils.decryptMessage(encryptedMessage.toString(), devicePrivateKey); - } else { - String errorMsg = "Could not verify payload signature. The message was not signed by a valid client"; - log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg); - } - } catch (TransportHandlerException e) { - String errorMsg = "Error occurred whilst trying to decrypt received message: [" + encryptedMessage + "]"; + if (verification) { + actualMessage = new String(Base64.decodeBase64(encodedMessage.toString()), StandardCharsets.UTF_8); + } else { + String errorMsg = "Could not verify payload signature. The message was not signed by a valid client"; log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg, e); + throw new AgentCoreOperationException(errorMsg); } - return actualMessage; } diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/mqtt/MQTTTransportHandler.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/mqtt/MQTTTransportHandler.java index d4626f6df..c11bbe19c 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/mqtt/MQTTTransportHandler.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/mqtt/MQTTTransportHandler.java @@ -27,6 +27,7 @@ import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttSecurityException; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core.AgentManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportHandler; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportHandlerException; @@ -53,6 +54,7 @@ public abstract class MQTTTransportHandler private static final Log log = LogFactory.getLog(MQTTTransportHandler.class); public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; + private static final String DEFAULT_PASSWORD = ""; private MqttClient client; private String clientId; @@ -81,6 +83,8 @@ public abstract class MQTTTransportHandler this.mqttBrokerEndPoint = mqttBrokerEndPoint; this.timeoutInterval = DEFAULT_TIMEOUT_INTERVAL; this.initSubscriber(); + options.setUserName(AgentManager.getInstance().getAgentConfigs().getAuthToken()); + options.setPassword(DEFAULT_PASSWORD.toCharArray()); } /** @@ -105,6 +109,8 @@ public abstract class MQTTTransportHandler this.mqttBrokerEndPoint = mqttBrokerEndPoint; this.timeoutInterval = intervalInMillis; this.initSubscriber(); + options.setUserName(AgentManager.getInstance().getAgentConfigs().getAuthToken()); + options.setPassword(DEFAULT_PASSWORD.toCharArray()); } public void setTimeoutInterval(int timeoutInterval) { diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/resources/deviceConfig.properties b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/resources/deviceConfig.properties index 930742a2a..1dc1374b9 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/resources/deviceConfig.properties +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/resources/deviceConfig.properties @@ -20,7 +20,8 @@ server-name=WSO2IoTServer owner=shabirmean deviceId=t4ctwq8qfl11 device-name=SMEAN_t4ctwq8qfl11 -controller-context=/virtual_firealarm/controller +controller-context=/virtual_firealarm/device +scep-context=/virtual_firealarm_scep https-ep=https://localhost:9443 http-ep=http://localhost:9763 apim-ep=http://192.168.67.21:8281 diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java index cb74b048b..ace9d2cde 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java @@ -137,8 +137,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler { String replyTemperature = "Current temperature was read as: '" + currentTemperature + "C'"; log.info(AgentConstants.LOG_APPENDER + replyTemperature); - String tempPublishTopic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC, - serverName, deviceOwner, deviceID); + String tempPublishTopic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC, deviceID); replyMessage = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature; securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage); @@ -152,7 +151,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler { log.info(AgentConstants.LOG_APPENDER + replyHumidity); String humidPublishTopic = String.format( - AgentConstants.MQTT_PUBLISH_TOPIC, serverName, deviceOwner, deviceID); + AgentConstants.MQTT_PUBLISH_TOPIC, deviceID); replyMessage = AgentConstants.HUMIDITY_CONTROL + ":" + currentHumidity; securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage); @@ -193,8 +192,6 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler { pushMessage.setRetained(false); String topic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC, - agentManager.getAgentConfigs().getServerName(), - agentManager.getAgentConfigs().getDeviceOwner(), agentManager.getAgentConfigs().getDeviceId()); publishToQueue(topic, pushMessage); diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConfiguration.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConfiguration.java index e36b161cb..8b052f61d 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConfiguration.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConfiguration.java @@ -29,6 +29,7 @@ public class AgentConfiguration { private String deviceId; private String deviceName; private String controllerContext; + private String scepContext; private String HTTPS_ServerEndpoint; private String HTTP_ServerEndpoint; private String apimGatewayEndpoint; @@ -150,6 +151,14 @@ public class AgentConfiguration { public void setDataPushInterval(int dataPushInterval) { this.dataPushInterval = dataPushInterval; } + + public String getScepContext() { + return scepContext; + } + + public void setScepContext(String scepContext) { + this.scepContext = scepContext; + } } diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java index f415ef9e0..12044a8d5 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java @@ -56,8 +56,8 @@ public class AgentConstants { --------------------------------------------------------------------------------------- */ public static final int DEFAULT_MQTT_RECONNECTION_INTERVAL = 2; // time in seconds public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; - public static final String MQTT_SUBSCRIBE_TOPIC = "%s/%s/" + DEVICE_TYPE + "/%s"; - public static final String MQTT_PUBLISH_TOPIC = "%s/%s/" + DEVICE_TYPE + "/%s/publisher"; + public static final String MQTT_SUBSCRIBE_TOPIC = "wso2/" + DEVICE_TYPE + "/%s"; + public static final String MQTT_PUBLISH_TOPIC = "wso2/" + DEVICE_TYPE + "/%s/publisher"; /* --------------------------------------------------------------------------------------- XMPP Connection specific information --------------------------------------------------------------------------------------- */ @@ -71,6 +71,7 @@ public class AgentConstants { public static final String DEVICE_ID_PROPERTY = "deviceId"; public static final String DEVICE_NAME_PROPERTY = "device-name"; public static final String DEVICE_CONTROLLER_CONTEXT_PROPERTY = "controller-context"; + public static final String DEVICE_SCEP_CONTEXT_PROPERTY = "scep-context"; public static final String SERVER_HTTPS_EP_PROPERTY = "https-ep"; public static final String SERVER_HTTP_EP_PROPERTY = "http-ep"; public static final String APIM_GATEWAY_EP_PROPERTY = "apim-ep"; diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java index b1d204d62..462bc5752 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java @@ -121,10 +121,7 @@ public class AgentManager { log.error("XMPP Endpoint String - " + agentConfigs.getXmppServerEndpoint() + ", provided in the configuration file is invalid."); } - String mqttTopic = String.format(AgentConstants.MQTT_SUBSCRIBE_TOPIC, - agentConfigs.getServerName(), - agentConfigs.getDeviceOwner(), - agentConfigs.getDeviceId()); + String mqttTopic = String.format(AgentConstants.MQTT_SUBSCRIBE_TOPIC, agentConfigs.getDeviceId()); // TransportHandler httpCommunicator = new FireAlarmHTTPCommunicator(); TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(agentConfigs.getDeviceOwner(), diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentUtilOperations.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentUtilOperations.java index d12baaa2b..3029d05bd 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentUtilOperations.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentUtilOperations.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core; +import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONObject; @@ -49,6 +50,8 @@ public class AgentUtilOperations { private static final Log log = LogFactory.getLog(AgentUtilOperations.class); private static final String JSON_MESSAGE_KEY = "Msg"; private static final String JSON_SIGNATURE_KEY = "Sig"; + private static final String JSON_SERIAL_KEY = "SerialNumber"; + private static final String JSON_TENANT_KEY = "Tenant"; /** * This method reads the agent specific configurations for the device from the @@ -92,6 +95,8 @@ public class AgentUtilOperations { AgentConstants.DEVICE_NAME_PROPERTY)); iotServerConfigs.setControllerContext(properties.getProperty( AgentConstants.DEVICE_CONTROLLER_CONTEXT_PROPERTY)); + iotServerConfigs.setScepContext(properties.getProperty( + AgentConstants.DEVICE_SCEP_CONTEXT_PROPERTY)); iotServerConfigs.setHTTPS_ServerEndpoint(properties.getProperty( AgentConstants.SERVER_HTTPS_EP_PROPERTY)); iotServerConfigs.setHTTP_ServerEndpoint(properties.getProperty( @@ -176,11 +181,12 @@ public class AgentUtilOperations { String serverSecureEndpoint = agentManager.getAgentConfigs().getHTTPS_ServerEndpoint(); String serverUnSecureEndpoint = agentManager.getAgentConfigs().getHTTP_ServerEndpoint(); String backEndContext = agentManager.getAgentConfigs().getControllerContext(); + String scepBackEndContext = agentManager.getAgentConfigs().getScepContext(); String deviceControllerAPIEndpoint = serverSecureEndpoint + backEndContext; String deviceEnrollmentEndpoint = - serverUnSecureEndpoint + backEndContext + AgentConstants.DEVICE_ENROLLMENT_API_EP; + serverUnSecureEndpoint + scepBackEndContext + AgentConstants.DEVICE_ENROLLMENT_API_EP; agentManager.setEnrollmentEP(deviceEnrollmentEndpoint); String registerEndpointURL = @@ -202,21 +208,11 @@ public class AgentUtilOperations { public static String prepareSecurePayLoad(String message) throws AgentCoreOperationException { - PublicKey serverPublicKey = EnrollmentManager.getInstance().getServerPublicKey(); PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey(); - - String encryptedMsg; - try { - encryptedMsg = CommunicationUtils.encryptMessage(message, serverPublicKey); - } catch (TransportHandlerException e) { - String errorMsg = "Error occurred whilst trying to encryptMessage: [" + message + "]"; - log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg, e); - } - + String encodedMessage = Base64.encodeBase64String(message.getBytes()); String signedPayload; try { - signedPayload = CommunicationUtils.signMessage(encryptedMsg, devicePrivateKey); + signedPayload = CommunicationUtils.signMessage(encodedMessage, devicePrivateKey); } catch (TransportHandlerException e) { String errorMsg = "Error occurred whilst trying to sign encrypted message of: [" + message + "]"; log.error(errorMsg); @@ -224,28 +220,28 @@ public class AgentUtilOperations { } JSONObject jsonPayload = new JSONObject(); - jsonPayload.put(JSON_MESSAGE_KEY, encryptedMsg); + jsonPayload.put(JSON_MESSAGE_KEY, encodedMessage); jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload); + //below statements are temporary fix. + jsonPayload.put(JSON_SERIAL_KEY, EnrollmentManager.getInstance().getSCEPCertificate().getSerialNumber()); + jsonPayload.put(JSON_TENANT_KEY, "carbon.super"); return jsonPayload.toString(); } - public static String extractMessageFromPayload(String message) throws AgentCoreOperationException { String actualMessage; PublicKey serverPublicKey = EnrollmentManager.getInstance().getServerPublicKey(); - PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey(); - JSONObject jsonPayload = new JSONObject(message); - Object encryptedMessage = jsonPayload.get(JSON_MESSAGE_KEY); + Object encodedMessage = jsonPayload.get(JSON_MESSAGE_KEY); Object signedPayload = jsonPayload.get(JSON_SIGNATURE_KEY); boolean verification; - if (encryptedMessage != null && signedPayload != null) { + if (encodedMessage != null && signedPayload != null) { try { verification = CommunicationUtils.verifySignature( - encryptedMessage.toString(), signedPayload.toString(), serverPublicKey); + encodedMessage.toString(), signedPayload.toString(), serverPublicKey); } catch (TransportHandlerException e) { String errorMsg = "Error occurred whilst trying to verify signature on received message: [" + message + "]"; @@ -257,21 +253,13 @@ public class AgentUtilOperations { "Need to be JSON - {\"Msg\":\"\", \"Sig\":\"\"}."; throw new AgentCoreOperationException(errorMsg); } - - try { - if (verification) { - actualMessage = CommunicationUtils.decryptMessage(encryptedMessage.toString(), devicePrivateKey); - } else { - String errorMsg = "Could not verify payload signature. The message was not signed by a valid client"; - log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg); - } - } catch (TransportHandlerException e) { - String errorMsg = "Error occurred whilst trying to decrypt received message: [" + encryptedMessage + "]"; + if (verification) { + actualMessage = new String(Base64.decodeBase64(encodedMessage.toString()), StandardCharsets.UTF_8); + } else { + String errorMsg = "Could not verify payload signature. The message was not signed by a valid client"; log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg, e); + throw new AgentCoreOperationException(errorMsg); } - return actualMessage; } diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/mqtt/MQTTTransportHandler.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/mqtt/MQTTTransportHandler.java index c019ce9ce..e25324ea1 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/mqtt/MQTTTransportHandler.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/mqtt/MQTTTransportHandler.java @@ -27,6 +27,7 @@ import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttSecurityException; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandler; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandlerException; @@ -51,7 +52,7 @@ import java.nio.charset.StandardCharsets; public abstract class MQTTTransportHandler implements MqttCallback, TransportHandler { private static final Log log = LogFactory.getLog(MQTTTransportHandler.class); - + private static final String DEFAULT_PASSWORD = ""; public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; private MqttClient client; @@ -81,6 +82,8 @@ public abstract class MQTTTransportHandler this.mqttBrokerEndPoint = mqttBrokerEndPoint; this.timeoutInterval = DEFAULT_TIMEOUT_INTERVAL; this.initSubscriber(); + options.setUserName(AgentManager.getInstance().getAgentConfigs().getAuthToken()); + options.setPassword(DEFAULT_PASSWORD.toCharArray()); } /** @@ -105,6 +108,8 @@ public abstract class MQTTTransportHandler this.mqttBrokerEndPoint = mqttBrokerEndPoint; this.timeoutInterval = intervalInMillis; this.initSubscriber(); + options.setUserName(AgentManager.getInstance().getAgentConfigs().getAuthToken()); + options.setPassword(DEFAULT_PASSWORD.toCharArray()); } public void setTimeoutInterval(int timeoutInterval) { diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/resources/deviceConfig.properties b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/resources/deviceConfig.properties index 930742a2a..1dc1374b9 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/resources/deviceConfig.properties +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/resources/deviceConfig.properties @@ -20,7 +20,8 @@ server-name=WSO2IoTServer owner=shabirmean deviceId=t4ctwq8qfl11 device-name=SMEAN_t4ctwq8qfl11 -controller-context=/virtual_firealarm/controller +controller-context=/virtual_firealarm/device +scep-context=/virtual_firealarm_scep https-ep=https://localhost:9443 http-ep=http://localhost:9763 apim-ep=http://192.168.67.21:8281 diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmControllerService.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmControllerService.java index ba2694742..a25f7da3c 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmControllerService.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmControllerService.java @@ -37,6 +37,13 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.InputStream; +/** + * This class consists the functions/APIs specific to the "actions" of the VirtualFirealarm device-type. These APIs + * include the ones that are used by the [Device] to contact the server (i.e: Enrollment & Publishing Data) and the + * ones used by the [Server/Owner] to contact the [Device] (i.e: sending control signals). This class also initializes + * the transport 'Connectors' [XMPP & MQTT] specific to the VirtualFirealarm device-type in order to communicate with + * such devices and to receive messages form it. + */ @API(name = "virtual_firealarm", version = "1.0.0", context = "/virtual_firealarm", tags = "virtual_firealarm") @DeviceType(value = "virtual_firealarm") public interface VirtualFireAlarmControllerService { @@ -89,40 +96,7 @@ public interface VirtualFireAlarmControllerService { @Path("device/temperature") @Consumes(MediaType.APPLICATION_JSON) Response pushTemperatureData(final DeviceData dataMsg); - - /** - * This is an API called/used by the SCEP Client of the VirtualFirealarm device in its SCEP enrollment process. - * This acts as the endpoint exposed as part of the SCEP-Server for use by a SCEP Client. This is one of the two - * method-signatures that takes different parameters according to the SCEP-Operation executed by the SCEP-Client - * of the enrolling device. The API supports 2 SCEP Operations [GetCACert] and [GetCACaps]. - *

- * Operation [GetCACert] returns the CA cert of the SCEP-Server for the device to verify its authenticity. - * Operation [GetCACaps] returns the CA Capabilities of the SCEP-Server. - * - * @param operation the SCEP operation requested by the client. [GetCACert] or [GetCACaps] - * @param message any messages pertaining to the requested SCEP Operation. - * @return an HTTP Response object with either the CA-Cert or the CA-Capabilities according to the operation. - */ - @GET - @Path("device/scep") - Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message); - - - /** - * This is an API called/used by the SCEP Client of the VirtualFirealarm device in its SCEP enrollment process. - * This acts as the endpoint exposed as part of the SCEP-Server for use by a SCEP Client. This is one of the two - * method-signatures that takes different parameters according to the SCEP-Operation executed by the SCEP-Client - * of the enrolling device. This API supports the SCEP Operation [PKIOperation]. - *

- * Operation [PKIOperation] returns a certificate generated by the SCEP-Server for the enrolling device. - * - * @param operation the final SCEP operation executed in the enrollment process - which is [PKIOperation] - * @param inputStream an input stream consisting of the Certificate-Signing-Request (CSR) from the device. - * @return an HTTP Response object with the signed certificate for the device by the CA of the SCEP Server. - */ - @POST - @Path("device/scep") - Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream); + /** * Retrieve Sensor data for the device type diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmControllerServiceImpl.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmControllerServiceImpl.java index afc786e3b..e7172b38c 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmControllerServiceImpl.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmControllerServiceImpl.java @@ -26,21 +26,23 @@ import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener; import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.DeviceData; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.transport.VirtualFireAlarmXMPPConnector; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.scep.ContentType; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.scep.SCEPOperation; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.transport.VirtualFireAlarmMQTTConnector; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.transport.VirtualFireAlarmXMPPConnector; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.VirtualFireAlarmServiceUtils; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.scep.ContentType; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.scep.SCEPOperation; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; import javax.servlet.http.HttpServletRequest; @@ -60,13 +62,6 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; -/** - * This class consists the functions/APIs specific to the "actions" of the VirtualFirealarm device-type. These APIs - * include the ones that are used by the [Device] to contact the server (i.e: Enrollment & Publishing Data) and the - * ones used by the [Server/Owner] to contact the [Device] (i.e: sending control signals). This class also initializes - * the transport 'Connectors' [XMPP & MQTT] specific to the VirtualFirealarm device-type in order to communicate with - * such devices and to receive messages form it. - */ @SuppressWarnings("Non-Annoted WebService") public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmControllerService { @@ -75,7 +70,7 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo private static final String MQTT_PROTOCOL = "MQTT"; private static Log log = LogFactory.getLog(VirtualFireAlarmControllerServiceImpl.class); // consists of utility methods related to encrypting and decrypting messages - private SecurityManager securityManager; + private org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager securityManager; // connects to the given MQTT broker and handles MQTT communication private VirtualFireAlarmMQTTConnector virtualFireAlarmMQTTConnector; // connects to the given XMPP server and handles XMPP communication @@ -117,6 +112,10 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo protocolString); } try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + VirtualFireAlarmConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } switch (protocolString) { case HTTP_PROTOCOL: String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); @@ -138,6 +137,9 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo } catch (DeviceManagementException | TransportHandlerException e) { log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " + protocolString); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } @@ -147,7 +149,6 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo public Response pushTemperatureData(final DeviceData dataMsg) { String deviceId = dataMsg.deviceId; String deviceIp = dataMsg.reply; - float temperature = dataMsg.value; String registeredIp = deviceToIpMap.get(deviceId); if (registeredIp == null) { log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + @@ -158,102 +159,19 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo " is already registered under some other IP. Re-registration required"); return Response.status(Response.Status.CONFLICT).build(); } - if (!VirtualFireAlarmServiceUtils.publishToDAS(dataMsg.deviceId, dataMsg.value)) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } - return Response.ok().build(); - } - - @GET - @Path("device/scep") - public Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message) { - if (log.isDebugEnabled()) { - log.debug("Invoking SCEP operation " + operation); - } - if (SCEPOperation.GET_CA_CERT.getValue().equals(operation)) { - if (log.isDebugEnabled()) { - log.debug("Invoking GetCACert"); - } - try { - CertificateManagementService certificateManagementService = - VirtualFireAlarmServiceUtils.getCertificateManagementService(); - SCEPResponse scepResponse = certificateManagementService.getCACertSCEP(); - Response.ResponseBuilder responseBuilder; - switch (scepResponse.getResultCriteria()) { - case CA_CERT_FAILED: - log.error("CA cert failed"); - responseBuilder = Response.serverError(); - break; - case CA_CERT_RECEIVED: - if (log.isDebugEnabled()) { - log.debug("CA certificate received in GetCACert"); - } - responseBuilder = Response.ok(scepResponse.getEncodedResponse(), - ContentType.X_X509_CA_CERT); - break; - case CA_RA_CERT_RECEIVED: - if (log.isDebugEnabled()) { - log.debug("CA and RA certificates received in GetCACert"); - } - responseBuilder = Response.ok(scepResponse.getEncodedResponse(), - ContentType.X_X509_CA_RA_CERT); - break; - default: - log.error("Invalid SCEP request"); - responseBuilder = Response.serverError(); - break; - } - - return responseBuilder.build(); - } catch (VirtualFireAlarmException e) { - log.error("Error occurred while enrolling the VirtualFireAlarm device", e); - } catch (KeystoreException e) { - log.error("Keystore error occurred while enrolling the VirtualFireAlarm device", e); - } - - } else if (SCEPOperation.GET_CA_CAPS.getValue().equals(operation)) { - - if (log.isDebugEnabled()) { - log.debug("Invoking GetCACaps"); - } - try { - CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. - getCertificateManagementService(); - byte caCaps[] = certificateManagementService.getCACapsSCEP(); - - return Response.ok(caCaps, MediaType.TEXT_PLAIN).build(); - - } catch (VirtualFireAlarmException e) { - log.error("Error occurred while enrolling the device", e); - } - } else { - log.error("Invalid SCEP operation " + operation); - } - return Response.serverError().build(); - } - - @POST - @Path("device/scep") - public Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream) { - if (log.isDebugEnabled()) { - log.debug("Invoking SCEP operation " + operation); - } - if (SCEPOperation.PKI_OPERATION.getValue().equals(operation)) { - if (log.isDebugEnabled()) { - log.debug("Invoking PKIOperation"); + try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + VirtualFireAlarmConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); } - try { - CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. - getCertificateManagementService(); - byte pkiMessage[] = certificateManagementService.getPKIMessageSCEP(inputStream); - return Response.ok(pkiMessage, ContentType.X_PKI_MESSAGE).build(); - } catch (VirtualFireAlarmException e) { - log.error("Error occurred while enrolling the device", e); - } catch (KeystoreException e) { - log.error("Keystore error occurred while enrolling the device", e); + if (!VirtualFireAlarmServiceUtils.publishToDAS(dataMsg.deviceId, dataMsg.value)) { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } + return Response.ok().build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } - return Response.serverError().build(); } @Path("device/stats/{deviceId}/sensors/{sensorName}") @@ -270,6 +188,10 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo VirtualFireAlarmConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]"; String sensorTableName = getSensorEventTableName(sensor); try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + VirtualFireAlarmConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } if (sensorTableName != null) { List sortByFields = new ArrayList<>(); SortByField sortByField = new SortByField("time", SORT.ASC, false); @@ -281,6 +203,9 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; log.error(errorMsg); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return Response.status(Response.Status.BAD_REQUEST).build(); } diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmManagerService.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmManagerService.java index 1d48b0764..0b4077b2d 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmManagerService.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmManagerService.java @@ -34,39 +34,32 @@ import javax.ws.rs.core.Response; @Path("enrollment") @API(name = "virtual_firealarm_mgt", version = "1.0.0", context = "/virtual_firealarm_mgt", tags = "virtual_firealarm") -@DeviceType(value = "virtual_firealarm") public interface VirtualFireAlarmManagerService { - @Path("devices/{device_id}") + @Path("/devices/{device_id}") @DELETE Response removeDevice(@PathParam("device_id") String deviceId); - @Path("devices/{device_id}") + @Path("/devices/{device_id}") @PUT Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name); - @Path("devices/{device_id}") + @Path("/devices/{device_id}") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response getDevice(@PathParam("device_id") String deviceId); - @Path("devices") + @Path("/devices") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response getFirealarmDevices(); - @Path("devices/download") + @Path("/devices/download") @GET - @Produces(MediaType.APPLICATION_JSON) + @Produces("application/zip") Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType); - - @Path("devices/generate_link") - @GET - Response generateSketchLink(@QueryParam("deviceName") String deviceName, - @QueryParam("sketchType") String sketchType); - } \ No newline at end of file diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmManagerServiceImpl.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmManagerServiceImpl.java index 284a2937a..5f56c4a72 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmManagerServiceImpl.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmManagerServiceImpl.java @@ -19,6 +19,8 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl; import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; @@ -27,6 +29,7 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppAccount; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient; @@ -63,14 +66,18 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag private static final String KEY_TYPE = "PRODUCTION"; private static ApiApplicationKey apiApplicationKey; + private static Log log = LogFactory.getLog(VirtualFireAlarmManagerServiceImpl.class); - @Path("devices/{device_id}") + @Path("/devices/{device_id}") @DELETE public Response removeDevice(@PathParam("device_id") String deviceId) { try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } boolean removed = APIUtil.getDeviceManagementService().disenrollDevice( deviceIdentifier); if (removed) { @@ -79,17 +86,24 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); } } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } } - @Path("devices/{device_id}") + @Path("/devices/{device_id}") @PUT public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) { try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); device.setDeviceIdentifier(deviceId); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); @@ -102,11 +116,15 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); } } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } } - @Path("devices/{device_id}") + @Path("/devices/{device_id}") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @@ -115,14 +133,21 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); return Response.ok().entity(device).build(); } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } } - @Path("devices") + @Path("/devices") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @@ -140,57 +165,44 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag Device[] devices = userDevicesforFirealarm.toArray(new Device[]{}); return Response.ok().entity(devices).build(); } catch (DeviceManagementException e) { + log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } } - @Path("devices/download") + @Path("/devices/download") @GET - @Produces(MediaType.APPLICATION_JSON) + @Produces("application/zip") public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) { try { ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); + response.status(Response.Status.OK); response.type("application/zip"); response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); - return response.build(); + Response resp = response.build(); + zipFile.getZipFile().delete(); + return resp; } catch (IllegalArgumentException ex) { return Response.status(400).entity(ex.getMessage()).build();//bad request } catch (DeviceManagementException ex) { + log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); } catch (JWTClientException ex) { + log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); } catch (APIManagerException ex) { + log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); } catch (DeviceControllerException ex) { + log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); } catch (IOException ex) { + log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); } catch (UserStoreException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } - } - - @Path("devices/generate_link") - @GET - public Response generateSketchLink(@QueryParam("deviceName") String deviceName, - @QueryParam("sketchType") String sketchType) { - try { - ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); - Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); - return rb.build(); - } catch (IllegalArgumentException ex) { - return Response.status(400).entity(ex.getMessage()).build();//bad request - } catch (DeviceManagementException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (JWTClientException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (APIManagerException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (DeviceControllerException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (UserStoreException ex) { + log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); } } @@ -215,8 +227,12 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); device.setEnrolmentInfo(enrolmentInfo); boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); + if (added) { + APIUtil.registerApiAccessRoles(APIUtil.getAuthenticatedUser()); + } return added; } catch (DeviceManagementException e) { + log.error(e.getMessage(), e); return false; } } diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/transport/VirtualFireAlarmMQTTConnector.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/transport/VirtualFireAlarmMQTTConnector.java index bb8baab3a..7922f1845 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/transport/VirtualFireAlarmMQTTConnector.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/transport/VirtualFireAlarmMQTTConnector.java @@ -22,6 +22,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.json.JSONObject; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; @@ -33,9 +34,9 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.VirtualFireAlarmServiceUtils; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; import org.wso2.carbon.identity.jwt.client.extension.JWTClient; @@ -47,7 +48,6 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.PublicKey; -import java.util.Calendar; import java.util.UUID; /** @@ -73,6 +73,8 @@ public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler { private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5); private static final String KEY_TYPE = "PRODUCTION"; private static final String EMPTY_STRING = ""; + private static final String JSON_SERIAL_KEY = "SerialNumber"; + private static final String JSON_TENANT_KEY = "Tenant"; /** * Default constructor for the VirtualFirealarmMQTTConnector. @@ -99,7 +101,8 @@ public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler { String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() .getRealmConfiguration().getAdminUserName(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(applicationUsername); - APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); + APIManagementProviderService apiManagementProviderService = APIUtil + .getAPIManagementProviderService(); String[] tags = {VirtualFireAlarmConstants.DEVICE_TYPE}; ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( VirtualFireAlarmConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true); @@ -156,17 +159,34 @@ public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler { if (log.isDebugEnabled()) { log.debug("Received MQTT message for: [DEVICE.ID-" + deviceId + "]"); } - + JSONObject jsonPayload = new JSONObject(mqttMessage.toString()); String actualMessage; try { + String tenantDomain = (String) jsonPayload.get(JSON_TENANT_KEY); + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceManagementProviderService deviceManagementProviderService = + (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, + null); + ctx.setTenantDomain(tenantDomain, true); + if (deviceManagementProviderService != null) { + DeviceIdentifier identifier = new DeviceIdentifier(deviceId, + VirtualFireAlarmConstants.DEVICE_TYPE); + Device device = deviceManagementProviderService.getDevice(identifier); + if (device != null) { + String owner = device.getEnrolmentInfo().getOwner(); + ctx.setUsername(owner); + } else { + return; + } + } + Long serialNo = (Long)jsonPayload.get(JSON_SERIAL_KEY); // the hash-code of the deviceId is used as the alias for device certificates during SCEP enrollment. // hence, the same is used here to fetch the device-specific-certificate from the key store. - PublicKey clientPublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey(deviceId); - PrivateKey serverPrivateKey = SecurityManager.getServerPrivateKey(); + PublicKey clientPublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey("" + serialNo); // the MQTT-messages from VirtualFireAlarm devices are in the form {"Msg":, "Sig":} actualMessage = VirtualFireAlarmServiceUtils.extractMessageFromPayload(mqttMessage.toString(), - serverPrivateKey, clientPublicKey); if (log.isDebugEnabled()) { log.debug("MQTT: Received Message [" + actualMessage + "] topic: [" + topic + "]"); @@ -174,30 +194,8 @@ public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler { if (actualMessage.contains("PUBLISHER")) { float temperature = Float.parseFloat(actualMessage.split(":")[2]); - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceManagementProviderService deviceManagementProviderService = - (DeviceManagementProviderService) ctx - .getOSGiService(DeviceManagementProviderService.class, null); - if (deviceManagementProviderService != null) { - DeviceIdentifier identifier = new DeviceIdentifier(deviceId, - VirtualFireAlarmConstants.DEVICE_TYPE); - Device device = deviceManagementProviderService.getDevice(identifier); - if (device != null) { - String owner = device.getEnrolmentInfo().getOwner(); - ctx.setTenantDomain(MultitenantUtils.getTenantDomain(owner), true); - ctx.setUsername(owner); - if (!VirtualFireAlarmServiceUtils.publishToDAS(deviceId, temperature)) { - log.error("MQTT Subscriber: Publishing data to DAS failed."); - } - } - } - } catch (DeviceManagementException e) { - log.error("Failed to retreive the device managment service for device type " + - VirtualFireAlarmConstants.DEVICE_TYPE, e); - } finally { - PrivilegedCarbonContext.endTenantFlow(); + if (!VirtualFireAlarmServiceUtils.publishToDAS(deviceId, temperature)) { + log.error("MQTT Subscriber: Publishing data to DAS failed."); } if (log.isDebugEnabled()) { log.debug("MQTT Subscriber: Published data to DAS successfully."); @@ -210,6 +208,11 @@ public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler { String errorMsg = "CertificateManagementService failure oo Signature-Verification/Decryption was unsuccessful."; log.error(errorMsg, e); + } catch (DeviceManagementException e) { + log.error("Failed to retreive the device managment service for device type " + + VirtualFireAlarmConstants.DEVICE_TYPE, e); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } } else { String errorMsg = @@ -225,39 +228,30 @@ public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler { */ @Override public void publishDeviceData(String... publishData) throws TransportHandlerException { - if (publishData.length != 4) { + if (publishData.length != 3) { String errorMsg = "Incorrect number of arguments received to SEND-MQTT Message. " + "Need to be [owner, deviceId, resource{BULB/TEMP}, state{ON/OFF or null}]"; log.error(errorMsg); throw new TransportHandlerException(errorMsg); } - String deviceOwner = publishData[0]; - String deviceId = publishData[1]; - String resource = publishData[2]; - String state = publishData[3]; + String deviceId = publishData[0]; + String resource = publishData[1]; + String state = publishData[2]; MqttMessage pushMessage = new MqttMessage(); String publishTopic = "wso2/" + VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId; try { - PublicKey devicePublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey(deviceId); PrivateKey serverPrivateKey = SecurityManager.getServerPrivateKey(); - String actualMessage = resource + ":" + state; - String encryptedMsg = VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage, - devicePublicKey, - serverPrivateKey); - + String encryptedMsg = VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage, serverPrivateKey); pushMessage.setPayload(encryptedMsg.getBytes(StandardCharsets.UTF_8)); pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE); pushMessage.setRetained(false); - publishToQueue(publishTopic, pushMessage); - } catch (VirtualFireAlarmException e) { - String errorMsg = "Preparing Secure payload failed for device - [" + deviceId + "] of owner - " + - "[" + deviceOwner + "]."; + String errorMsg = "Preparing Secure payload failed for device - [" + deviceId + "]"; log.error(errorMsg); throw new TransportHandlerException(errorMsg, e); } diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/transport/VirtualFireAlarmXMPPConnector.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/transport/VirtualFireAlarmXMPPConnector.java index 7f6355744..420567952 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/transport/VirtualFireAlarmXMPPConnector.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/transport/VirtualFireAlarmXMPPConnector.java @@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.transport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jivesoftware.smack.packet.Message; +import org.json.JSONObject; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppAccount; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig; @@ -29,15 +30,14 @@ import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.transport.xmpp.XMPPTransportHandler; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.VirtualFireAlarmServiceUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.io.File; import java.security.PrivateKey; import java.security.PublicKey; -import java.util.Calendar; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -52,6 +52,7 @@ public class VirtualFireAlarmXMPPConnector extends XMPPTransportHandler { private static String xmppVFireAlarmAdminAccountJID; private static final String V_FIREALARM_XMPP_PASSWORD = "vfirealarm@123"; private static final String DEVICEMGT_CONFIG_FILE = "devicemgt-config.xml"; + private static final String JSON_SERIAL_KEY = "SerialNumber"; private ScheduledFuture connectorServiceHandler; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); @@ -155,9 +156,15 @@ public class VirtualFireAlarmXMPPConnector extends XMPPTransportHandler { } try { - PublicKey clientPublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey(deviceId); - PrivateKey serverPrivateKey = SecurityManager.getServerPrivateKey(); - String actualMessage = VirtualFireAlarmServiceUtils.extractMessageFromPayload(message, serverPrivateKey, + PrivilegedCarbonContext.startTenantFlow(); + String tenantDomain = MultitenantUtils.getTenantDomain(owner); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(owner); + + JSONObject jsonPayload = new JSONObject(message); + Long serialNo = (Long)jsonPayload.get(JSON_SERIAL_KEY); + PublicKey clientPublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey("" + serialNo); + String actualMessage = VirtualFireAlarmServiceUtils.extractMessageFromPayload(message, clientPublicKey); if (log.isDebugEnabled()) { log.debug("XMPP: Received Message [" + actualMessage + "] from: [" + from + "]"); @@ -166,10 +173,6 @@ public class VirtualFireAlarmXMPPConnector extends XMPPTransportHandler { switch (subject) { case "PUBLISHER": float temperature = Float.parseFloat(actualMessage.split(":")[1]); - PrivilegedCarbonContext.startTenantFlow(); - String tenantDomain = MultitenantUtils.getTenantDomain(owner); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(owner); if (!VirtualFireAlarmServiceUtils.publishToDAS(deviceId, temperature)) { log.error("XMPP Connector: Publishing VirtualFirealarm data to DAS failed."); } @@ -194,6 +197,8 @@ public class VirtualFireAlarmXMPPConnector extends XMPPTransportHandler { String errorMsg = "CertificateManagementService failure oo Signature-Verification/Decryption was unsuccessful."; log.error(errorMsg, e); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } } else { log.warn("Received XMPP message from client with unexpected JID [" + from + "]."); @@ -215,14 +220,9 @@ public class VirtualFireAlarmXMPPConnector extends XMPPTransportHandler { String state = publishData[3]; try { - PublicKey devicePublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey(deviceId); PrivateKey serverPrivateKey = SecurityManager.getServerPrivateKey(); - String actualMessage = resource + ":" + state; - String encryptedMsg = VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage, - devicePublicKey, - serverPrivateKey); - + String encryptedMsg = VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage, serverPrivateKey); String clientToConnect = deviceId + "@" + xmppServerIP + File.separator + deviceOwner; sendXMPPMessage(clientToConnect, encryptedMsg, "CONTROL-REQUEST"); diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/APIUtil.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/APIUtil.java index ed6f9892c..cb32ee5da 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/APIUtil.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/APIUtil.java @@ -13,9 +13,13 @@ import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.user.core.service.RealmService; import java.util.ArrayList; import java.util.HashMap; @@ -63,7 +67,8 @@ public class APIUtil { return analyticsDataAPI; } - public static List getAllEventsForDevice(String tableName, String query, List sortByFields) throws AnalyticsException { + public static List getAllEventsForDevice(String tableName, String query, + List sortByFields) throws AnalyticsException { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI(); int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); @@ -159,4 +164,52 @@ public class APIUtil { PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); return threadLocalCarbonContext.getTenantDomain(); } + + public static UserStoreManager getUserStoreManager() { + RealmService realmService; + UserStoreManager userStoreManager; + try { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); + if (realmService == null) { + String msg = "Realm service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + int tenantId = ctx.getTenantId(); + userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager(); + } catch (UserStoreException e) { + String msg = "Error occurred while retrieving current user store manager"; + log.error(msg, e); + throw new IllegalStateException(msg); + } + return userStoreManager; + } + + public static void registerApiAccessRoles(String user) { + UserStoreManager userStoreManager = null; + try { + userStoreManager = getUserStoreManager(); + if (userStoreManager != null) { + String[] userList = new String[]{user}; + if (!userStoreManager.isExistingRole(Constants.DEFAULT_ROLE_NAME)) { + userStoreManager.addRole(Constants.DEFAULT_ROLE_NAME, userList, Constants.DEFAULT_PERMISSION); + } + } + } catch (UserStoreException e) { + log.error("Error while creating a role and adding a user for virtual_firealarm.", e); + } + } + + public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceAccessAuthorizationService deviceAccessAuthorizationService = + (DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null); + if (deviceAccessAuthorizationService == null) { + String msg = "Device Authorization service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return deviceAccessAuthorizationService; + } } diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/Constants.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/Constants.java new file mode 100644 index 000000000..97ae2b8f8 --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/Constants.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.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.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util; + +import org.wso2.carbon.user.core.Permission; + +/** + * This hold the constants related to the device type. + */ +public class Constants { + + public static final String DEFAULT_PERMISSION_RESOURCE = "/permission/admin/device-mgt/virtual_firealarm/user"; + public static final String DEFAULT_ROLE_NAME = "virtual_firealarm_user"; + public static final Permission DEFAULT_PERMISSION[] = new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE, + "ui.execute")}; +} diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmServiceUtils.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmServiceUtils.java index 21f27acf9..7d29f8ffd 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmServiceUtils.java +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmServiceUtils.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util; +import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; @@ -253,8 +254,6 @@ public class VirtualFireAlarmServiceUtils { payloadData); } catch (DataPublisherConfigurationException e) { return false; - } finally { - PrivilegedCarbonContext.endTenantFlow(); } return true; } @@ -264,43 +263,39 @@ public class VirtualFireAlarmServiceUtils { /** * * @param message - * @param encryptionKey * @param signatureKey * @return * @throws VirtualFireAlarmException */ - public static String prepareSecurePayLoad(String message, Key encryptionKey, PrivateKey signatureKey) - throws VirtualFireAlarmException { - String encryptedMsg = SecurityManager.encryptMessage(message, encryptionKey); - String signedPayload = SecurityManager.signMessage(encryptedMsg, signatureKey); - + public static String prepareSecurePayLoad(String message, PrivateKey signatureKey) throws VirtualFireAlarmException { + message = Base64.encodeBase64String(message.getBytes()); + String signedPayload = SecurityManager.signMessage(message, signatureKey); JSONObject jsonPayload = new JSONObject(); - jsonPayload.put(JSON_MESSAGE_KEY, encryptedMsg); + jsonPayload.put(JSON_MESSAGE_KEY, message); jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload); - return jsonPayload.toString(); } /** * * @param message - * @param decryptionKey * @param verifySignatureKey * @return * @throws VirtualFireAlarmException */ - public static String extractMessageFromPayload(String message, Key decryptionKey, PublicKey verifySignatureKey) + public static String extractMessageFromPayload(String message, PublicKey verifySignatureKey) throws VirtualFireAlarmException { String actualMessage; JSONObject jsonPayload = new JSONObject(message); - Object encryptedMessage = jsonPayload.get(JSON_MESSAGE_KEY); + Object encodedMessage = jsonPayload.get(JSON_MESSAGE_KEY); Object signedPayload = jsonPayload.get(JSON_SIGNATURE_KEY); - if (encryptedMessage != null && signedPayload != null) { + if (encodedMessage != null && signedPayload != null) { if (SecurityManager.verifySignature( - encryptedMessage.toString(), signedPayload.toString(), verifySignatureKey)) { - actualMessage = SecurityManager.decryptMessage(encryptedMessage.toString(), decryptionKey); + encodedMessage.toString(), signedPayload.toString(), verifySignatureKey)) { + actualMessage = new String(Base64.decodeBase64(encodedMessage.toString())); + //SecurityManager.decryptMessage(encryptedMessage.toString(), decryptionKey); } else { String errorMsg = "The message was not signed by a valid client. Could not verify signature on payload"; throw new VirtualFireAlarmException(errorMsg); @@ -316,17 +311,13 @@ public class VirtualFireAlarmServiceUtils { /** * - * @param deviceId + * @param alias * @return * @throws VirtualFireAlarmException */ - public static PublicKey getDevicePublicKey(String deviceId) throws VirtualFireAlarmException { + public static PublicKey getDevicePublicKey(String alias) throws VirtualFireAlarmException { PublicKey clientPublicKey; - String alias = ""; - try { - alias += deviceId.hashCode(); - CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils.getCertificateManagementService(); X509Certificate clientCertificate = (X509Certificate) certificateManagementService.getCertificateByAlias( @@ -348,7 +339,7 @@ public class VirtualFireAlarmServiceUtils { } throw new VirtualFireAlarmException(errorMsg, e); } else { - errorMsg = "An error occurred whilst trying to retrieve certificate for deviceId [" + deviceId + + errorMsg = "An error occurred whilst trying to retrieve certificate for alias [" + alias + "] with alias: [" + alias + "]"; if(log.isDebugEnabled()){ log.debug(errorMsg); diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/META-INF/permissions.xml b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/META-INF/permissions.xml index f855d1dfd..ad503c34c 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/META-INF/permissions.xml +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/META-INF/permissions.xml @@ -30,91 +30,64 @@ Get device - /device-mgt/user/devices/list - /devices/* + /device-mgt/virtual_firealarm/user + /enrollment/devices/* GET virtual_firealarm_user Remove device - /device-mgt/user/devices/remove - /devices/* + /device-mgt/virtual_firealarm/user + /enrollment/devices/* DELETE virtual_firealarm_user Download device - /device-mgt/user/devices/add - /devices/download + /login + /enrollment/devices/download GET virtual_firealarm_user Update device - /device-mgt/user/devices/update - /devices/* + /device-mgt/virtual_firealarm/user + /enrollment/devices/* POST virtual_firealarm_user Get Devices - /device-mgt/user/devices - /devices - GET - virtual_firealarm_user - - - Generate Link - /device-mgt/user/devices/generate_link - /devices/generate_link + /device-mgt/virtual_firealarm/user + /enrollment/devices GET virtual_firealarm_user Register Device - /device-mgt/user/device/register + /device-mgt/virtual_firealarm/user /device/register/*/*/* POST virtual_firealarm_device Control Buzz - /device-mgt/user/device/buzz + /device-mgt/virtual_firealarm/user /device/*/buzz POST virtual_firealarm_user - - Get Temperature - /device-mgt/user/device/temperature - /device/*/temperature - GET - virtual_firealarm_user - Push Temperature - /device-mgt/user/device/temperature + /device-mgt/virtual_firealarm/user /device/temperature POST virtual_firealarm_device - - Get SCEP - /device-mgt/user/device/scep - /device/scep - GET - virtual_firealarm_user - - - Push SCEP - /device-mgt/user/device/scep - /device/scep - POST - virtual_firealarm_device - + Get Stats - /device-mgt/user/device/stats + /device-mgt/virtual_firealarm/user /device/stats/*/sensors/* GET virtual_firealarm_device diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/pom.xml b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/pom.xml new file mode 100644 index 000000000..af055e14d --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/pom.xml @@ -0,0 +1,201 @@ + + + + + + virtual-fire-alarm-plugin + org.wso2.carbon.devicemgt-plugins + 2.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api + war + WSO2 Carbon - IoT Server SCEP Server API + WSO2 Carbon - Virtual FireAlarm SCEP Server API Implementation + http://wso2.org + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + provided + + + org.apache.axis2.wso2 + axis2-client + + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.certificate.mgt.core + provided + + + commons-codec.wso2 + commons-codec + + + + + + + + org.apache.cxf + cxf-rt-frontend-jaxws + provided + + + org.apache.cxf + cxf-rt-frontend-jaxrs + provided + + + org.apache.cxf + cxf-rt-transports-http + provided + + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + commons-httpclient.wso2 + commons-httpclient + provided + + + + org.wso2.carbon + org.wso2.carbon.utils + provided + + + org.bouncycastle.wso2 + bcprov-jdk15on + + + org.wso2.carbon + org.wso2.carbon.user.api + + + org.wso2.carbon + org.wso2.carbon.queuing + + + org.wso2.carbon + org.wso2.carbon.base + + + org.apache.axis2.wso2 + axis2 + + + org.igniterealtime.smack.wso2 + smack + + + org.igniterealtime.smack.wso2 + smackx + + + jaxen + jaxen + + + commons-fileupload.wso2 + commons-fileupload + + + org.apache.ant.wso2 + ant + + + org.apache.ant.wso2 + ant + + + commons-httpclient.wso2 + commons-httpclient + + + org.eclipse.equinox + javax.servlet + + + org.wso2.carbon + org.wso2.carbon.registry.api + + + + + + commons-codec.wso2 + commons-codec + + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + + virtual_firealarm_scep + + + + + + diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServer.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServer.java new file mode 100644 index 000000000..c5b4676bc --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServer.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.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.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import java.io.InputStream; + + +public interface VirtualFireAlarmScepServer { + + /** + * This is an API called/used by the SCEP Client of the VirtualFirealarm device in its SCEP enrollment process. + * This acts as the endpoint exposed as part of the SCEP-Server for use by a SCEP Client. This is one of the two + * method-signatures that takes different parameters according to the SCEP-Operation executed by the SCEP-Client + * of the enrolling device. The API supports 2 SCEP Operations [GetCACert] and [GetCACaps]. + *

+ * Operation [GetCACert] returns the CA cert of the SCEP-Server for the device to verify its authenticity. + * Operation [GetCACaps] returns the CA Capabilities of the SCEP-Server. + * + * @param operation the SCEP operation requested by the client. [GetCACert] or [GetCACaps] + * @param message any messages pertaining to the requested SCEP Operation. + * @return an HTTP Response object with either the CA-Cert or the CA-Capabilities according to the operation. + */ + @GET + @Path("scep") + Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message); + + + /** + * This is an API called/used by the SCEP Client of the VirtualFirealarm device in its SCEP enrollment process. + * This acts as the endpoint exposed as part of the SCEP-Server for use by a SCEP Client. This is one of the two + * method-signatures that takes different parameters according to the SCEP-Operation executed by the SCEP-Client + * of the enrolling device. This API supports the SCEP Operation [PKIOperation]. + *

+ * Operation [PKIOperation] returns a certificate generated by the SCEP-Server for the enrolling device. + * + * @param operation the final SCEP operation executed in the enrollment process - which is [PKIOperation] + * @param inputStream an input stream consisting of the Certificate-Signing-Request (CSR) from the device. + * @return an HTTP Response object with the signed certificate for the device by the CA of the SCEP Server. + */ + @POST + @Path("scep") + Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream); + +} diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServerImpl.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServerImpl.java new file mode 100644 index 000000000..c2f7a17e6 --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServerImpl.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.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.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse; +import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.exception.VirtualFireAlarmException; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.scep.ContentType; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.scep.SCEPOperation; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.VirtualFireAlarmServiceUtils; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.InputStream; + +@SuppressWarnings("Non-Annoted WebService") +public class VirtualFireAlarmScepServerImpl implements VirtualFireAlarmScepServer { + + private static Log log = LogFactory.getLog(VirtualFireAlarmScepServerImpl.class); + + @GET + @Path("scep") + public Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message) { + if (log.isDebugEnabled()) { + log.debug("Invoking SCEP operation " + operation); + } + if (SCEPOperation.GET_CA_CERT.getValue().equals(operation)) { + if (log.isDebugEnabled()) { + log.debug("Invoking GetCACert"); + } + try { + CertificateManagementService certificateManagementService = + VirtualFireAlarmServiceUtils.getCertificateManagementService(); + SCEPResponse scepResponse = certificateManagementService.getCACertSCEP(); + Response.ResponseBuilder responseBuilder; + switch (scepResponse.getResultCriteria()) { + case CA_CERT_FAILED: + log.error("CA cert failed"); + responseBuilder = Response.serverError(); + break; + case CA_CERT_RECEIVED: + if (log.isDebugEnabled()) { + log.debug("CA certificate received in GetCACert"); + } + responseBuilder = Response.ok(scepResponse.getEncodedResponse(), + ContentType.X_X509_CA_CERT); + break; + case CA_RA_CERT_RECEIVED: + if (log.isDebugEnabled()) { + log.debug("CA and RA certificates received in GetCACert"); + } + responseBuilder = Response.ok(scepResponse.getEncodedResponse(), + ContentType.X_X509_CA_RA_CERT); + break; + default: + log.error("Invalid SCEP request"); + responseBuilder = Response.serverError(); + break; + } + + return responseBuilder.build(); + } catch (VirtualFireAlarmException e) { + log.error("Error occurred while enrolling the VirtualFireAlarm device", e); + } catch (KeystoreException e) { + log.error("Keystore error occurred while enrolling the VirtualFireAlarm device", e); + } + + } else if (SCEPOperation.GET_CA_CAPS.getValue().equals(operation)) { + + if (log.isDebugEnabled()) { + log.debug("Invoking GetCACaps"); + } + try { + CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. + getCertificateManagementService(); + byte caCaps[] = certificateManagementService.getCACapsSCEP(); + + return Response.ok(caCaps, MediaType.TEXT_PLAIN).build(); + + } catch (VirtualFireAlarmException e) { + log.error("Error occurred while enrolling the device", e); + } + } else { + log.error("Invalid SCEP operation " + operation); + } + return Response.serverError().build(); + } + + @POST + @Path("scep") + public Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream) { + if (log.isDebugEnabled()) { + log.debug("Invoking SCEP operation " + operation); + } + if (SCEPOperation.PKI_OPERATION.getValue().equals(operation)) { + if (log.isDebugEnabled()) { + log.debug("Invoking PKIOperation"); + } + try { + CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. + getCertificateManagementService(); + byte pkiMessage[] = certificateManagementService.getPKIMessageSCEP(inputStream); + return Response.ok(pkiMessage, ContentType.X_PKI_MESSAGE).build(); + } catch (VirtualFireAlarmException e) { + log.error("Error occurred while enrolling the device", e); + } catch (KeystoreException e) { + log.error("Keystore error occurred while enrolling the device", e); + } + } + return Response.serverError().build(); + } + +} diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/exception/VirtualFireAlarmException.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/exception/VirtualFireAlarmException.java new file mode 100644 index 000000000..4a81ec6d5 --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/exception/VirtualFireAlarmException.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.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.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.exception; + +public class VirtualFireAlarmException extends Exception { + private static final long serialVersionUID = 118512086957330189L; + + public VirtualFireAlarmException(String errorMessage) { + super(errorMessage); + } + + public VirtualFireAlarmException(String errorMessage, Throwable throwable) { + super(errorMessage, throwable); + } +} diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/VirtualFireAlarmServiceUtils.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/VirtualFireAlarmServiceUtils.java new file mode 100644 index 000000000..de3d1e6a2 --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/VirtualFireAlarmServiceUtils.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.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.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.exception.VirtualFireAlarmException; + +import java.lang.*; +import java.security.PublicKey; +import java.security.cert.X509Certificate; + +/** + * + */ +public class VirtualFireAlarmServiceUtils { + private static final Log log = LogFactory.getLog(VirtualFireAlarmServiceUtils.class); + + /** + * + * @return + * @throws VirtualFireAlarmException + */ + public static CertificateManagementService getCertificateManagementService() throws VirtualFireAlarmException { + + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + CertificateManagementService certificateManagementService = (CertificateManagementService) + ctx.getOSGiService(CertificateManagementService.class, null); + + if (certificateManagementService == null) { + String msg = "EnrollmentService is not initialized"; + log.error(msg); + throw new VirtualFireAlarmException(msg); + } + + return certificateManagementService; + } + + /** + * + * @param deviceId + * @return + * @throws VirtualFireAlarmException + */ + public static PublicKey getDevicePublicKey(String deviceId) throws VirtualFireAlarmException { + PublicKey clientPublicKey; + String alias = ""; + + try { + alias += deviceId.hashCode(); + + CertificateManagementService certificateManagementService = + VirtualFireAlarmServiceUtils.getCertificateManagementService(); + X509Certificate clientCertificate = (X509Certificate) certificateManagementService.getCertificateByAlias( + alias); + clientPublicKey = clientCertificate.getPublicKey(); + + } catch (VirtualFireAlarmException e) { + String errorMsg = "Could not retrieve CertificateManagementService from the runtime."; + if(log.isDebugEnabled()){ + log.debug(errorMsg); + } + throw new VirtualFireAlarmException(errorMsg, e); + } catch (KeystoreException e) { + String errorMsg; + if (e.getMessage().contains("NULL_CERT")) { + errorMsg = "The Device-View page might have been accessed prior to the device being started."; + if(log.isDebugEnabled()){ + log.debug(errorMsg); + } + throw new VirtualFireAlarmException(errorMsg, e); + } else { + errorMsg = "An error occurred whilst trying to retrieve certificate for deviceId [" + deviceId + + "] with alias: [" + alias + "]"; + if(log.isDebugEnabled()){ + log.debug(errorMsg); + } + throw new VirtualFireAlarmException(errorMsg, e); + } + } + return clientPublicKey; + } + +} diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/ContentType.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/ContentType.java new file mode 100644 index 000000000..707ca75fd --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/ContentType.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.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.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.scep; + +public class ContentType { + public static final String X_PKI_MESSAGE = "application/x-pki-message"; + public static final String X_X509_CA_CERT = "application/x-x509-ca-cert"; + public static final String X_X509_CA_RA_CERT = "application/x-x509-ca-ra-cert"; +} + diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/SCEPOperation.java b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/SCEPOperation.java new file mode 100644 index 000000000..b93a99016 --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/SCEPOperation.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.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.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.scep; + +public enum SCEPOperation { + GET_CA_CERT("GetCACert"), + GET_CA_CAPS("GetCACaps"), + PKI_OPERATION("PKIOperation"); + + private String value; + + private SCEPOperation(String value) { + this.setValue(value); + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 000000000..fa4461919 --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 000000000..23280d436 --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/web.xml b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000..1daeeb516 --- /dev/null +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,46 @@ + + + WSO2 IoT Server + WSO2 IoT Server + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + CXFServlet + /* + + + isAdminService + false + + + doAuthentication + false + + + isSharedWithAllTenants + true + + + providerTenantDomain + carbon.super + + + + + managed-api-enabled + false + + + managed-api-owner + admin + + + \ No newline at end of file diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.device-view/device-view.hbs b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.device-view/device-view.hbs index c6d599d8e..2d2d6fead 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.device-view/device-view.hbs +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.device-view/device-view.hbs @@ -15,7 +15,7 @@ Operations

- {{unit "iot.unit.device.operation-bar" device=device}} + {{unit "iot.unit.device.operation-bar" device=device backendApiUri=backendApiUri}}
{{/zone}} diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.device-view/device-view.js b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.device-view/device-view.js index dbec07bd6..fcbb3c0e9 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.device-view/device-view.js +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.device-view/device-view.js @@ -24,9 +24,8 @@ function onRequest(context) { if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { var deviceModule = require("/app/modules/device.js").deviceModule; var device = deviceModule.viewDevice(deviceType, deviceId); - if (device && device.status != "error") { - return {"device": device}; + return {"device": device, "backendApiUri" : devicemgtProps["httpsURL"] + "/virtual_firealarm/"}; } else { response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!"); exit(); diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.type-view/public/js/download.js b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.type-view/public/js/download.js index c9dd69c05..d16ad4a78 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.type-view/public/js/download.js +++ b/components/iot-plugins/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.virtual_firealarm.type-view/public/js/download.js @@ -140,10 +140,6 @@ function downloadAgent() { $('#downloadForm').submit(); hideAgentDownloadPopup(); $(modalPopupContent).html($('#device-agent-downloading-content').html()); - showAgentDownloadPopup(); - setTimeout(function () { - hideAgentDownloadPopup(); - }, 1000); } else { $("#invalid-username-error-msg span").text("Invalid device name"); $("#invalid-username-error-msg").removeClass("hidden"); diff --git a/components/iot-plugins/virtual-fire-alarm-plugin/pom.xml b/components/iot-plugins/virtual-fire-alarm-plugin/pom.xml index 305393197..613c9b81f 100644 --- a/components/iot-plugins/virtual-fire-alarm-plugin/pom.xml +++ b/components/iot-plugins/virtual-fire-alarm-plugin/pom.xml @@ -38,6 +38,7 @@ org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl org.wso2.carbon.device.mgt.iot.virtualfirealarm.api + org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api diff --git a/features/iot-plugins-feature/androidsense-plugin-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/p2.inf b/features/iot-plugins-feature/androidsense-plugin-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/p2.inf index 7790b5b36..184f4bc9a 100644 --- a/features/iot-plugins-feature/androidsense-plugin-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/p2.inf +++ b/features/iot-plugins-feature/androidsense-plugin-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/p2.inf @@ -9,9 +9,6 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/android_sense/);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/android_sense/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\ diff --git a/features/iot-plugins-feature/iot-base-plugin-feature/org.wso2.carbon.device.mgt.iot.feature/src/main/resources/conf/devicemgt-config.xml b/features/iot-plugins-feature/iot-base-plugin-feature/org.wso2.carbon.device.mgt.iot.feature/src/main/resources/conf/devicemgt-config.xml index b245214be..add9c2ee2 100644 --- a/features/iot-plugins-feature/iot-base-plugin-feature/org.wso2.carbon.device.mgt.iot.feature/src/main/resources/conf/devicemgt-config.xml +++ b/features/iot-plugins-feature/iot-base-plugin-feature/org.wso2.carbon.device.mgt.iot.feature/src/main/resources/conf/devicemgt-config.xml @@ -36,10 +36,10 @@ false org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient XMPP - http://204.232.188.215 + http://localhost 9090 admin - wso2iot123 + admin diff --git a/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/pom.xml b/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/pom.xml index 97398f640..6cd36e17c 100644 --- a/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/pom.xml +++ b/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/pom.xml @@ -46,6 +46,11 @@ org.wso2.carbon.device.mgt.iot.virtualfirealarm.api war + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api + war + com.h2database.wso2 h2-database-engine @@ -124,6 +129,15 @@ ${project.build.directory}/maven-shared-archive-resources/webapps/ virtual_firealarm.war + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api + + war + true + ${project.build.directory}/maven-shared-archive-resources/webapps/ + virtual_firealarm_scep.war + diff --git a/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/advanced_agent/deviceConfig.properties b/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/advanced_agent/deviceConfig.properties index 9e200340e..872e74208 100644 --- a/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/advanced_agent/deviceConfig.properties +++ b/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/advanced_agent/deviceConfig.properties @@ -20,7 +20,8 @@ server-name=${SERVER_NAME} owner=${DEVICE_OWNER} deviceId=${DEVICE_ID} device-name=${DEVICE_NAME} -controller-context=/virtual_firealarm/controller +controller-context=/virtual_firealarm/device +scep-context=/virtual_firealarm_scep https-ep=${HTTPS_EP} http-ep=${HTTP_EP} apim-ep=${APIM_EP} diff --git a/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/agent/deviceConfig.properties b/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/agent/deviceConfig.properties index 9e200340e..872e74208 100644 --- a/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/agent/deviceConfig.properties +++ b/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/agent/deviceConfig.properties @@ -20,7 +20,8 @@ server-name=${SERVER_NAME} owner=${DEVICE_OWNER} deviceId=${DEVICE_ID} device-name=${DEVICE_NAME} -controller-context=/virtual_firealarm/controller +controller-context=/virtual_firealarm/device +scep-context=/virtual_firealarm_scep https-ep=${HTTPS_EP} http-ep=${HTTP_EP} apim-ep=${APIM_EP} diff --git a/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/configs/virtual_firealarm.json b/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/configs/virtual_firealarm.json index 5fab6136d..a878ee05a 100644 --- a/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/configs/virtual_firealarm.json +++ b/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/configs/virtual_firealarm.json @@ -2,7 +2,7 @@ "deviceType": { "label": "Virtual Firealarm", "category": "virtual", - "downloadAgentLinkGenUri": "manager/device/virtual_firealarm/generate_link" + "downloadAgentUri": "virtual_firealarm/enrollment/devices/download" }, "analyticStreams": [ { diff --git a/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/p2.inf b/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/p2.inf index 540535f3b..ec1c2fafb 100644 --- a/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/p2.inf +++ b/features/iot-plugins-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/p2.inf @@ -19,6 +19,8 @@ instructions.unconfigure = \ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/device-types/virtual_firealarm.json);\ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/virtual_firealarm.war);\ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/virtual_firealarm);\ +org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/virtual_firealarm_scep.war);\ +org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/virtual_firealarm_scep);\ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../dbscripts/cdm/plugins/virtual_firealarm);\ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../resources/sketches/virtual_firealarm);\ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../resources/sketches/virtual_firealarm_advanced);\ diff --git a/pom.xml b/pom.xml index 7c0a7be07..f002f58e5 100644 --- a/pom.xml +++ b/pom.xml @@ -423,6 +423,12 @@ ${carbon.devicemgt.plugins.version} war + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api + ${carbon.devicemgt.plugins.version} + war + org.wso2.carbon.devicemgt-plugins