android

Android management API onboard a device error


We are using Android Management Api to provision an Android 14 device with the native Google DPC using the '6-Taps at startup' method,and are really struggling to get it working. (We have tried it on Android 12 & 13 with the same result)

We are producing a QR code using a JSON payload of the following format :

{
    "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME": "com.google.android.apps.work.clouddpc/.receivers.CloudDeviceAdminReceiver",
    "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM": "MY_BASE64_CHECKSUM",
    "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION": "https://play.google.com/managed/downloadManagingApp?identifier=setup",
    "android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS" :"true",
   "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED" :"true",
    "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE":{
        "com.google.android.apps.work.clouddpc.EXTRA_ENROLLMENT_TOKEN": "MY_ENROLLMENT_TOKEN"
    }
}

Our method for generating the 20 character Enrollment Token ('AnotherClass.GetEnrollment()') - not detailed here as it is not relevant),is correct (it works with afw#setup).

We are am generating the checksum by :

  1. getting an array of bytes from the file at "https://play.google.com/managed/downloadManagingApp?identifier=setup"
  2. encoding the base64 checksum of the file.

However, when we scan the code on the phone, it asks for Wifi credentials, then carries on. It then gets to the "Getting ready for work setup..." stage, then after a few minutes it stops and we get a message "Can't set up device" and we have to reset the device.

Our questions are :

  1. Is this code correct?

  2. Are the parameters in the payload correct? Some places say use '"android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM' others say use 'PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM'?

  3. are there any other parameters that we need?

  4. Other sources say we need to use 'keytool' command line tool to generate the checksum. Surely we need to generate this on the fly in C# as the DPC version must be subject to change at any time?

  5. If the 'afw#setup' method does not need this stuff to install the native DPC, when why do we even need the location/checksum at all? (Have tried omitting these and that did not work either).

What is going wrong?

PS. When we try and add in the WiFi details PROVISIONING_WIFI_SSID / PROVISIONING_WIFI_PASSWORD / PROVISIONING_WIFI_SECURITY_TYPE = 'WPA' the device just says 'Cannot connect to Wifi' ( The SSID/Password are definitely correct and there is nothing wrong with the WiFi)

 However that is another issue - for now, we are more concerned with getting the native DPC installed....

(The outcome is the same whether PROVISIONING_SKIP_EDUCATION_SCREENS / android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED are included or not.)

Here is the full listing of our code (with the WiFi stuff commented out) . The QR Code is derived in the 'GetQrBitMap' method.

using Newtonsoft.Json;
using QRCoder; // the Nuget package that actually creates the QR code
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Drawing;
using System.Net.Http;
using System.Security.Cryptography;
using System.Threading.Tasks;

 
 public class ProvisioningData
{
    [JsonProperty("android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME")]
    public string DeviceAdminComponentName { get; set; }

    [JsonProperty("android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION")]
    public string DeviceAdminPackageDownloadLocation { get; set; }

    [JsonProperty("android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM")]
    public string DeviceAdminSignatureChecksum { get; set; }

    [JsonProperty("android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE")]
    public AdminExtrasBundle AdminExtrasBundle { get; set; }

    [JsonProperty("android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS")]
    public string SkipEducationScreens { get; set; }

    [JsonProperty("android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED")]
    public string LeaveAllSystemAppsEnabled { get; set; }

    //[JsonProperty("android.app.extra.PROVISIONING_WIFI_SSID")]
    //public string WifiSsid { get; set; }

    //[JsonProperty("android.app.extra.PROVISIONING_WIFI_PASSWORD")]
    //public string WifiPassword { get; set; }

    //[JsonProperty("android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE")]
    //public string SecurityType { get; set; }


}

public class AdminExtrasBundle
{
    [JsonProperty("com.google.android.apps.work.clouddpc.EXTRA_ENROLLMENT_TOKEN")]
    public string EnrollmentToken { get; set; }
}

public class QRHelper
{

    private static byte[] DownloadFileBytes(string url)
    {
        using (HttpClient client = new HttpClient())
        {
            var response = client.GetAsync(url).Result;
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"Failed to download file. Status code: {response.StatusCode}");
            }

            return response.Content.ReadAsByteArrayAsync().Result;
        }
    }

    private static string CalcChecksum(byte[] fileBytes)
    {
        using (SHA256 sha256 = SHA256.Create())
        {
            byte[] hash = sha256.ComputeHash(fileBytes);
            // Replaces & Trim() needed because apparently  Android Management API I expects the checksum to be in a specific Base64 URL-safe format.
            return Convert.ToBase64String(hash).Replace('+', '-').Replace('/', '_').TrimEnd('=');
        }
    }

    private static System.Drawing.Bitmap GenQrImage(string code)
    {
        QRCodeGenerator qrGenerator = new QRCodeGenerator();
        QRCodeData qrCodeData = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
        QRCode qrCode = new QRCode(qrCodeData);
        return qrCode.GetGraphic(20);
    }

    private static byte[] ImageToByte(Image img)
    {
        ImageConverter converter = new ImageConverter();
        return (byte[])converter.ConvertTo(img, typeof(byte[]));
    }

    private static string GetImageAsBase64String(byte[] bin)
    {
        if (bin != null)
        {
            return Convert.ToBase64String(bin);
        }
        else
        {
            return null;
        }
    }

    public static async Task<Tuple<string, string>> GetQrBitMap()
    {
        string code = await AnotherClass.GetEnrollment();
        string fileUrl = "https://play.google.com/managed/downloadManagingApp?identifier=setup";

        byte[] fileBytes = DownloadFileBytes(fileUrl);
        string checksum = CalcChecksum(fileBytes);

        string ssid = "MY_SSID";
        string pwd = "MY_PASSWORD";
        string securityType = "WPA";

        // Create provisioning data using a DTO
        var provisioningData = new ProvisioningData
        {
            DeviceAdminComponentName = "com.google.android.apps.work.clouddpc/.receivers.CloudDpcAdminReceiver",
            DeviceAdminSignatureChecksum = checksum,
            DeviceAdminPackageDownloadLocation = fileUrl,
            SkipEducationScreens = "true",
            LeaveAllSystemAppsEnabled = "true",
            //WifiSsid = ssid,
            //WifiPassword = pwd,
            //SecurityType = securityType,
            AdminExtrasBundle = new AdminExtrasBundle
            {
                EnrollmentToken =  code
            }
        };

        // Serialize DTO to JSON using Newtonsoft.Json
        string jsonData = JsonConvert.SerializeObject(provisioningData, Formatting.None, new JsonSerializerSettings
        {
            ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
        });


        System.Drawing.Bitmap bmp = GenQrImage(jsonData);
        byte[] bytes = ImageToByte(bmp);
        string ret = GetImageAsBase64String(bytes);

        // see https://stackoverflow.com/questions/30129486/set-img-src-from-byte-array/30130095 ...

        return Tuple.Create("data:image/bmp;base64," + ret, code);
    }

 
}

Solution

  • This is what I had to do.

    A) The JSON Payload format When creating the QR Code, to use the native Google DPC, the most basic JSON payload (if we leave aside embedding the WiFi creds for a moment), needs to resemble the following :

    {
        "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME": "com.google.android.apps.work.clouddpc/.receivers.CloudDeviceAdminReceiver",
        "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION": "https://play.google.com/managed/downloadManagingApp?identifier=setup",
        "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM": "I5YvS0O5hXY46mb01BlRjq4oJJGs2kuUcHvVkAPEXlg",
        "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE": {
            "com.google.android.apps.work.clouddpc.EXTRA_ENROLLMENT_TOKEN": "XXXXXXXXXXXXXXXXXXXX"
        }
    }
    

    B) How the checksum is derived.

    How is the checksum "I5YvS0O5hXY46mb01BlRjq4oJJGs2kuUcHvVkAPEXlg" calculated? This string does appear in the AMAPI documentation at https://developers.google.com/android/management/provision-device, though I am unsure as to how often the Google DPC (and the documentation on this) is updated. Therefore, I think it is useful to understand how this checksum can be derived.

    a) First, you need to download the Java Development Kit (JDK) (the latest at the time of writing is jdk-23) b)If you browse to the Download location at "https://play.google.com/managed/downloadManagingApp?identifier=setup" , your browser will download an apk file with a long, random-looking, name. c) The JDK contains a file called 'toolkit' which can be used to calculate the (SHA 256) checksum . d) assuming you have a Windows PC, open up the Command Prompt. e) In CMD Line : cd "C:\Program Files\Java\jdk-23\bin" (or whatever version of JDK you have) keytool -printcert -jarfile "The Full Path to the Apk file you downloaded .apk"

    f) Two checksums will be produced - it is the SHA256 one we need (NB this is only valid until Dec 19th 2024 18:16 GMT - after that you will have to repeat this procedure (or hope that Google have updated their documentation). g) Please note that the Checksum is in Hex form. You will have to use an online converter (Or ChatGPT et al) to convert it to a URL-safe Base64 encoded string. h) If you perform this procedure before Dec 19th 18:16 GMT, you should get "I5YvS0O5hXY46mb01BlRjq4oJJGs2kuUcHvVkAPEXlg". If you do this AFTER that date/time (when I assume a new version of Google DPC will be issued), you should a different, but valid, answer. (Hopefully Google will have updated their documentation to reflect this anyway).

    C) How to get the QR Code from the JSON Payload.

    There are many libraries you could use. The one I advise to use is ZXing.Net. (https://github.com/micjahn/ZXing.Net) There is an excellent article by Luis Llamas at https://www.luisllamas.es/en/csharp-zxing/ which explains how to generate the QR Code.

    D) Things to watch out for:

    1. Ensure that the QR Code is LARGE enough (and of a good enough resolution) for the camera on the device to take in all the detail. (The QR code will look very detailed and cluttered compared with what you might be used to seeing).
    2. Stick with the "BarcodeWriter" options that Luis Llamas suggests. Messing around with these seems to screw things up.
    3. Ensure your broadband is powerful enough. I tried to test the "worst case scenario" by tethering to another phone during provisioning - it failed everytime. 4)If you are still struggling during your dev process, try putting the QR code you generated into an online QR Code decoder (like https://qrcode-decoder.com/ ) , to see if it decodes BACK to your JSON payload. If not, then you need to tweak your encoding process/options. If the online decoder fails to decode back to your payload, then you can be sure that the device you are trying to provision will not be able to decode it either!