Connecting to Azure Iot Hub using TPM - java

I have successfully provisioned a device in Azure IoT using TPM authentication by following this sample and the following guide: https://learn.microsoft.com/en-us/azure/iot-dps/quick-enroll-device-tpm-java
Now that my device is provisioned I'm trying to figure out the simplest way to connect to the IoT Hub using the keys stored on the TPM chip. I've tried the following code snippet:
SecurityProviderTpm securityClientTPM = new SecurityProviderTPMHsm();
DeviceClient client = DeviceClient.createFromSecurityProvider("myhub.azure-devices.net", "my-device", securityClientTPM, IotHubClientProtocol.HTTPS);
but this fails with:
Exception in thread "main" java.io.IOException: com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException: activateIdentityKey first before signing
at com.microsoft.azure.sdk.iot.device.auth.IotHubSasTokenHardwareAuthenticationProvider.generateSasTokenSignatureFromSecurityProvider(IotHubSasTokenHardwareAuthenticationProvider.java:169)
at com.microsoft.azure.sdk.iot.device.auth.IotHubSasTokenHardwareAuthenticationProvider.<init>(IotHubSasTokenHardwareAuthenticationProvider.java:51)
at com.microsoft.azure.sdk.iot.device.DeviceClientConfig.<init>(DeviceClientConfig.java:192)
at com.microsoft.azure.sdk.iot.device.InternalClient.<init>(InternalClient.java:109)
at com.microsoft.azure.sdk.iot.device.DeviceClient.<init>(DeviceClient.java:284)
at com.microsoft.azure.sdk.iot.device.DeviceClient.createFromSecurityProvider(DeviceClient.java:250)
at samples.com.microsoft.azure.sdk.iot.SendEvent.main(SendEvent.java:88)
Caused by: com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException: activateIdentityKey first before signing
at com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderTPMHsm.signWithIdentity(SecurityProviderTPMHsm.java:371)
at com.microsoft.azure.sdk.iot.device.auth.IotHubSasTokenHardwareAuthenticationProvider.generateSasTokenSignatureFromSecurityProvider(IotHubSasTokenHardwareAuthenticationProvider.java:155)
... 6 more
Searching the SDK code shows that activateIdentityKey is only called during the provisioning process though.
Re-invoking the provisioning proceedure everytime I want to connect the client doesn't seem right. Is there a better way to connect the device to the IoT Hub once it's been provisioned?

I was able to work around this by removing the check in the signWithIdentity function and removing the need to pass the publicArea to the signData function.
The publicArea is only used to derive the hash algorithm which can be set to a constant given that we know how the key was created.
My updated signData function looks like:
private byte[] signData(Tpm tpm, byte[] tokenData) throws SecurityProviderException {
TPM_ALG_ID idKeyHashAlg = TPM_ALG_ID.SHA256;
...
This has been working well for us so far, but it would be nice to get some feedback from the library authors :)

Related

How to programmatically set external ip for Google Cloud virtual machine in Java?

I am trying to programmatically start Google Cloud virtual machine instances. It occurred to me that in order to have internet access, have to set an external IP address.
// Access Config
AccessConfig accessConfig = AccessConfig.newBuilder()
.setNatIP("foo")
.setType("ONE_TO_ONE_NAT")
.setName("External NAT")
.setExternalIpv6("bar")
.build();
// Use the network interface provided in the networkName argument.
NetworkInterface networkInterface = NetworkInterface.newBuilder()
.setName(networkName)
.setAccessConfigs(0, accessConfig)
.build();
That is my status quo. It is inspired by this article post. I hoped that would work in Java, too, but currently, I am stuck.
All I get is:
com.google.api.gax.rpc.InvalidArgumentException: Bad Request
Unfortunately, Google Cloud Compute Engine Docs doesn't really provide any further information, on how to set the external IP properly.
Thanks in advance.
I have encountered the answer. In the Google Cloud Compute Engine Docs it is explained for Windows Instances. It took me a while to recognize it because I've focused only Linux Instances' related questions.
The solution:
instanceResource = Instance.newBuilder()
.setName(instanceName)
.setMachineType(machineType)
.addDisks(disk)
// Add external internet to instance
.addNetworkInterfaces(NetworkInterface.newBuilder()
.addAccessConfigs(AccessConfig.newBuilder()
.setType("ONE_TO_ONE_NAT")
.setName("External NAT")
.build())
.setName("global/networks/default")
.build())
.setMetadata(buildMetadata())
.build();

How to fix AWS 403 error "Check your AWS Secret Access Key and signing method" when calling SES listcontacts

I have been stuck for about the past 6 hours at this point I'm thinking the only reasonable explanations are that this is a AWS SDK bug or the error message is wrong.
I am using SESv2 class from the AWS SDK in a JAVA SpringBoot app and attempting to manage various details of my SES (Simple Email Service) account.
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sesv2.SesV2Client;
import software.amazon.awssdk.services.sesv2.model.*;
I have created an IAM user, created security credentials, set them up using multiple different methods as described here guid to credentials environment I've given full access to SES to this IAM role user. I then wrote some code and I was able to do all of the following,
Create a contact list
Delete a contact list
Create contact
Create a Topic in a contact list
Send an email
However, for some unknown reason when I go to test a function I wrote to get a list of contacts so I can test sending an email to multiple contacts I get the following 403 error message,
The request signature we calculated does not match the signature you
provided. Check your AWS Secret Access Key and signing method. Consult
the service documentation for details.
I've verified the credentials are correct. I have created a new set of credentials and made the old set inactive. No dice, all the functions listed above still work however the listContacts in the SesV2Client class still fails with the same error. As you can see below I even bypassed the env variables and just hardcoded the key and secret to pull out all the stops, still fails. In the function that fails, I've gone over and over the values im passing in they are valid and exist 100% because as I said I can make the other calls in the list above to verify the topics and contact list exists.
private List<Contact> listContactsForSiteUpdatesMailingList() {
try (SesV2Client client = SesV2Client.builder()
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(awsCreds))
.build()){
TopicFilter topicFilter = TopicFilter.builder().topicName(TOPIC_SITE_UPDATES).useDefaultIfPreferenceUnavailable(true).build();
ListContactsFilter listContactsFilter = ListContactsFilter.builder().topicFilter(topicFilter).filteredStatus(SubscriptionStatus.OPT_IN).build();
ListContactsRequest listContactsRequest = ListContactsRequest.builder()
.contactListName(CONTACT_LIST).filter(listContactsFilter).build();
ListContactsResponse listContactsResponse = client.listContacts(listContactsRequest);
return listContactsResponse.contacts();
} catch (Exception ex) {
System.out.println("The email was not sent. Error message: "
+ ex.getMessage());
return null;
}
}
Whats going on here and how can I get to the bottom of this error?
EDIT:
Looking at AWS Console Users>Access Management and then looking at the user a created I can even verify that there was "programmatic access"
An example of accessing a ContactList with no issues
EDIT 2: My SES account is currently sandboxed. I just wanted to mention the question is this possibly happening because of that? Grasping at straws here.
I was able to reproduce your issue. I created a list and added a contact. Both worked. However, when i executed listContacts, I got this error:
This looks like a bug. To address this, open a Github issue on the SDK Java Github here:
https://github.com/aws/aws-sdk-java
This is confirmed as a bug in the AWS SDK. To get around this you can use the async client like so
SesV2AsyncClient client = SesV2AsyncClient.builder()
.region(Region.US_EAST_1)
.build())
TopicFilter topicFilter = TopicFilter.builder().topicName(TOPIC_SITE_UPDATES).useDefaultIfPreferenceUnavailable(true).build();
ListContactsFilter listContactsFilter = ListContactsFilter.builder().topicFilter(topicFilter).filteredStatus(SubscriptionStatus.OPT_IN).build();
ListContactsRequest listContactsRequest = ListContactsRequest.builder()
.contactListName(CONTACT_LIST).filter(listContactsFilter).build();
CompletableFuture<ListContactsResponse> listContactsResponseCompletableFuture = client.listContacts(listContactsRequest);
ListContactsResponse listContactsResponse = listContactsResponseCompletableFuture.get();

Smack android enable xep-0115 cache

Hello I'am building an android app using smack, the server support both the xep-0030 and the xep-0115, smack also support them.
What I want to achieve is the ability to cache on the client the server capabilities in order to reduce the number of disco#info performed by the client on login.
Based on the smack documentation what I have done is this:
EntityCapsManager entityCapsManager = EntityCapsManager.getInstanceFor(xmppConnection);
entityCapsManager.enableEntityCaps();
EntityCapsPersistentCache cache = new SimpleDirectoryPersistentCache(cacheFile);
entityCapsManager.setPersistentCache(cache);
but even with this lines of code result in the client always performing the same number of disco#info
there is a solution to my problem or I have to leave with that?
this is an example of my presence:
<presence from='romeo#montague.lit/orchard'>
<c xmlns='http://jabber.org/protocol/caps'
hash='sha-1'
node='http://code.google.com/p/exodus'
ver='QgayPKawpkPSDYmwT/WM94uAlu0='/>
</presence>

TokenResponseException: missing scope when using the RemoteAPI of AppEngine in Java with OAuth 2.0 on stand-alone application

My goal is for my stand-alone application to access the datastore of a Google App Engine application so that I can query it. My application used to work with ClientLogin, but I have been asked to use OAuth 2.0 for the authentication (and using ClientLogin doesn't work anymore).
I follow the instructions on this page: https://cloud.google.com/appengine/docs/java/tools/remoteapi
I use the provided code, have made an service account, downloaded the json key, made an environment variable pointing to this key. The result is that I get the following exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
at myApplication.myClass4.moveResultsOfFeature(myClass4.java:51)
at myApplication.myClass2.migrate(MyClass3.java:32)
at myApplication.myClass1.main(Starter.java:11)
Caused by: java.lang.RuntimeException: Failed to acquire Google Application Default credential.
at com.google.appengine.tools.remoteapi.RemoteApiOptions.useApplicationDefaultCredential(RemoteApiOptions.java:163)
at commonMigration.RemoteOptions.<clinit>(RemoteOptions.java:18)
... 3 more
Caused by: com.google.appengine.repackaged.com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_scope",
"error_description" : "Empty or missing scope not allowed."
}
at com.google.appengine.repackaged.com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.appengine.repackaged.com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.appengine.repackaged.com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.appengine.repackaged.com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
at com.google.appengine.repackaged.com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.appengine.tools.remoteapi.RemoteApiOptions.useApplicationDefaultCredential(RemoteApiOptions.java:160)
... 4 more
which seems to point to a missing scope argument, a concern which isn't mentioned in the explication on the web page. Is there an easy way to fix this issue?
Per request, my code (simplified):
public class StackOverflow {
private static RemoteApiOptions REMOTE_OPTIONS = new RemoteApiOptions().server(
<application-id>.appspot.com, 443)
.useApplicationDefaultCredential();
public static void main(String[] args0) throws IOException {
// MAKING THE CONNECTION
RemoteApiInstaller installer = new RemoteApiInstaller();
// LOAD FROM Local
installer.install(REMOTE_OPTIONS);
try {
// MY OPERATIONS
} finally {
installer.uninstall();
}
}
}
This is a current limitation of the Remote API. See the note here:
Note: The Remote API call to useApplicationDefaultCredential() can only use credentials provided by the gcloud command.
(It's possible you followed the instructions before the note was added, since it is a recently discovered limitation). The limitation will be fixed in a future release. For now, you should either run:
gcloud auth login
And use your user account to authenticate using useApplicationDefaultCredential(). Or, you can use a service account with .useServiceAccountCredential, which accepts the service account email and a path to a p12 file instead of the json file.

ADAL 4 Android not passing client secret

I'll first say that I'm sure it is just me since people have probably got this to work out of the box without having to edit the ADAL 4 Android Library without editing the source.
When running the sample program and authenticating with a token I get an error from AZURE that it is not passing the client_secret in the message body. I can confirm that this is in fact the case - it is not passing the client_secret.
Although if I edit the OAuth2.java file and change the method buildTokenRequestMessage to something like the following the workflow works perfectly
public String buildTokenRequestMessage(String code) throws UnsupportedEncodingException {
String message = String.format("%s=%s&%s=%s&%s=%s&%s=%s&%s=%s",
AuthenticationConstants.OAuth2.GRANT_TYPE,
StringExtensions.URLFormEncode(AuthenticationConstants.OAuth2.AUTHORIZATION_CODE),
AuthenticationConstants.OAuth2.CODE, StringExtensions.URLFormEncode(code),
AuthenticationConstants.OAuth2.CLIENT_ID,
StringExtensions.URLFormEncode(mRequest.getClientId()),
AuthenticationConstants.OAuth2.REDIRECT_URI,
StringExtensions.URLFormEncode(mRequest.getRedirectUri())
// these are the two lines I've added to make it work
AuthenticationConstants.OAuth2.CLIENT_SECRET,
StringExtensions.URLFormEncode("<MY CLIENT SECRET>")
);
return message;
}
Am I doing something wrong? If not, what is the correct way to access the client secret?
My implementation is straight from the demo application with only changes being setting up the strings to match my endpoints.
Thanks
You need to register your app as a Native application at Azure AD portal. You don't need client secret for native app.

Categories

Resources