Giter Site home page Giter Site logo

Comments (149)

guerrerotook avatar guerrerotook commented on August 11, 2024 14

Buenas noticias!! Ya he conseguido capturar el tráfico TLS de la app de android y ya tengo todo lo necesario. Además esta semana empiezo dos semanas de vacaciones y me voy a poner a tope con eso.

Voy a cambiar bastantes cosas y simular que es un dispositivo Android en vez de la web que es ahora.

Good news everyone, I successfully capture the TLS traffic in the Android app and now I have everything I need to continue. These next two weeks I will on vacations and I will have a lot of free time.

There are going to be a lot of changes in the code because I'm going to simulate that I'm a Android device instead of the web app.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 10

Hello everyone,

An update of the second factor of authentication. I started the job of integrating this here, https://github.com/guerrerotook/securitas-direct-new-api/tree/otp_challange

I made progress and I'm able to list the customer phone, select one phone and then receive the SMS and validate that the config flow works. From there we can have a funcional system.

There are some edges that need to be fixed, like, how to handle refresh tokens from the API instead of login again. (this will make the integration to ask for the code every hour, something that is not possible).

Bear with me on this, I'm working as fast as I can.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 7

Goods news everyone, I found the refreshlogin operation and I started the integration.

2ce56c0

For now the API throws an error 500 but I need to keep investivating if this thing works or not.

from securitas-direct-new-api.

shantur avatar shantur commented on August 11, 2024 5

@guerrerotook : OWP to OWA Fixed the issue.
I have submitted a PR (#65) which fixes config_flow as well.
I didn't want to change much to make sure it goes well with your plans.

Let me know if this helps.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 5

@guerrerotook : OWP to OWA Fixed the issue. I have submitted a PR (#65) which fixes config_flow as well. I didn't want to change much to make sure it goes well with your plans.

Let me know if this helps.

It works! That was beautiful. I just tested on my local development environment that was executed two weeks ago and it automatically gets a new token and everything works out of the box.

Thanks very much for the contribution @shantur. It fixed everything.

I'm going to clean the code, merge back to master, prepare the release and update the documentation.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 4

Let me take a look at this today. Thanks everyone for the comments and feedback.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 4

Madre mía que cantidad de casos raros que estamos teniendo co la API. En otra issue menciona que hay que refrescar el token cada 5 minutos y no cada 20 como lo tengo ahora mismo. He pedido que me digan lo que han modificado para intentar hacer que esta cosa funcione.

Muchas gracias a todos por los comentarios!

from securitas-direct-new-api.

shantur avatar shantur commented on August 11, 2024 4

@guerrerotook : I have figured out the login flow which leads to proper refresh token and hash. Below are the requests needed. Variables are in <> brackets

Request 1 - mkLoginToken

Headers : None required

Body

{
    "operationName": "mkLoginToken",
    "query": "mutation mkLoginToken($user: String!, $password: String!, $id: String!, $country: String!, $lang: String!, $callby: String!, $idDevice: String!, $idDeviceIndigitall: String!, $deviceType: String!, $deviceVersion: String!, $deviceResolution: String!, $deviceName: String!, $deviceBrand: String!, $deviceOsVersion: String!, $uuid: String!) { xSLoginToken(user: $user, password: $password, country: $country, lang: $lang, callby: $callby, id: $id, idDevice: $idDevice, idDeviceIndigitall: $idDeviceIndigitall, deviceType: $deviceType, deviceVersion: $deviceVersion, deviceResolution: $deviceResolution, deviceName: $deviceName, deviceBrand: $deviceBrand, deviceOsVersion: $deviceOsVersion, uuid: $uuid) { __typename res msg hash refreshToken legals changePassword needDeviceAuthorization mainUser } }",
    "variables": {
        "callby": "OWA_10",
        "country": "GB",
        "deviceBrand": "google",
        "deviceName": "Android SDK built for x86",
        "deviceOsVersion": "10",
        "deviceResolution": "",
        "deviceType": "",
        "deviceVersion": "10.64.0",
        "id": "OWA_______________<username>_______________<timestamp>",
        "idDevice": "<device_id_used_by_firebase_push_notification_not_check_can_be_anything>",
        "idDeviceIndigitall": "<device_id_used_by_InDigital_apis_not_checked_can_be_anything>",
        "lang": "en",
        "password": "<password>",
        "user": "<username>",
        "uuid": "<unique_installation_id_which_identifies_current_device>" 
    }
}

Response

{
  "data": {
    "xSLoginToken": {
      "__typename": "XSLoginToken",
      "res": "OK",
      "msg": "User validated successfully",
      "hash": null,
      "refreshToken": null,
      "legals": true,
      "changePassword": false,
      "needDeviceAuthorization": true,
      "mainUser": false
    }
  }
}

Request 2 - mkValidateDevice

Headers -

auth : {"user":"<username>","id":"OWA_______________<username>_______________<timestamp>","country":"GB","lang":"en","callby":"OWA_10","hash":"","refreshToken":""}

Body

{
    "operationName": "mkValidateDevice",
    "query": "mutation mkValidateDevice($idDevice: String, $idDeviceIndigitall: String, $uuid: String, $deviceName: String, $deviceBrand: String, $deviceOsVersion: String, $deviceVersion: String) {\n  xSValidateDevice(idDevice: $idDevice, idDeviceIndigitall: $idDeviceIndigitall, uuid: $uuid, deviceName: $deviceName, deviceBrand: $deviceBrand, deviceOsVersion: $deviceOsVersion, deviceVersion: $deviceVersion) {\n    res\n    msg\n    hash\n    refreshToken\n    legals\n  }\n}\n",
    "variables": {
        "deviceBrand": "google",
        "deviceName": "Android SDK built for x86",
        "deviceOsVersion": "10",
        "deviceVersion": "10.64.0",
        "idDevice": "<device_id_used_by_firebase_push_notification_not_check_can_be_anything>",
         "uuid": "<unique_installation_id_which_identifies_current_device" 
    }
}

Response

{
  "errors": [
    {
      "message": "Unauthorized",
      "name": "SecurityError",
      "time_thrown": "2022-08-31T20:04:57.326Z",
      "data": {
        "auth-type": "OTP",
        "auth-code": "10001",
        "auth-phones": [
          {
            "id": 0,
            "phone": "********155"
          },
          {
            "id": 1,
            "phone": "********627"
          }
        ],
        "auth-otp-hash": "<otp_hash>"
      },
      "path": [
        "xSValidateDevice"
      ]
    }
  ],
  "data": {
    "xSValidateDevice": null
  }
}

Request 3 - mkLoginToken

Headers -

auth : {"user":"<username>","id":"OWA_______________<username>_______________<timestamp>","country":"GB","lang":"en","callby":"OWA_10","hash":"","refreshToken":""}

Body

{
    "operationName": "mkSendOTP",
    "query": "mutation mkSendOTP($recordId: Int!, $otpHash: String!) {\n  xSSendOtp(recordId: $recordId, otpHash: $otpHash) {\n    res\n    msg\n  }\n}\n",
    "variables": {
        "otpHash": "<otp_hash>",
        "recordId": <selected_phone_id>
    }
}

Response

{
  "data": {
    "xSSendOtp": {
      "res": "OK",
      "msg": "Request processed correctly"
    }
  }
}

Request 4 - mkValidateDevice

Headers -

auth : {"user":"<username>","id":"OWA_______________<username>_______________<timestamp>","country":"GB","lang":"en","callby":"OWA_10","hash":"","refreshToken":""}
security : {"token":"<sms_verification_code>","type":"OTP","otpHash":"<otp_hash>"}

Body

<Same as Request 2>

Response

{
  "data": {
    "xSValidateDevice": {
      "res": "OK",
      "msg": "Request processed correctly",
      "hash": null,
      "refreshToken": null,
      "legals": null
    }
  }
}

Request 5 - mkLoginToken

Headers : None required

Body

<Same as Request 1>

Response

{
  "data": {
    "xSLoginToken": {
      "__typename": "XSLoginToken",
      "res": "OK",
      "msg": "User validated successfully",
      "hash":  <login_token_hash>,
      "refreshToken": <refresh_token>,
      "legals": true,
      "changePassword": false,
      "needDeviceAuthorization": false,
      "mainUser": false
    }
  }
}

After this the current device is won't need verification again.
Notes : Device Brand and Device Name can be anything, but not tested.

Hope this helps and the integration can be improved. Let me know if you need more help.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 3

Hey, progress report. I made all the code changes to incorporate all the necessary headers and secrets that the API required.

I'm making process with the API but because I have to test with my personal account I don't want to upset the API.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 3

Interesting. I will test this flow as you described. The idDeviceIndigtall is for the marketing team https://indigitall.com/ but I thought the idDevice it was important.

This is how I create the UUID,

just for your information.

Thanks for the help!

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024 2

Dear @javiermartingonzalez

It is very simple. You only need to create an automation like below (please, remember to update "<Securitas alarm entity name>" by your Security alarm entity name):

image

That automation will be execute each 5 minutes and the home assitant alarm status will be update from the Securitas status value.

On the other hand, for sure if you would like to execute that action in other automations or scripts, you could create a script with the automation action and call it from wherever you want.

Regards
Javier.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 2

Yo estoy mirando la integración con el código fuente de la última versión. Dadme un poco de tiempo.

from securitas-direct-new-api.

bcampru avatar bcampru commented on August 11, 2024 2

Hey everyone, let me summarize my efforts so far with the new device authentication that Securitas started enforcing recently. As you may know now is mandatory to verify the device you are calling the API in order to have an open session. That is what making the HA integration not working, or not making it functional if we have to login every 20 minutes with an SMS code.

Where we are right now?

There is a new branch otp_challange that contains all my efforts to make this thing works. There is a API call validate_device that as the name says validate that the device is authorized. I have the SMS flow working in HA. You can select one of your phone numbers, receive an SMS and then call this API again. But for whatever reason this is not working as expected. We should get this response in json.

{
    "data": {
        "xSValidateDevice": {
            "res": "OK",
            "msg": "Petición procesada correctamente",
            "hash": null,
            "refreshToken": null,
            "legals": null
        }
    }
}

And then make another request to login and we should get something like that:

{
    "data": {
        "xSLoginToken": {
            "__typename": "XSLoginToken",
            "res": "OK",
            "msg": "Usuario validado correctamente",
            "hash": "",
            "refreshToken": "",
            "legals": true,
            "changePassword": false,
            "needDeviceAuthorization": false,
            "mainUser": true
        }
    }
}

In the hash and the refreshToken we should get a secure web token.

But no, what we get is a hash token in the device_call making the second call to login with the property needDeviceAuthorization set to true.

What is the heart of the issue?

Right now there is a idDevice property that identifies the device that looks like this:

idDevice=d7MwrBXGQF6ZjI7b4_hVgU:APA91bFg79TE0qo3z72dWJ2iJf_swmUie777KgKSLod3qDMS5UxDh9YO5Rrd0n2bDtk2v5G2Wb9zUAoR-ES_aozdVDZTfOKCgloH6D-nvgQO2YY_ToLc6cb7EBKsdPWosFiea6oYsQZb

But I have no idea how to create id like this myself. It doesn’t look like a encoded base 64 string and it looks like a encrypted token. That is what is preventing us to successfully validate the device.

What have I tried?

I have this old android device where I installed a trusted certificate CA so I can monitor all the traffic in the device from all apps. With that I was able to fully capture all the traffic of the securitas app. I uninstall the app and reinstall a couple of time to see how the flow works. Once the device is validated, even if you uninstall the app and reinstall you don’t need to validate again. So the validate_device operation somehow persist over time.

What am I asking?

Help. I don’t know if someone have more experience with this kind of API or put another perspective that can me it works. I offer the possibility of sharing the logs without my personal information or help someone to capture the traffic on their devices.

Hello, I've tried to reverse engineer the verisure app, what i've discovered is that they are saving the deviceId param inside a sharedPreferences (com.indigitall.prefs), the key name is com.indigitall.prefs.deviceId.

For getting and setting this variable they are using the class yb/c (you can find this reverse engineering the apk), in my opinion the important method of this class is the one named u:

public static void u(Context paramContext, String paramString) {
    if (a.t(paramString)) {
      SharedPreferences.Editor editor = h(paramContext);
      if (editor != null)
        editor.putString("com.indigitall.prefs.deviceId", paramString).apply(); 
    } 
}

I've tried to track where the paramString variable is created and it comes from the class r8/b. From this point it starts to get difficult to track the origin and I've stopped here, the next step might be trying to debug the app and see what's going on.

Hopefully this will be helpful.

from securitas-direct-new-api.

s3v avatar s3v commented on August 11, 2024 1

I had no success in using release V1.3.0.0 for logging in to the french graphql endpoint https://customers.securitasdirect.fr/owa-api/graphql. Maybe not all countries are using the same version on the graphql end.

I noticed that the ApiManager._generate_id() is returning timestamps that are too long versus those that they use on the FR endpoint. But even after modifying those to a maximum of 14 characters (eg id ending on _______20226172028859), i keep getting a commanderror as below:

CommandError: 400, message='Invalid header value char', url=URL('https://customers.securitasdirect.fr/owa-api/graphql')

After adding an "auth" and an "installation" header value of {} in the login request, the request passes successfully again. I'm not sure if you are seeing the same behavior on your graphql endpoint?

Edit: it seems that they are also expecting those on the ApiManager.check_general_status() request.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 1

Thanks for the new version.

I am checking and it seems it has still some issue in order to operarte with Securitas Web API. Even though it is able to loggin, it seems it has some issue when you try to operate with: disarm, armed total, ... I got always the same warning messages when I try to execute any operation: 2022-06-17 09:04:54 ERROR (MainThread) [custom_components.securitas.securitas_direct_new_api.apimanager] Tu Alarma está gestionando una solicitud anterior. Por favor, espera 90 segundos antes de realizar otra petición (5 min si es una petición de imagen). However if I try to operate from Website they work. Let me know how I can help you if you need further information.

Thanks in advance and regards. Javier

About this issue, regarless if you do that on the web app, mobile app or throught the API the result is the same. When the error is in Spanish (Tu Alarma está gestionando una solicitud anterior. Por favor, espera 90 segundos antes de realizar otra petición (5 min si es una petición de imagen), that means that your alarm still processing a previous request and it can't make any new requests. That is something that something it happens depending on the network coverage of the central panel of your alarm. the only thing that we can do is wait.

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024 1

Desde hace 2 días ha dejado de funcionarme la integración, me aparece como "no disponible". Actualicé a tu última versión hace 5 días e iba bien, pero desde el día 21 por la tarde dejó de funcionar. El error que me da es el siguiente: Este error se originó a partir de una integración personalizada.

Logger: custom_components.securitas.securitas_direct_new_api.apimanager Source: custom_components/securitas/securitas_direct_new_api/apimanager.py:106 Integration: Securitas Direct (documentation, issues) First occurred: 22 de junio de 2022, 17:55:30 (1 occurrences) Last logged: 22 de junio de 2022, 17:55:30

Unauthorized

A mi me paso exactamente lo mismo desde el dia que indicas, hoy he desinstalado toda la integracion e reiniciado he vuelto a instalarla desde cero y ahora esta funcionando, puedes probar.

from securitas-direct-new-api.

DNKROZ avatar DNKROZ commented on August 11, 2024 1

A mi me paso exactamente lo mismo desde el dia que indicas, hoy he desinstalado toda la integracion e reiniciado he vuelto a instalarla desde cero y ahora esta funcionando, puedes probar.

Hoy intenté esto sin mucha esperanza pero curiosamente funcionó, la web me pide el doble factor, pero ahora la integración ha vuelto a funcionar tras borrarlo todo y volver a instalar... pero ni idea de por qué.

I tried this today not hoping for it to work but oddly enough, it worked!, website still asks me for 2FA, but the integration is working again after purging everything and reinstalling... don't have clue about why though.

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024 1

Desde hace 2 días ha dejado de funcionarme la integración, me aparece como "no disponible". Actualicé a tu última versión hace 5 días e iba bien, pero desde el día 21 por la tarde dejó de funcionar. El error que me da es el siguiente: Este error se originó a partir de una integración personalizada.
Registrador: custom_components.securitas.securitas_direct_new_api.apimanager Fuente: custom_components/securitas/securitas_direct_new_api/apimanager.py:106 Integración: Securitas Direct (documentación, problemas) Ocurrió por primera vez: 22 de junio de 2022, 17:55:30 (1 ocurrencias) Última logueado: 22 de junio de 2022, 17:55:30
No autorizado

A mi me paso exactamente lo mismo desde el dia que indica, hoy he desinstalado toda la integracion y reiniciado he vuelto a instalarla desde cero y ahora esta funcionando, puedes probar.

A mi me pasó lo mismo y él intentó esto mismo de reinstalar. He desinstalado la que tenía, reiniciado, y cuando voy a instalar, sólo me aparece la integración de "Securitas Direct" (Antes también aparecía una llamada "Securitas") y cuando intento instalarla, me pide usuario y contraseña y me da error "Unknown Se produjo un error"

Eso me paso a mi tambien, asegurate de que no quede nada, desinstalala de HACS y si tienes Shamba asegurate que en la carpeta custom components tampoco haya nada de securitas, reinicia antes de instalar e intentalo de nuevo y por supuesto asegurate que usuario y contraseña sea la de tu alarma.
Suerte.

from securitas-direct-new-api.

javiermartingonzalez avatar javiermartingonzalez commented on August 11, 2024 1

Yo ni he reinstalado, ayer no funcionaba... y hoy de repente está funcionando.

A ver hasta cuándo dura, web sigue pidiendo 2FA

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024 1

Se sabe algo nuevo de Securitas?

from securitas-direct-new-api.

rlcobos2 avatar rlcobos2 commented on August 11, 2024 1

I don't know what they've done but I'm afraid it's a HA thing throughout the day Securitas, ZHA and Sonoff Lan have stopped working What a mess

Sorry to the group, because offtopic response.

@otistarda, i have the same problems,

      ZHA ( at the end unique real solution was delete zigbee.db and reassign each device to the network ), hard job, but, at least it's solved and i can forgot it.

      Sonoff ( suppouse you are using alexxit integration like me ), they have a new update fixing the problem

      Securitas direct. Still waiting to @guerrerotook availability to fix this new change in securitas part.

Sorry for the offtopic.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 1

Te respondo en español y en inglés después!

Español
Pues por ahora la integración funciona con el tema de la autenticación de SMS y tengo el config flow configurado para que te vayan saliendo unas ventanas en el HA que te piden el móvil que tienes registrado y todo eso. Hasta ahí bien, pero el problema fundamental es que no se que API utilizan para refrescar el token.

Cuando te auténticas te dan un token para iniciar sesióny otra cosa llamada refreshToken, este segundo token se utiliza para volver a pedir un token sin tener que volver a iniciar sesión. Es lo que utilizan las aplicaciones móviles para iniciar sesión. El problema es que la version web de la aplicación no expone esa API y no se como se hace. Nuestra opción sería ver si podemos bajarnos el APK de la version de Android para ver que html/javascript se descarga en esa version e intentar solucionarlo. Pero siendo sinceros la cosa está complicada.

La unica alternativa es que, cada 30 minutos la integración dejaría de funcionar y te pediría iniciar sesión otra vez. Cosa que es imposible.

Si alguien sabe cómo bajarse el APK de la app y descompilarlo sería ideal.

English version.
The current status of the ignoration is that we are able to login and request an SMS for the 2FA and it works. The integration with HA is also done and inside the config flow you are being presented with a UI where you can select your phone number and input the SMS code to authenticate.

Given said that, the issue right now is that as part of the login process there is two tokens, the authentication token, and the refresh token. The refresh token is being used to refresh the authentication token for mobile applications. But on the web version of the app this API and the javascript code are not being exposed. My only hope is to download the Android APK and see how the version for mobile includes this API and we can use it also to refresh the token.

The only possible alternative right now is to manually login every 30 minutes with the SMS challenge, something that is super annoying.

If someone knows how to download the APK and decompile would be fantastic.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 1

Hello @guerrerotook,

To begin with, thank you for having so much trouble with this.

I was looking into the web requests in the browser inspector and something caught my attention:

  • There is this method call "mkValidateDevice" which first returns "Unauthorized" and only after the OTP is correctly sent will return the hash and refreshToken.

  • The webapp always requires a new OTP on every login ands sends no arguments in mkValidateDevice except for the OTP in the security header of the 2nd call

  • This method however can receive a few arguments going by the signature in the request:

    • $idDevice: String, $idDeviceIndigitall: String, $uuid: String, $deviceName: String, $deviceBrand: String, $deviceOsVersion: String, $deviceVersion: String

You may have already tried this, but I wonder if the "trusted device" is stored server-side, and if so, if we can make up some device by filling those fields with some randomly generated constant data it might return a valid session afterwards in the first mkValidateDevice efectively skipping the need for the OTP.

I did try to pull your branch to try it but was unable to get it running on my HA for some reason.

What you described is correct. The missing part was the RefreshLogin operation.

They don't send the code for the refresh operation in the javascript code for the web app.

from securitas-direct-new-api.

vipial1 avatar vipial1 commented on August 11, 2024 1

Buenas noticias!! Ya he conseguido capturar el tráfico TLS de la app de android y ya tengo todo lo necesario. Además esta semana empiezo dos semanas de vacaciones y me voy a poner a tope con eso.

Voy a cambiar bastantes cosas y simular que es un dispositivo Android en vez de la web que es ahora.

Eso es genial! Asi quizás tambien se puede solicitar imágenes de los fotodetectores! Te puedo echar una mano si lo necesitas.

from securitas-direct-new-api.

vipial1 avatar vipial1 commented on August 11, 2024 1

Hi @guerrerotook, can we test the OTP branch?

Not yet, I'm able to get the authentication token but struggled to setup the config flow in HA.

In the future I will ask you guys to test this branch before merging back to master.

hey @guerrerotook
Take a look to this: vipial1@531f476

It is not nice, but working.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 1

Hey everyone, let me summarize my efforts so far with the new device authentication that Securitas started enforcing recently.
As you may know now is mandatory to verify the device you are calling the API in order to have an open session. That is what making the HA integration not working, or not making it functional if we have to login every 20 minutes with an SMS code.

Where we are right now?

There is a new branch otp_challange that contains all my efforts to make this thing works. There is a API call validate_device that as the name says validate that the device is authorized. I have the SMS flow working in HA. You can select one of your phone numbers, receive an SMS and then call this API again. But for whatever reason this is not working as expected.
We should get this response in json.

{
    "data": {
        "xSValidateDevice": {
            "res": "OK",
            "msg": "Petición procesada correctamente",
            "hash": null,
            "refreshToken": null,
            "legals": null
        }
    }
}

And then make another request to login and we should get something like that:

{
    "data": {
        "xSLoginToken": {
            "__typename": "XSLoginToken",
            "res": "OK",
            "msg": "Usuario validado correctamente",
            "hash": "",
            "refreshToken": "",
            "legals": true,
            "changePassword": false,
            "needDeviceAuthorization": false,
            "mainUser": true
        }
    }
}

In the hash and the refreshToken we should get a secure web token.

But no, what we get is a hash token in the device_call making the second call to login with the property needDeviceAuthorization set to true.

What is the heart of the issue?

Right now there is a idDevice property that identifies the device that looks like this:

idDevice=d7MwrBXGQF6ZjI7b4_hVgU:APA91bFg79TE0qo3z72dWJ2iJf_swmUie777KgKSLod3qDMS5UxDh9YO5Rrd0n2bDtk2v5G2Wb9zUAoR-ES_aozdVDZTfOKCgloH6D-nvgQO2YY_ToLc6cb7EBKsdPWosFiea6oYsQZb

But I have no idea how to create id like this myself. It doesn’t look like a encoded base 64 string and it looks like a encrypted token.
That is what is preventing us to successfully validate the device.

What have I tried?

I have this old android device where I installed a trusted certificate CA so I can monitor all the traffic in the device from all apps. With that I was able to fully capture all the traffic of the securitas app.
I uninstall the app and reinstall a couple of time to see how the flow works. Once the device is validated, even if you uninstall the app and reinstall you don’t need to validate again. So the validate_device operation somehow persist over time.

What am I asking?

Help. I don’t know if someone have more experience with this kind of API or put another perspective that can me it works. I offer the possibility of sharing the logs without my personal information or help someone to capture the traffic on their devices.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024 1

Hey, @shantur thank very much for the comment. You are right this is the right flow and this flow is already implemented in the otp_challenge branch where I have been working.

The problem came when you calling a second time the mkValidateDevice and I don't get a valid token and refresh token. So the device is not validated but the login succeed. Meaning that for about 30 minutes you can call the api but then you need to do the SMS code again. Something that is not acceptable.

I explain that a little bit up in the post, here is the link. #57 (comment)

The problem is that this idDevice I don't know how to generate in a way that let me validate the device.

Happy to show you my setup, I clone this repository, https://github.com/guerrerotook/home-assistant open the VSCode Container in there and in the component/securitas-direct is a submodule to this repo, so you can work and experiment there.

from securitas-direct-new-api.

shantur avatar shantur commented on August 11, 2024 1

@guerrerotook : I think the flow is a bit different.
As I explained the idDevice is not being used for our purposes, I examined the Android app and the requests it makes. I tested with idDevice just being set to "bla" and it works. idDevice is just used for Firebase push notifications and it comes from Firebase Cloud Messaging,
idDevice and idDeviceIndigitall can be totally ignored and just set to anything.
uuid is the one that identifies our device and should be kept same in all the requests.

I couldn't get the custom component working with latest home-assistant dev environment and need to look into it but one difference that I spotted in your version is that you have "OWP_10" in callby and id fields where as I have "OWA_10". This could be the factor as OWP could mean OW Portal and OWA could be OW App.

I won't get time to try your version of home-assistant till later this evening, if you have this working would you mind testing the OWA change?

Thanks

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024

Thanks for the information. I can confim it.
I appreciate your work and look forward to hearing from you soon.

from securitas-direct-new-api.

albertruizalonso avatar albertruizalonso commented on August 11, 2024

I was going crazy!
Mistakes with the integration of "Securitas"
It doesn't work right now.
When I enter the "Securitas" website, I also had a password error, forcing me to change it.
I guess that must be the same problem¿?😫😫

from securitas-direct-new-api.

alnavasa avatar alnavasa commented on August 11, 2024

+1

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024

Solved on latest release. https://github.com/guerrerotook/securitas-direct-new-api/releases/tag/V1.3.0.0

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024

Thanks for the new version.

I am checking and it seems it has still some issue in order to operarte with Securitas Web API.
Even though it is able to loggin, it seems it has some issue when you try to operate with: disarm, armed total, ...
I got always the same warning messages when I try to execute any operation:
2022-06-17 09:04:54 ERROR (MainThread) [custom_components.securitas.securitas_direct_new_api.apimanager] Tu Alarma está gestionando una solicitud anterior. Por favor, espera 90 segundos antes de realizar otra petición (5 min si es una petición de imagen).
However if I try to operate from Website they work.
Let me know how I can help you if you need further information.

Thanks in advance and regards.
Javier

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024

I am doing another test with check_alarm_panel paramenter false.
I will let you know the result.

Regards
Javier.

from securitas-direct-new-api.

albertruizalonso avatar albertruizalonso commented on August 11, 2024

You're right, This night, I tried it and it apparently disconnected properly in the home assistant panel, but really, it was connected.
Imagine the fright when it started ring at 2 am...🤣🤣🤣🤣
Still, thank you very much. Really, you're a crack! @guerrerotook

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024

First, thanks again for your altruist work.

I just finished my test with check_alarm_panel false.
Now the issue is each time alarm operation execution is lanched, home assitant alarm status doesn't change. So I have added a script in order to check the alarm status afterward any alamar operation waiting 5 seconds before checking (to avoid a possible saturation). On that way it seems working, however it is very unstable and takes much time each execution.

I guess there will be another way to solve this in the code.

Let me know if you need further information or if you want me to do another test.

Regards
Javier.

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024

Deeping more in my reshearch.

After doing several tests with the paramenter check_alarm_panel with value false, I reached a conclusion.

The issue is that each time an alarm operation is executed from Home Assistant, it doesn't updatethe status alarm afterward execution.

I had understood that paramenter check_alarm_panel was only involved when you carried out directly some operation from the Securitas alarm panel (key, remote control, and so on), but doesn't when the operation was direclty lanched from Home Assistant. Please, let me know if I am wrong.

From the other hand, in order to solve the issue when you operate directly on the Securitas panel, I have added a script that check in Securitas side and update side the actully alarm status in Home Assistant each 5 minutes.

I hope having been usefull.

Regards.
Javier.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024

Let me take a look at this today. Thanks everyone for the comments and feedback.

from securitas-direct-new-api.

javiermartingonzalez avatar javiermartingonzalez commented on August 11, 2024

Same here than Javier. Sometimes, HA not updating status after alarm change.

Checking Verisure app, 95% of times it's updated there so it automatically updates in HA in about 10 minutes. The other 5%, Verisure is not getting last status (showing disconnected when is recently connected), so I need to press Check status on Verisure app and then 10 minutes later, HA is updated.

@Javvaz Can you share the script with us to trigger that forcing get status without accessing Verisure app?

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024

About this topic, there are two separate ways of checking the status of the alarm in the code.

  • Check Genral Status, goes to the server and ask securitas direct was is the last server alarm status that they have on record. That is a quick, fast and non invasive request to the alarm control panel. (you need to set check_alarm to false)
  • Check Alarm: this method will goes to your alarm control panel and check the status of your alarm, showing in your users auditing and making use of the resources of the panel. Takes much more time, and during that time you can't arm or disarm you alarm.

So I add this flag in the configuration that basically only check the status of the alarm (first method) because it's fast and you don't need to make a request every 20 minutes.

Coming back to your script, you can set the check_alarm flag in the configuration to true and it will check your alarm panel directly every 20 minutes.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024

I had no success in using release V1.3.0.0 for logging in to the french graphql endpoint https://customers.securitasdirect.fr/owa-api/graphql. Maybe not all countries are using the same version on the graphql end.

I noticed that the ApiManager._generate_id() is returning timestamps that are too long versus those that they use on the FR endpoint. But even after modifying those to a maximum of 14 characters (eg id ending on _______20226172028859), i keep getting a commanderror as below:

CommandError: 400, message='Invalid header value char', url=URL('https://customers.securitasdirect.fr/owa-api/graphql')

After adding an "auth" and an "installation" header value of {} in the login request, the request passes successfully again. I'm not sure if you are seeing the same behavior on your graphql endpoint?

Edit: it seems that they are also expecting those on the ApiManager.check_general_status() request.

Thanks for the comment @s3v, you raised a very important issue that maybe not all the country are using the same version of the graph api on the backend. I'm using the service from Spain and you from France. I think that I need to rethink how I can handle all of these multiple version of the server side API so I can have these operations depending on the configuration of your country.

Given said that, I can debug the API from my side because I have access to the API in Spain, but I'm going to need your help in order to do the same for the Frend and other API versions as well.

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024

Thanks for the information and your work. I appreciate it.

The issue now with setting check_alarm to false is the home assistant alarm status doesn't inmediatelly change after executing any alarm operation. However that is something was working fine in the previous version.

Regards.
Javier.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024

Thanks for the information and your work. I appreciate it.

The issue now with setting check_alarm to false is the home assistant alarm status doesn't inmediatelly change after executing any alarm operation. However that is something was working fine in the previous version.

Regards. Javier.

That is really weird, because when I do a arm or disarm operation on the API, afterwards it always returns the next status for the alarm. Like in my case, when you arm or disarm, you can see Arming flashing in the UI and the whatever status you can set the alarm to.

My recomendation would be that you increase the logger detail for the component and see how it goes.

logger:
  default: error
  logs:
    custom_components.securitas: debug

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024

To be honest I am not sure what is happening.

WIth check_alarm_panel true I always get the same messages "Tu Alarma está gestionando una solicitud anterior. Por favor, espera 90 segundos antes de realizar otra petición (5 min si es una petición de imagen)", however if I execute the same operation in Securitas Website works fine.

With check_alarm_panel false. Everything works fine except the home asistant alarm status is not update each time I execute any operation, I have to force the update through out the script.

I wonder if it is related to that I have the Securitas Verisure alarm previous to the last one.

Thanks for your help.

Javier.

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024

Dear @guerrerotook

Thanks again for your work and collaboration.

I just checked my Securitas account in the Securitas Website and now they are applying the 2FA, so when you are authenticating in the WebSite they ask you the phone number in order to send you a code before asking you the same one.

Now your integration is failing with the below message:
2022-06-21 17:49:53 ERROR (MainThread) [custom_components.securitas.securitas_direct_new_api.apimanager] Unauthorized

I checked with true and false in the check_alarm_panel parameter with the same error (it was clear that was not involved in that, but ... I tried it just in case)

I am not sure how you are thinking to solve it.

Regards.

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024

Dear @guerrerotook Luis Guerrero Guirado FTE

Thanks again for your work and collaboration.

I just checked my Securitas account in the Securitas Website and now they are applying the 2FA, so when you are authenticating in the WebSite they ask you the phone number in order to send you a code before asking you the same one.

Now your integration is failing with the below message: 2022-06-21 17:49:53 ERROR (MainThread) [custom_components.securitas.securitas_direct_new_api.apimanager] Unauthorized

I checked with true and false in the check_alarm_panel parameter with the same error (it was clear that was not involved in that, but ... I tried it just in case)

I am not sure how you are thinking to solve it.

Regards.

That is a tought one, because I need to see how the handle the second factor of authentication to integrate that in the code. But for my account still not asking for it.

from securitas-direct-new-api.

jcorreaes avatar jcorreaes commented on August 11, 2024

Same issue here.
I had 2FA activated yesterday on the web access (not in the app yet). The integration is not working anymore.
I'm afraid no way to deactivate it. They ask for a 6 digit pin sent to your mobile phone.
It's not going to be easy to handle.

I'm from Spain, so @guerrerotook have you tried from Securitas app or webapp?

from securitas-direct-new-api.

javiermartingonzalez avatar javiermartingonzalez commented on August 11, 2024

Same here, in Spain and 2FA in web from today. Mobile app not asking for it.

from securitas-direct-new-api.

manolodh avatar manolodh commented on August 11, 2024

Desde hace 2 días ha dejado de funcionarme la integración, me aparece como "no disponible". Actualicé a tu última versión hace 5 días e iba bien, pero desde el día 21 por la tarde dejó de funcionar. El error que me da es el siguiente:
Este error se originó a partir de una integración personalizada.

Logger: custom_components.securitas.securitas_direct_new_api.apimanager
Source: custom_components/securitas/securitas_direct_new_api/apimanager.py:106
Integration: Securitas Direct (documentation, issues)
First occurred: 22 de junio de 2022, 17:55:30 (1 occurrences)
Last logged: 22 de junio de 2022, 17:55:30

Unauthorized

from securitas-direct-new-api.

Fireful avatar Fireful commented on August 11, 2024

Desde hace 2 días ha dejado de funcionarme la integración, me aparece como "no disponible". Actualicé a tu última versión hace 5 días e iba bien, pero desde el día 21 por la tarde dejó de funcionar. El error que me da es el siguiente: Este error se originó a partir de una integración personalizada.
Logger: custom_components.securitas.securitas_direct_new_api.apimanager Source: custom_components/securitas/securitas_direct_new_api/apimanager.py:106 Integration: Securitas Direct (documentation, issues) First occurred: 22 de junio de 2022, 17:55:30 (1 occurrences) Last logged: 22 de junio de 2022, 17:55:30
Unauthorized

A mi me paso exactamente lo mismo desde el dia que indicas, hoy he desinstalado toda la integracion e reiniciado he vuelto a instalarla desde cero y ahora esta funcionando, puedes probar.

A mi me pasó lo mismo y he intentado esto mismo de reinstalar. He desinstalado la que tenía, reiniciado, y cuando voy a instalar, sólo me aparece la integración de "Securitas Direct" (Antes también aparecía una llamada "Securitas") y cuando intento instalarla, me pide usuario y contraseña y me da error "Unknown error occurred"

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024

Ahora falla otra vez incluso con intervalo de 5 minutos a la hora de refresecar el token.

Gracias por tu trabajo y saludos.

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024

I don't know what they've done but I'm afraid it's a HA thing throughout the day Securitas, ZHA and Sonoff Lan have stopped working
What a mess

from securitas-direct-new-api.

jsole avatar jsole commented on August 11, 2024

A mi también me está fallando desde hace unas horas... ¿@guerrerotook has conseguido averiguar que están cambiando?

Un saludo y gracias por todo!

from securitas-direct-new-api.

javiermartingonzalez avatar javiermartingonzalez commented on August 11, 2024

It seems to be something with HA new release. It was working but after updating, Securitas and Switchbot stop working

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024

Como vamos @guerrerotomo es solo un mensaje de animo :)

from securitas-direct-new-api.

siom7 avatar siom7 commented on August 11, 2024

Hello @guerrerotook ! Thanks for your time and your hard work. I think about Bluestack (Android emulator on Windows) to download Verisure Android APP but I don't know if it can help you it's just an idea and maybe you already try it.

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024

We'll keep an eye out, I'm sure you'll get it.
Thanks for taking so much trouble.

from securitas-direct-new-api.

jsole avatar jsole commented on August 11, 2024

Maybe you can use wireshark to listen to the connections the app is doing and get some information, at least the url it's calling.
The info will be encrypted due to the https, but maybe you can get something interesting.

from securitas-direct-new-api.

joaoestevinho avatar joaoestevinho commented on August 11, 2024

Hello @guerrerotook,

To begin with, thank you for having so much trouble with this.

I was looking into the web requests in the browser inspector and something caught my attention:

  • There is this method call "mkValidateDevice" which first returns "Unauthorized" and only after the OTP is correctly sent will return the hash and refreshToken.
  • The webapp always requires a new OTP on every login ands sends no arguments in mkValidateDevice except for the OTP in the security header of the 2nd call
  • This method however can receive a few arguments going by the signature in the request:
    • $idDevice: String, $idDeviceIndigitall: String, $uuid: String, $deviceName: String, $deviceBrand: String, $deviceOsVersion: String, $deviceVersion: String

You may have already tried this, but I wonder if the "trusted device" is stored server-side, and if so, if we can make up some device by filling those fields with some randomly generated constant data it might return a valid session afterwards in the first mkValidateDevice efectively skipping the need for the OTP.

I did try to pull your branch to try it but was unable to get it running on my HA for some reason.

from securitas-direct-new-api.

pmcastro10 avatar pmcastro10 commented on August 11, 2024

Animo y gracias por tus esfuerzos... pedir ayuda con lo de la app a Securitas ni de broma, no?...

Saludos

from securitas-direct-new-api.

jmatiasGH avatar jmatiasGH commented on August 11, 2024

Ánimo Guerrerotook! Gracias por tus grandes esfuerzos y esta gran integración. No tengo mucho tiempo pero si puedo de alguna forma colaborar de algún modo, aunque sea haciendo pruebas me dices.

from securitas-direct-new-api.

rlcobos2 avatar rlcobos2 commented on August 11, 2024

Thanks for your effort.

This is a nice project!!!

Ánimo!!!

from securitas-direct-new-api.

alnavasa avatar alnavasa commented on August 11, 2024

Thanks a lot @guerrerotook , there's a lot of people that would benefit from your hard work! thanks!

from securitas-direct-new-api.

Lugib avatar Lugib commented on August 11, 2024

Buenas noticias!! Ya he conseguido capturar el tráfico TLS de la app de android y ya tengo todo lo necesario. Además esta semana empiezo dos semanas de vacaciones y me voy a poner a tope con eso.

Voy a cambiar bastantes cosas y simular que es un dispositivo Android en vez de la web que es ahora.

Good news everyone, I successfully capture the TLS traffic in the Android app and now I have everything I need to continue. These next two weeks I will on vacations and I will have a lot of free time.

There are going to be a lot of changes in the code because I'm going to simulate that I'm a Android device instead of the web app.

Great news! Buenas noticias compi!
Hopefully new version will fix integration problems.
If you need any tester let me know I can help :-)

Cheers!
Saludos y Gracias!

from securitas-direct-new-api.

andr1u avatar andr1u commented on August 11, 2024

Thank you again!

I uninstalled the addon because was not working, reinstalling will not create the alarm entity again. Hope this fix like May's water! 😁

from securitas-direct-new-api.

Lugib avatar Lugib commented on August 11, 2024

Any news so far @guerrerotook ?

from securitas-direct-new-api.

soth78 avatar soth78 commented on August 11, 2024

If u need a tester @guerrerotook, let me know!

from securitas-direct-new-api.

andr1u avatar andr1u commented on August 11, 2024

Hey, progress report. I made all the code changes to incorporate all the necessary headers and secrets that the API required.

I'm making process with the API but because I have to test with my personal account I don't want to upset the API.

Hi @guerrerotook, can we test the OTP branch?

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024

Hi @guerrerotook, can we test the OTP branch?

Not yet, I'm able to get the authentication token but struggled to setup the config flow in HA.

In the future I will ask you guys to test this branch before merging back to master.

from securitas-direct-new-api.

andr1u avatar andr1u commented on August 11, 2024

Hi @guerrerotook, can we test the OTP branch?

Not yet, I'm able to get the authentication token but struggled to setup the config flow in HA.

In the future I will ask you guys to test this branch before merging back to master.

OK. Thank you again for your work!

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024

Hola a todos, permítanme resumir mis esfuerzos hasta ahora con la nueva autenticación de dispositivos que Securitas comenzó a implementar recientemente. Como sabrá, ahora es obligatorio verificar el dispositivo al que está llamando la API para tener una sesión abierta. Eso es lo que hace que la integración HA no funcione, o que no funcione si tenemos que iniciar sesión cada 20 minutos con un código SMS.

¿Dónde estamos ahora?

Hay una nueva rama otp_challange que contiene todos mis esfuerzos para hacer que esto funcione. Hay una llamada a la API validate_device que, como dice el nombre, valida que el dispositivo está autorizado. Tengo el flujo de SMS trabajando en HA. Puede seleccionar uno de sus números de teléfono, recibir un SMS y luego volver a llamar a esta API. Pero por alguna razón esto no funciona como se esperaba. Deberíamos obtener esta respuesta en json.

{
    "data": {
        "xSValidateDevice": {
            "res": "OK",
            "msg": "Petición procesada correctamente",
            "hash": null,
            "refreshToken": null,
            "legals": null
        }
    }
}

Y luego haga otra solicitud para iniciar sesión y deberíamos obtener algo como eso:

{
    "data": {
        "xSLoginToken": {
            "__typename": "XSLoginToken",
            "res": "OK",
            "msg": "Usuario validado correctamente",
            "hash": "",
            "refreshToken": "",
            "legals": true,
            "changePassword": false,
            "needDeviceAuthorization": false,
            "mainUser": true
        }
    }
}

En el hash y el refreshToken deberíamos obtener un token web seguro.

Pero no, lo que obtenemos es un token hash en device_call que realiza la segunda llamada para iniciar sesión con la propiedad needDeviceAuthorization establecida en verdadero.

¿Cuál es el corazón de la cuestión?

En este momento hay una propiedad idDevice que identifica el dispositivo que se ve así:

idDevice=d7MwrBXGQF6ZjI7b4_hVgU:APA91bFg79TE0qo3z72dWJ2iJf_swmUie777KgKSLod3qDMS5UxDh9YO5Rrd0n2bDtk2v5G2Wb9zUAoR-ES_aozdVDZTfOKCgloH6D-nvgQO2YY_ToLc6cb7EBKsdPWosFiea6oYsQZb

Pero no tengo idea de cómo crear una identificación como esta. No parece una cadena de base 64 codificada y parece un token cifrado. Eso es lo que nos impide validar con éxito el dispositivo.

¿Qué he probado?

Tengo este antiguo dispositivo Android en el que instalé un certificado CA de confianza para poder monitorear todo el tráfico en el dispositivo desde todas las aplicaciones. Con eso pude capturar completamente todo el tráfico de la aplicación securitas. Desinstalo la aplicación y la vuelvo a instalar un par de veces para ver cómo funciona el flujo. Una vez que se valida el dispositivo, incluso si desinstala la aplicación y la vuelve a instalar, no necesita validar nuevamente. Entonces, la operación del dispositivo de validación persiste de alguna manera en el tiempo.

¿Qué estoy preguntando?

Ayuda. No sé si alguien tiene más experiencia con este tipo de API o pone otra perspectiva que me puede funcionar. Ofrezco la posibilidad de compartir los logs sin mi información personal o ayudar a alguien a capturar el tráfico en sus dispositivos.

Gracias por tu esfuerzo, estoy seguro que al final lo conseguiras.

from securitas-direct-new-api.

DNKROZ avatar DNKROZ commented on August 11, 2024

Hello @guerrerotook , first and foremost thanks for all your work, appreciated.

As far as I understand (not my area of expertise) we don't have a way to generate a secure web token from scratch since this is something done by the app and we can only see the results of that but not the method used to generate it, but we can have (or maybe access) the stored device token since this should be stored locally or exchanged with the remote server during the validation process.

Maybe, as a workaround for the time being, we could include this device token during HA integration config flow as a user input value and use the token generated by our phone (or a cheap Android device) to be able to spoof that id info and disguise the custom integration as our own phone or device.

It's not ideal, this would be to be able to run all config flow from the custom integration (including SMS and device token generation) but should enable us to have "something" to work with.

Most probably you've already thought about this... but just my two cents :)
If you need something from me (I have several Android phones with several Android versions) or some testing just ask.

Regards.

from securitas-direct-new-api.

vipial1 avatar vipial1 commented on August 11, 2024

Hey everyone, let me summarize my efforts so far with the new device authentication that Securitas started enforcing recently. As you may know now is mandatory to verify the device you are calling the API in order to have an open session. That is what making the HA integration not working, or not making it functional if we have to login every 20 minutes with an SMS code.

Where we are right now?

There is a new branch otp_challange that contains all my efforts to make this thing works. There is a API call validate_device that as the name says validate that the device is authorized. I have the SMS flow working in HA. You can select one of your phone numbers, receive an SMS and then call this API again. But for whatever reason this is not working as expected. We should get this response in json.

{
    "data": {
        "xSValidateDevice": {
            "res": "OK",
            "msg": "Petición procesada correctamente",
            "hash": null,
            "refreshToken": null,
            "legals": null
        }
    }
}

And then make another request to login and we should get something like that:

{
    "data": {
        "xSLoginToken": {
            "__typename": "XSLoginToken",
            "res": "OK",
            "msg": "Usuario validado correctamente",
            "hash": "",
            "refreshToken": "",
            "legals": true,
            "changePassword": false,
            "needDeviceAuthorization": false,
            "mainUser": true
        }
    }
}

In the hash and the refreshToken we should get a secure web token.

But no, what we get is a hash token in the device_call making the second call to login with the property needDeviceAuthorization set to true.

What is the heart of the issue?

Right now there is a idDevice property that identifies the device that looks like this:

idDevice=d7MwrBXGQF6ZjI7b4_hVgU:APA91bFg79TE0qo3z72dWJ2iJf_swmUie777KgKSLod3qDMS5UxDh9YO5Rrd0n2bDtk2v5G2Wb9zUAoR-ES_aozdVDZTfOKCgloH6D-nvgQO2YY_ToLc6cb7EBKsdPWosFiea6oYsQZb

But I have no idea how to create id like this myself. It doesn’t look like a encoded base 64 string and it looks like a encrypted token. That is what is preventing us to successfully validate the device.

What have I tried?

I have this old android device where I installed a trusted certificate CA so I can monitor all the traffic in the device from all apps. With that I was able to fully capture all the traffic of the securitas app. I uninstall the app and reinstall a couple of time to see how the flow works. Once the device is validated, even if you uninstall the app and reinstall you don’t need to validate again. So the validate_device operation somehow persist over time.

What am I asking?

Help. I don’t know if someone have more experience with this kind of API or put another perspective that can me it works. I offer the possibility of sharing the logs without my personal information or help someone to capture the traffic on their devices.

hmmmm, interesting. Have you checked the HTTP response headers? Sometimes you find there some interesting values. If you can share with me some logs (maybe wireshark trace?), I would take a look.

from securitas-direct-new-api.

jmatiasGH avatar jmatiasGH commented on August 11, 2024

from securitas-direct-new-api.

soysnorre avatar soysnorre commented on August 11, 2024

Hey everyone, let me summarize my efforts so far with the new device authentication that Securitas started enforcing recently. As you may know now is mandatory to verify the device you are calling the API in order to have an open session. That is what making the HA integration not working, or not making it functional if we have to login every 20 minutes with an SMS code.

Where we are right now?

There is a new branch otp_challange that contains all my efforts to make this thing works. There is a API call validate_device that as the name says validate that the device is authorized. I have the SMS flow working in HA. You can select one of your phone numbers, receive an SMS and then call this API again. But for whatever reason this is not working as expected. We should get this response in json.

{
    "data": {
        "xSValidateDevice": {
            "res": "OK",
            "msg": "Petición procesada correctamente",
            "hash": null,
            "refreshToken": null,
            "legals": null
        }
    }
}

And then make another request to login and we should get something like that:

{
    "data": {
        "xSLoginToken": {
            "__typename": "XSLoginToken",
            "res": "OK",
            "msg": "Usuario validado correctamente",
            "hash": "",
            "refreshToken": "",
            "legals": true,
            "changePassword": false,
            "needDeviceAuthorization": false,
            "mainUser": true
        }
    }
}

In the hash and the refreshToken we should get a secure web token.
But no, what we get is a hash token in the device_call making the second call to login with the property needDeviceAuthorization set to true.

What is the heart of the issue?

Right now there is a idDevice property that identifies the device that looks like this:

idDevice=d7MwrBXGQF6ZjI7b4_hVgU:APA91bFg79TE0qo3z72dWJ2iJf_swmUie777KgKSLod3qDMS5UxDh9YO5Rrd0n2bDtk2v5G2Wb9zUAoR-ES_aozdVDZTfOKCgloH6D-nvgQO2YY_ToLc6cb7EBKsdPWosFiea6oYsQZb

But I have no idea how to create id like this myself. It doesn’t look like a encoded base 64 string and it looks like a encrypted token. That is what is preventing us to successfully validate the device.

What have I tried?

I have this old android device where I installed a trusted certificate CA so I can monitor all the traffic in the device from all apps. With that I was able to fully capture all the traffic of the securitas app. I uninstall the app and reinstall a couple of time to see how the flow works. Once the device is validated, even if you uninstall the app and reinstall you don’t need to validate again. So the validate_device operation somehow persist over time.

What am I asking?

Help. I don’t know if someone have more experience with this kind of API or put another perspective that can me it works. I offer the possibility of sharing the logs without my personal information or help someone to capture the traffic on their devices.

hmmmm, interesting. Have you checked the HTTP response headers? Sometimes you find there some interesting values. If you can share with me some logs (maybe wireshark trace?), I would take a look.

Muchas gracias por el esfuerzo en esta integración @guerrerotook-. Acabo de intentar llevar a cabo la integración con Securitas y no soy capaz de llevar a cabo la misma.

Ahora tras leer todos estos ISSUES encuentro la razón de ella.

Sólo hacerte saber del gran trabajo que haces y si necesitas de ayuda para algo lo intentamos, pero mi nivel de programación es bajo es este momento en estas areas.

Saludos y gracias,

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024

Hey everyone, let me summarize my efforts so far with the new device authentication that Securitas started enforcing recently. As you may know now is mandatory to verify the device you are calling the API in order to have an open session. That is what making the HA integration not working, or not making it functional if we have to login every 20 minutes with an SMS code.

Where we are right now?

There is a new branch otp_challange that contains all my efforts to make this thing works. There is a API call validate_device that as the name says validate that the device is authorized. I have the SMS flow working in HA. You can select one of your phone numbers, receive an SMS and then call this API again. But for whatever reason this is not working as expected. We should get this response in json.

{
    "data": {
        "xSValidateDevice": {
            "res": "OK",
            "msg": "Petición procesada correctamente",
            "hash": null,
            "refreshToken": null,
            "legals": null
        }
    }
}

And then make another request to login and we should get something like that:

{
    "data": {
        "xSLoginToken": {
            "__typename": "XSLoginToken",
            "res": "OK",
            "msg": "Usuario validado correctamente",
            "hash": "",
            "refreshToken": "",
            "legals": true,
            "changePassword": false,
            "needDeviceAuthorization": false,
            "mainUser": true
        }
    }
}

In the hash and the refreshToken we should get a secure web token.
But no, what we get is a hash token in the device_call making the second call to login with the property needDeviceAuthorization set to true.

What is the heart of the issue?

Right now there is a idDevice property that identifies the device that looks like this:

idDevice=d7MwrBXGQF6ZjI7b4_hVgU:APA91bFg79TE0qo3z72dWJ2iJf_swmUie777KgKSLod3qDMS5UxDh9YO5Rrd0n2bDtk2v5G2Wb9zUAoR-ES_aozdVDZTfOKCgloH6D-nvgQO2YY_ToLc6cb7EBKsdPWosFiea6oYsQZb

But I have no idea how to create id like this myself. It doesn’t look like a encoded base 64 string and it looks like a encrypted token. That is what is preventing us to successfully validate the device.

What have I tried?

I have this old android device where I installed a trusted certificate CA so I can monitor all the traffic in the device from all apps. With that I was able to fully capture all the traffic of the securitas app. I uninstall the app and reinstall a couple of time to see how the flow works. Once the device is validated, even if you uninstall the app and reinstall you don’t need to validate again. So the validate_device operation somehow persist over time.

What am I asking?

Help. I don’t know if someone have more experience with this kind of API or put another perspective that can me it works. I offer the possibility of sharing the logs without my personal information or help someone to capture the traffic on their devices.

Hello, I've tried to reverse engineer the verisure app, what i've discovered is that they are saving the deviceId param inside a sharedPreferences (com.indigitall.prefs), the key name is com.indigitall.prefs.deviceId.

For getting and setting this variable they are using the class yb/c (you can find this reverse engineering the apk), in my opinion the important method of this class is the one named u:

public static void u(Context paramContext, String paramString) {
    if (a.t(paramString)) {
      SharedPreferences.Editor editor = h(paramContext);
      if (editor != null)
        editor.putString("com.indigitall.prefs.deviceId", paramString).apply(); 
    } 
}

I've tried to track where the paramString variable is created and it comes from the class r8/b. From this point it starts to get difficult to track the origin and I've stopped here, the next step might be trying to debug the app and see what's going on.

Hopefully this will be helpful.

That is very interesting, do you know how to read those values in Android? I have a rooted device.

from securitas-direct-new-api.

AdriVillaB avatar AdriVillaB commented on August 11, 2024

The shared preferences is stored on the data directory, /data/data/<package_name>/shared_prefs. It's a XML file with all the values there, you could grep for com.indigitall.prefs.deviceId and you'll get your value.

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024

nada nuevo sobre securitas, ¿no?

from securitas-direct-new-api.

shantur avatar shantur commented on August 11, 2024

I have this old android device where I installed a trusted certificate CA so I can monitor all the traffic in the device from all apps. With that I was able to fully capture all the traffic of the securitas app. I uninstall the app and reinstall a couple of time to see how the flow works. Once the device is validated, even if you uninstall the app and reinstall you don’t need to validate again. So the validate_device operation somehow persist over time.

@guerrerotook : I am trying to figure out how Device ID is generated. It would be helpful if you could share the captured traffic?

from securitas-direct-new-api.

shantur avatar shantur commented on August 11, 2024

I have this old android device where I installed a trusted certificate CA so I can monitor all the traffic in the device from all apps. With that I was able to fully capture all the traffic of the securitas app. I uninstall the app and reinstall a couple of time to see how the flow works. Once the device is validated, even if you uninstall the app and reinstall you don’t need to validate again. So the validate_device operation somehow persist over time.

Sometimes apps create some file in external storage and read them later. Maybe this creates a file in the external storage. Try to use any file explorer app to check external storage

from securitas-direct-new-api.

andr1u avatar andr1u commented on August 11, 2024

Come on guys! It seems you’re close to fix it…

from securitas-direct-new-api.

guerrerotook avatar guerrerotook commented on August 11, 2024

Testing it right now!

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024

@guerrerotook: OWP a OWA Solucionado el problema. He enviado un PR ( #65 ) que también corrige config_flow. No quería cambiar mucho para asegurarme de que va bien con tus planes.
Déjeme saber si esto ayuda.

¡Funciona! Eso fue hermoso. Acabo de probar en mi entorno de desarrollo local que se ejecutó hace dos semanas y automáticamente obtiene un nuevo token y todo funciona de forma inmediata.

Muchas gracias por el aporte. Arregló todo.

Voy a limpiar el código, fusionarlo de nuevo con el maestro, preparar el lanzamiento y actualizar la documentación.

Felicidades a todos.

spectacular you are some cracks

from securitas-direct-new-api.

josecarre avatar josecarre commented on August 11, 2024

Yessss!!! amazing work @shantur and @guerrerotook ! looking forward for testing the new release 😃

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024

no words, amazing

from securitas-direct-new-api.

siom7 avatar siom7 commented on August 11, 2024

Many many many thanks for your patience and your hard work !!!

from securitas-direct-new-api.

soth78 avatar soth78 commented on August 11, 2024

from securitas-direct-new-api.

DNKROZ avatar DNKROZ commented on August 11, 2024

Great job, congratulations to everyone involved, can't wait to use the integration again. Regards.

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024

Hey guys, does anyone else have this?
From HA the alarm is armed perfectly but I cannot disarm it I have to do it from the app

from securitas-direct-new-api.

chabou-san avatar chabou-san commented on August 11, 2024

Great job, congratulations to everyone involved, can't wait to use the integration again. Regards.

This. Big kudos to everyone involved. 👍🎉

from securitas-direct-new-api.

TheGui01 avatar TheGui01 commented on August 11, 2024

from securitas-direct-new-api.

pganansia avatar pganansia commented on August 11, 2024

Great great job!

from securitas-direct-new-api.

Javvaz avatar Javvaz commented on August 11, 2024

First of all, thanks for you work and dedication, I appreciate it.
At the same time, I would like to comment I got to implement the new integration with 2FA, but I don't get to disarm the alarm either scripts or control panel, I only can arm, but not disarm, I have no idea.

I have checked everything without success. Do you have any tip or idea?

from securitas-direct-new-api.

rlcobos2 avatar rlcobos2 commented on August 11, 2024

Congratulations @guerrerotook , this is a very good work!!!!

I have the same issue, but want to explain.

When you disarm the alarm, really this is disarmed ( you can check in the mobile app ), but not refresh the status on HA until some minutes.

Thanks for all your effort!!!

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024

Felicidades@guerrerotook, este es un muy buen trabajo !!!!

Tengo el mismo problema, pero quiero explicar.

Cuando desarma la alarma, realmente se desarma (puede verificar en la aplicación móvil), pero no actualiza el estado en HA hasta algunos minutos.

¡¡¡Gracias por todo tu esfuerzo!!!

In my case no, if I disarm from HA when entering the application it is still connected :-(

from securitas-direct-new-api.

soysnorre avatar soysnorre commented on August 11, 2024

Muchas gracias @guerrerotook.. Increible trabajo

En mi caso, siendo primera vez que integro, el panel es ok y arma , pero como puedo ver en otros no desarma la misma. Reviso en la aplicación y frente al cuadro de alarma y no desactiva.

Saludos y gracias.

from securitas-direct-new-api.

soth78 avatar soth78 commented on August 11, 2024

from securitas-direct-new-api.

IgorPereira-PT avatar IgorPereira-PT commented on August 11, 2024

I have the same issue.

I can arm but i can't disarm.

I tried to call the service to disarm, with and without a code but always without success.

from securitas-direct-new-api.

otistarda avatar otistarda commented on August 11, 2024

A ver si a nuestro crack se le ocurre algo :-(

from securitas-direct-new-api.

vipial1 avatar vipial1 commented on August 11, 2024

Is it working with the latest HomeAssistant version? I got exception after sending the received sms code.

from securitas-direct-new-api.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.