Search in sources :

Example 1 with Base64.encodeBase64String

use of com.google.api.client.util.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.

the class IotHubServiceSasTokenTest method constructor_good_case_flow_check.

// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
@Test
public void constructor_good_case_flow_check() throws Exception {
    // Arrange
    String cryptoProvider = "HmacSHA256";
    String charset = "UTF-8";
    String iotHubName = "b.c.d";
    String hostName = "HOSTNAME." + iotHubName;
    String sharedAccessKeyName = "ACCESSKEYNAME";
    String policyName = "SharedAccessKey";
    String sharedAccessKey = encodeBase64String("1234567890abcdefghijklmnopqrstvwxyz=".getBytes(StandardCharsets.UTF_8));
    String connectionString = "HostName=" + hostName + ";SharedAccessKeyName=" + sharedAccessKeyName + ";" + policyName + "=" + sharedAccessKey;
    IotHubConnectionString iotHubConnectionString = IotHubConnectionStringBuilder.createConnectionString(connectionString);
    // Assert
    new Expectations() {

        URLEncoder urlEncoder;

        System system;

        final SecretKeySpec secretKeySpec;

        Mac mac;

        {
            URLEncoder.encode(hostName.toLowerCase(), String.valueOf(StandardCharsets.UTF_8));
            System.currentTimeMillis();
            // Semmle flags this as sensitive call, but it is a false positive since it is for test purposes
            // lgtm
            byte[] body = { 1 };
            secretKeySpec = new SecretKeySpec(body, cryptoProvider);
            Mac.getInstance(cryptoProvider);
        }
    };
    // Act
    IotHubServiceSasToken iotHubServiceSasToken = new IotHubServiceSasToken(iotHubConnectionString);
}
Also used : Expectations(mockit.Expectations) IotHubServiceSasToken(com.microsoft.azure.sdk.iot.service.auth.IotHubServiceSasToken) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) URLEncoder(java.net.URLEncoder) Mac(javax.crypto.Mac) Test(org.junit.Test)

Example 2 with Base64.encodeBase64String

use of com.google.api.client.util.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.

the class ProvisioningServiceSasTokenTest method constructorCheckFormatSucceeded.

// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string (one year)]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_008: [The function shall return with the generated token]
@Test
public void constructorCheckFormatSucceeded() throws Exception {
    // Arrange
    String deviceProvisioningServiceName = "b.c.d";
    String hostName = "HOSTNAME." + deviceProvisioningServiceName;
    String sharedAccessKeyName = "ACCESSKEYNAME";
    String policyName = "SharedAccessKey";
    String sharedAccessKey = encodeBase64String("key".getBytes(StandardCharsets.UTF_8));
    String connectionString = "HostName=" + hostName + ";SharedAccessKeyName=" + sharedAccessKeyName + ";" + policyName + "=" + sharedAccessKey;
    ProvisioningConnectionString provisioningConnectionString = ProvisioningConnectionStringBuilder.createConnectionString(connectionString);
    // Act
    ProvisioningSasToken provisioningServiceSasToken = new ProvisioningSasToken(provisioningConnectionString);
    String token = provisioningServiceSasToken.toString();
    // Assert
    assertTrue(token.contains("SharedAccessSignature sr=hostname.b.c.d&sig="));
    assertTrue(token.contains("&se="));
    assertTrue(token.contains("&skn=ACCESSKEYNAME"));
}
Also used : ProvisioningConnectionString(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString) ProvisioningSasToken(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningSasToken) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) ProvisioningConnectionString(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString) Test(org.junit.Test)

Example 3 with Base64.encodeBase64String

use of com.google.api.client.util.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.

the class ProvisioningServiceSasTokenTest method constructorSucceeded.

// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
@Test
public void constructorSucceeded() throws Exception {
    // Arrange
    String cryptoProvider = "HmacSHA256";
    String charset = "UTF-8";
    String deviceProvisioningServiceName = "b.c.d";
    String hostName = "HOSTNAME." + deviceProvisioningServiceName;
    String sharedAccessKeyName = "ACCESSKEYNAME";
    String policyName = "SharedAccessKey";
    String sharedAccessKey = encodeBase64String("key".getBytes(StandardCharsets.UTF_8));
    String connectionString = "HostName=" + hostName + ";SharedAccessKeyName=" + sharedAccessKeyName + ";" + policyName + "=" + sharedAccessKey;
    ProvisioningConnectionString provisioningConnectionString = ProvisioningConnectionStringBuilder.createConnectionString(connectionString);
    // Assert
    new Expectations() {

        URLEncoder urlEncoder;

        System system;

        final SecretKeySpec secretKeySpec;

        Mac mac;

        {
            URLEncoder.encode(hostName.toLowerCase(), String.valueOf(StandardCharsets.UTF_8));
            System.currentTimeMillis();
            decodeBase64(sharedAccessKey.getBytes(charset));
            // Semmle flags this as sensitive call, but it is a false positive since it is for test purposes
            // lgtm
            byte[] body = { 1 };
            secretKeySpec = new SecretKeySpec(body, cryptoProvider);
            Mac.getInstance(cryptoProvider);
        }
    };
    // Act
    ProvisioningSasToken provisioningServiceSasToken = new ProvisioningSasToken(provisioningConnectionString);
}
Also used : Expectations(mockit.Expectations) ProvisioningConnectionString(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString) ProvisioningSasToken(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningSasToken) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) ProvisioningConnectionString(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString) URLEncoder(java.net.URLEncoder) Mac(javax.crypto.Mac) Test(org.junit.Test)

Example 4 with Base64.encodeBase64String

use of com.google.api.client.util.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.

the class ContractAPIHttpTest method requestNonceWithDPSTPMSucceeds.

// SRS_ContractAPIHttp_25_004: [This method shall retrieve the Url by calling 'generateRegisterUrl' on an object for UrlPathBuilder.]
// SRS_ContractAPIHttp_25_005: [This method shall prepare the PUT request by setting following headers on a HttpRequest 1. User-Agent : User Agent String for the SDK 2. Accept : "application/json" 3. Content-Type: "application/json; charset=utf-8".]
// SRS_ContractAPIHttp_25_006: [This method shall set the SSLContext for the Http Request.]
// SRS_ContractAPIHttp_25_008: [If service return a status as 404 then this method shall trigger the callback to the user with the response message.]
@Test
public void requestNonceWithDPSTPMSucceeds() throws IOException, ProvisioningDeviceClientException {
    // arrange
    final byte[] expectedPayload = "testByte".getBytes(StandardCharsets.UTF_8);
    ContractAPIHttp contractAPIHttp = createContractClass();
    prepareRequestExpectations();
    new NonStrictExpectations() {

        {
            mockedRequestData.getRegistrationId();
            result = TEST_REGISTRATION_ID;
            mockedRequestData.getEndorsementKey();
            result = TEST_EK;
            mockedRequestData.getStorageRootKey();
            result = TEST_SRK;
            mockedRequestData.getSslContext();
            result = mockedSslContext;
            mockedHttpRequest.send();
            result = mockedHttpResponse;
            ProvisioningDeviceClientExceptionManager.verifyHttpResponse(mockedHttpResponse);
            result = new ProvisioningDeviceHubException("test Exception");
            mockedHttpResponse.getStatus();
            result = 401;
            TpmRegistrationResultParser.createFromJson(new String(mockedHttpResponse.getBody()));
            result = mockedTpmRegistrationResultParser;
            mockedTpmRegistrationResultParser.getAuthenticationKey();
            result = encodeBase64String("some auth key".getBytes(StandardCharsets.UTF_8));
            new DeviceRegistrationParser(anyString, anyString, anyString, anyString);
            result = mockedDeviceRegistrationParser;
            mockedDeviceRegistrationParser.toJson();
            result = "some json";
        }
    };
    // act
    contractAPIHttp.requestNonceForTPM(mockedRequestData, mockedResponseCallback, null);
    // assert
    prepareRequestVerifications(HttpMethod.PUT, 0);
    new Verifications() {

        {
            new UrlPathBuilder(TEST_HOST_NAME, TEST_SCOPE_ID, ProvisioningDeviceClientTransportProtocol.HTTPS);
            times = 1;
            mockedUrlPathBuilder.generateRegisterUrl(TEST_REGISTRATION_ID);
            times = 1;
            mockedHttpRequest.setSSLContext(mockedSslContext);
            times = 1;
            mockedResponseCallback.run((ResponseData) any, null);
            times = 1;
        }
    };
}
Also used : UrlPathBuilder(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) DeviceRegistrationParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser) ContractAPIHttp(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.http.ContractAPIHttp) Test(org.junit.Test)

Example 5 with Base64.encodeBase64String

use of com.google.api.client.util.Base64.encodeBase64String in project gocd by gocd.

the class AgentRegistrationController method agentRequest.

@RequestMapping(value = "/admin/agent", method = RequestMethod.POST)
public ResponseEntity agentRequest(@RequestParam("hostname") String hostname, @RequestParam("uuid") String uuid, @RequestParam("location") String location, @RequestParam("usablespace") String usableSpaceStr, @RequestParam("operatingSystem") String os, @RequestParam("agentAutoRegisterKey") String agentAutoRegisterKey, @RequestParam("agentAutoRegisterResources") String agentAutoRegisterResources, @RequestParam("agentAutoRegisterEnvironments") String agentAutoRegisterEnvs, @RequestParam("agentAutoRegisterHostname") String agentAutoRegisterHostname, @RequestParam("elasticAgentId") String elasticAgentId, @RequestParam("elasticPluginId") String elasticPluginId, @RequestParam("token") String token, HttpServletRequest request) {
    final String ipAddress = request.getRemoteAddr();
    LOG.debug("Processing registration request from agent [{}/{}]", hostname, ipAddress);
    boolean keyEntry;
    String preferredHostname = hostname;
    boolean isElasticAgent = elasticAgentAutoregistrationInfoPresent(elasticAgentId, elasticPluginId);
    try {
        if (!encodeBase64String(hmac().doFinal(uuid.getBytes())).equals(token)) {
            String message = "Not a valid token.";
            LOG.error("Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]" + "ElasticAgentID=[{}] PluginID=[{}]", FORBIDDEN, message, uuid, hostname, elasticAgentId, elasticPluginId);
            return new ResponseEntity<>(message, FORBIDDEN);
        }
        boolean shouldAutoRegister = shouldAutoRegister(agentAutoRegisterKey, isElasticAgent);
        if (shouldAutoRegister) {
            preferredHostname = getPreferredHostname(agentAutoRegisterHostname, hostname);
        } else {
            if (elasticAgentAutoregistrationInfoPresent(elasticAgentId, elasticPluginId)) {
                String message = String.format("Elastic agent registration requires an auto-register agent key to be" + " setup on the server. The agentAutoRegisterKey: [%s] is either not provided or expired. Agent-id: [%s], Plugin-id: [%s]", agentAutoRegisterKey, elasticAgentId, elasticPluginId);
                LOG.error("Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]" + "ElasticAgentID=[{}] PluginID=[{}]", UNPROCESSABLE_ENTITY, message, uuid, hostname, elasticAgentId, elasticPluginId);
                return new ResponseEntity<>(message, UNPROCESSABLE_ENTITY);
            }
        }
        Agent agent = createAgentFromRequest(uuid, preferredHostname, ipAddress, elasticAgentId, elasticPluginId);
        agent.validate();
        if (agent.hasErrors()) {
            List<ConfigErrors> errors = agent.errorsAsList();
            throw new GoConfigInvalidException(null, new AllConfigErrors(errors));
        }
        if (partialElasticAgentAutoregistrationInfo(elasticAgentId, elasticPluginId)) {
            String message = "Elastic agents must submit both elasticAgentId and elasticPluginId.";
            LOG.error("Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]" + "ElasticAgentID=[{}] PluginID=[{}]", UNPROCESSABLE_ENTITY, message, uuid, hostname, elasticAgentId, elasticPluginId);
            return new ResponseEntity<>(message, UNPROCESSABLE_ENTITY);
        }
        if (elasticAgentIdAlreadyRegistered(elasticAgentId, elasticPluginId)) {
            String message = "Duplicate Elastic agent Id used to register elastic agent.";
            LOG.error("Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]" + "ElasticAgentID=[{}] PluginID=[{}]", UNPROCESSABLE_ENTITY, message, uuid, hostname, elasticAgentId, elasticPluginId);
            return new ResponseEntity<>(message, UNPROCESSABLE_ENTITY);
        }
        if (shouldAutoRegister && !agentService.isRegistered(uuid)) {
            LOG.info("[Agent Auto Registration] Auto registering agent with uuid {} ", uuid);
            agent.setEnvironments(agentAutoRegisterEnvs);
            agent.setResources(agentAutoRegisterResources);
            agentService.register(agent);
            if (agent.hasErrors()) {
                throw new GoConfigInvalidException(null, new AllConfigErrors(agent.errorsAsList()).asString());
            }
        }
        boolean registeredAlready = agentService.isRegistered(uuid);
        long usableSpace = Long.parseLong(usableSpaceStr);
        AgentRuntimeInfo agentRuntimeInfo = AgentRuntimeInfo.fromServer(agent, registeredAlready, location, usableSpace, os);
        if (elasticAgentAutoregistrationInfoPresent(elasticAgentId, elasticPluginId)) {
            agentRuntimeInfo = ElasticAgentRuntimeInfo.fromServer(agentRuntimeInfo, elasticAgentId, elasticPluginId);
        }
        keyEntry = agentService.requestRegistration(agentRuntimeInfo);
        final HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<>("", httpHeaders, keyEntry ? OK : ACCEPTED);
    } catch (Exception e) {
        LOG.error("Error occurred during agent registration process. Error: HttpCode=[{}] Message=[{}] UUID=[{}] " + "Hostname=[{}] ElasticAgentID=[{}] PluginID=[{}]", UNPROCESSABLE_ENTITY, getErrorMessage(e), uuid, hostname, elasticAgentId, elasticPluginId, e);
        return new ResponseEntity<>(String.format("Error occurred during agent registration process: %s", getErrorMessage(e)), UNPROCESSABLE_ENTITY);
    }
}
Also used : Agent(com.thoughtworks.go.config.Agent) HttpHeaders(org.springframework.http.HttpHeaders) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) GoConfigInvalidException(com.thoughtworks.go.config.exceptions.GoConfigInvalidException) GoConfigInvalidException(com.thoughtworks.go.config.exceptions.GoConfigInvalidException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) ResponseEntity(org.springframework.http.ResponseEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

Base64.encodeBase64String (org.apache.commons.codec.binary.Base64.encodeBase64String)14 Test (org.junit.Test)8 Mac (javax.crypto.Mac)4 SecretKeySpec (javax.crypto.spec.SecretKeySpec)4 ProvisioningConnectionString (com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString)3 ProvisioningSasToken (com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningSasToken)3 IotHubConnectionString (com.microsoft.azure.sdk.iot.service.IotHubConnectionString)3 IotHubServiceSasToken (com.microsoft.azure.sdk.iot.service.auth.IotHubServiceSasToken)2 URLEncoder (java.net.URLEncoder)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 Expectations (mockit.Expectations)2 NonStrictExpectations (mockit.NonStrictExpectations)2 ResponseEntity (org.springframework.http.ResponseEntity)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 MessageProperty (com.microsoft.azure.sdk.iot.device.MessageProperty)1 SignRequest (com.microsoft.azure.sdk.iot.device.hsm.parser.SignRequest)1 HttpsBatchMessage (com.microsoft.azure.sdk.iot.device.transport.https.HttpsBatchMessage)1 HttpsSingleMessage (com.microsoft.azure.sdk.iot.device.transport.https.HttpsSingleMessage)1 UrlPathBuilder (com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder)1