Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Identifier rejected on 55U7KQ #14

Open
marcandre83 opened this issue Oct 17, 2023 · 97 comments
Open

Identifier rejected on 55U7KQ #14

marcandre83 opened this issue Oct 17, 2023 · 97 comments

Comments

@marcandre83
Copy link

I bought a 55U7KQ that came out this year. It looks like Hisense did some changes to MQTT again, I am getting “Connection refused: Identifier rejected” over MQTT Explorer as well as within the mqtt logs on my raspberry although I am using my phone’s MAC address as the client ID.
Also on this newer model I can not use the Remotenow app, only the VIDAA app. Any help would be highy appreciated.

Bildschirmfoto 2023-10-17 um 16 47 42
@barrel24
Copy link

i believe our issues my be linked however i cannot use the vidaa app only the remote now app. it is also only able to control volume now and wont do anything with a payload (changesource, launchapp etc) i am however abe to connect with mqtt explorer just check you have entered the certificates correctly for client cert and client key in mqtt explorer. other than that my knowledge is limited lol

@LeoKlaus
Copy link

Having the same issue on a 55U8KQ. I'm pretty sure Hisense changed the way MQTT auth works with newer models (those supporting only the Vidaa App).

I think this might be beyond the scope of what @Krazy998 is doing here, but here's what I could find so far:

  • When setting up and using the Vidaa App, I haven't been able to capture any MQTT traffic whatsoever using Wireshark. In general, there seems to be no direct communication between the TV and the device, as far as I could tell. The only packets the TV sent were DLNA and MDNS discovery related. Pretty much the same goes for the phone (tried an Android and iPhone).
  • I've looked through the files the Android app creates (/root/data/datacom.universal.remote.multi) and have found the following:
    • There's a preferences file containing some identifiers for the device (the phone)
    • There are two SQLite Databases: comm.db and mqttAndroidService.db, with the latter being empty in my case even after pairing and using the remote functionality.

comm.dbcontains a lot of information regarding the paired TV, with probably the most interesting table being deviceconnectbean. This table (in my case) contains the following data:

id accesstoken mac refreshtoken accesstoken_duration_day accesstoken_time refreshtoken_time refreshtoken_duration_day
1 _+pUZJFGxZtnQsDYQEc3ewOv4dG/xJuvlR93qp7CVC6+pX/xN571Bh79/s76QWgS9 e0d8c4d2280088b8632f70f6 #+pUZJFGxZtnQsDYQEc3ewOv4dG/xJuvlR93qp7CVC6+juMFCy+y8Sv9I2PvnUysQ 2 1697805808 1697805808 30

This seems to indicate that the authentication process is much more complex now and I have no idea where to start with this. Anyways, I'll attach the database so you can have a look at them:
comm.db.zip

@Krazy998
Copy link
Owner

Krazy998 commented Oct 21, 2023

Thank you for sharing @LeoKlaus - I was going to suggest wireshark however now that hisense is using TLS it would have been difficult. But worth a initial try. I think its important to establish if the new Vidaa app actually is using a local connect to the tv or is it using some broker or service on the internet. Wireshark should at least tell us that hopefully.

The only other suggestion is to create a serial cable which can TTL directly to the TV and pull the config / app files for analysis. Im not sure how the new 55U8KQ TV's are, but my older 75" has a headphone jack (there is a service jack on the back of the tv) which effectively can connect to a usbTTL device.

I haven't done this in a while however - When the TV is booting you can interrupt its boot and get local access. I found I could only a small portion of the filesystem is set to read only. There is a script that is run as root that kicks off the update check where you can modify it to also launch a telnet server with root access. This will give you ability to pull the code off the device (if it hasnt been patched already on newer devices).

@anonymous-one
Copy link

Just want to chime in... I battled with this for quite some time before giving up.

I own a recently purchased (Oct 2023) 65E7KQ PRO which only connects via the VIDAA app.

I can pretty much repeat everything listed above. I ended up buying a broadlink IR blaster as all I cared about was ON / OFF.

I'll add another small (annoying) nugget : With this set, wifi / network connection is not established until after the TV has been powered on at least once, regardless of what you set in the menus etc. Pretty annoying for those of us who power socket the set OFF for the night (linked to my home alarm state etc...)...

@anonymous-one
Copy link

From what I recall when I was trying to overcome all of this after the initial handshake (eg: the TV was listed in the app), I was able to control it even when I firewalled it off from WAN access.

99% sure, but someone should verify, as I overcame most of what I wanted to do with a broadlink IR blaster and gave up...

Thank you for sharing @LeoKlaus - I was going to suggest wireshark however now that hisense is using TLS it would have been difficult. But worth a initial try. I think its important to establish if the new Vidaa app actually is using a local connect to the tv or is it using some broker or service on the internet. Wireshark should at least tell us that hopefully.

The only other suggestion is to create a serial cable which can TTL directly to the TV and pull the config / app files for analysis. Im not sure how the new 55U8KQ TV's are, but my older 75" has a headphone jack (there is a service jack on the back of the tv) which effectively can connect to a usbTTL device.

I haven't done this in a while however - When the TV is booting you can interrupt its boot and get local access. I found I could only a small portion of the filesystem is set to read only. There is a script that is run as root that kicks off the update check where you can modify it to also launch a telnet server with root access. This will give you ability to pull the code off the device (if it hasnt been patched already on newer devices).

@LeoKlaus
Copy link

LeoKlaus commented Nov 5, 2023

The whole setup process and control does work without the TV having internet access.

I've tried capturing and decrypting the traffic from the app to the TV, but haven't been able to do so for lack of a rootable Android device. On both Android and iOS, the app ignores the system proxy configuration and uses certificate pinning, so a simple mitm doesn't work.

On Android, I've been able to at least capture the MQTT traffic (still on port 36669) using PCAPdroid.

The app itself uses Baidu protect. This (among other things) prevents you from running with USB debugging enabled.

If someone has a rooted Android device and a recent Hisense TV and wants to try getting this to work, the following might help:
Anything that modifies the APK will prevent the app from starting, so your best bet is injecting code at runtime.
https://codeshare.frida.re/@masbog/frida-android-unpinning-ssl/
IIRC, there are also Magisk modules that help bypassing certificate pinning.

If that works and the TV can still be controlled, you should be able to capture and decrypt the traffic using PCAPdroid with the MITM add-on (as far as I could tell, all the commands are still sent on port 36669).

It would be really cool to get this to work, but decompilation (and to some extent reverse engineering) is not exactly legal here in Germany, so even if I managed to break into the app, I couldn't post my findings.

@chimpzilla
Copy link

I have a brand new A6K 2023 model with the latest version of the Vidaa protocol.
I've tried for a few weeks to solve this and had some progress. The APK cannot be reverse engineered properly with the likes of apktool etc. CFR had the best results, but still not very good.
Frida just won't work at all with this app, it must have a lot of anti-frida code running and must be fairly up to date.
You can view some of the apps debugging output though from USB debugging using ADB/Android Studio Logcat without doing anything to the apk. Just enable dev mode in Android and plug it into your PC with Android Studio's logcat running.

If you try a MITM (unpinning doesn't seem to work), the TV drops the connection. However, I was able to see what the initial connection message was including the username, password and client ID and I was able to connect for a limited amount of time using this information using the MQTT Explorer.
Here is what I've found.
Client ID:
C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001
The first part of that is the mac address of the Android device. I was using Android 9, later versions don't allow access to this information, so they must generate a random ID. I don't know what the "44DE1F" is, but it doesn't seem to change,
Username:
his$1700688335
The number is UNIX time (number of seconds since 1970)
Password:
10121AEA780F5D61B6BD93C202F0A6AE
This is an encrypted value based on the client ID and the username. If I change any value in either the client name or the username, none of it works.
It generates a fresh username based on the Unix time, this works for at least and hour (the TV must therefore be checking the time itself).
I suspect that the password is encrypted using the private key located inside the p12 keystore. The reason I suspect this is because in the logcat the following information is displayed at the same time.
38D65DC30F45109A369A86FCE866A85B$C0:BD:D1:3D:6E:3E
keyValue ==>41
value ==> E11C3113BA7285BBC64CAFA18CFB3055
keyNewpass == multiscreen123,userNewName = his$1700688335,passNewword === [C@d0eef3f
topic: /mobile/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001

The "multiscreen123" is the password for the keystore, so this is why I think this might be the case. However, it could be a key hardcoded into the java, which we can't see as it won't decompile. The "passNewword ===[C@d0eef3f" I guess is the "10121AEA780F5D61B6BD93C202F0A6AE", but they didn't convert the byte array to hex for debugging. Shame because it would make testing a lot easier than having to use a rooted phone with PCAPdroid

@LeoKlaus
Copy link

LeoKlaus commented Nov 23, 2023

Very interesting findings. I'm really surprised you were able to use Logcat, as I remember seeing something along the lines of

if(debugger.isEnabled) {
    kill(self.pid)
}

(don't remember the exact implementation but it was very clear what it was supposed to do) in the decompiled code.

I didn't quite understand what information let you connect, though.
ClientID and username is pretty self-explanatory from your comment (though I don't understand who in their right mind would make this depend on timestamps, of all things).

The password you used to connect was 10121AEA780F5D61B6BD93C202F0A6AE, as in that's the plaintext thing?

The key takeway (for me) here is that, even if somebody managed to reverse engineer or find the algorithm/key they use to determine the password, the whole timestamp thing would make it a giant pain in the ass to integrate this into a smart home system.
I don't think node-red, ioBroker and the likes even support dynamic generation of login data, let alone using some self-defined algorithm including time stamps...

@chimpzilla
Copy link

Yes, that's the plain text password, hex values.
Here's the full captured plaintext
MQTT..C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001..his$1700688335..10121AEA780F5D61B6BD93C202F0A6AE

vs the older way
MQTT..mqtt-explorer-96747f72..hisenseservice..multimqttservice

@chimpzilla
Copy link

The timestamp has been put in to stop it being just hardcoded and used on any TV. Hisense obviously don't want people to be able to control their own TV!
If I gave anyone with an up to date TV a fresh set of login details I'm 99% sure that they would work if they used them within an hour. I don't think there's anything in there related to the TV in the details (I could be wrong) and the TV doesn't check the mac address because I managed to connect from my laptop that has a different mac address.
I will check this at some point by checking with a Hisense TV running in a shop (I have one down the road from me).

@chimpzilla
Copy link

Looks like they work for about 4 hours in each direction. I just captured these details with my clock set to 4 hours time.
client id:
C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001
username:
his$1700762502
password:
696CFC0716D0F4DAE4DF350E1BF3C725

I can confirm these are working with my Hisense. If anybody wants to try them in the next 8 hours or so just to prove that the TV details aren't involved. You'll notice that even once it's expired that the error in MQTT explorer is no longer "invalid client ID" but "Not authorised"

@LeoKlaus
Copy link

I keep getting "Disconnected from server" within MQTTExplorer. Tried your MAC, and both the "private" one and the real MAC of my iPhone.

This is really interesting though. If what you assume is true, this implementation does not only suck ass for us users but also from a security-standpoint.

@chimpzilla
Copy link

What certs do you have setup? I get that error message of the certificate is added,

@LeoKlaus
Copy link

What certs do you have setup? I get that error message of the certificate is added,

None, actually. I just got a new Mac and didn't carry over any of the MQTTExplorer settings. I just installed it.

@chimpzilla
Copy link

image

@LeoKlaus
Copy link

LeoKlaus commented Nov 23, 2023

Okay, I've used the certs from d3nd3/Hisense-mqtt-keyfiles.

Now, I get "Connection Refused: Not authorized" when using your MAC and "Identifier Rejected" when using any of mine.
I'm an idiot and had the wrong password in the password field. Using your MAC and credentials, I can indeed connect to the broker.

@chimpzilla
Copy link

Excellent. Saves me having to get out of bed, go to my local TV shop and loiter around in the carpark with my laptop! We now know that there's no "extra" info put into the password or the client ID from the TV itself. If we can correctly generate the password to match the clientID and username we can connect to any TV/
It all revolves around the Unix timestamp to generate the password (the client ID is in there too, but this probably can be anything).
The password is too short to be simply the clientID+username encrypted, it must be some sort of hash/hmac value related to what it would be when encrypted.
If I alter any of the information in either the clientID or username then it fails
Without knowing what format that takes, it's going to be very difficult to workout, but I will keep trying.

@MaxwellJK
Copy link

Hey @chimpzilla i also own the same model (A6K) and i would be happy to help as much as i can.
I am just reading what you have found and it is amazing - thanks for it and for sharing.
Have you made any progress?
thanks

@chimpzilla
Copy link

No luck, sorry. It's pretty hardened to trying work out what's going on.

@Krazy998
Copy link
Owner

Krazy998 commented Dec 8, 2023

I think only way would be to get root access to the tv via serial console (if that is still possible) and examine the code. Clearly hisense has gone out of its way to limit the ability to manage their latest TV's.

On a sidenote - I have root access to my old 3 year hisense and I have examined their logs and various other things. I can tell you they send logs to unified-ter-na.hismarttv.com which include things like what is playing on the tv (using data from the tv guide) what source is selected.

@MaxwellJK
Copy link

I have dug up a little bit more and by using logcat i found a lot of interesting details.

  • First of all, my token lasts 2 days instead of 4 hours. I didn't check if it was exactly 48 hours but in my logcat i have this entry "accesstoken_duration_day": 2, with the access token being created on 1702403040 epoch time (Tue Dec 12 2023 17:44:00 GMT).
  • Second, and probably more interesting, thing is that i was able to find a RefreshToken lasting 30 days and this log MQTT_CONNECT_INFO: url === ssl://192.168.1.234:36669,ip == 192.168.1.234 with something i assume are temporary username, access token and client id (then replaced with the official one mentioned above).
  • the app sends requests to these URLs https://vidaa-base-auth.vidaahub.com/aaa/get_dev_serial and https://vidaa-base-auth.vidaahub.com/aaa/sign_in - i wonder if the creds are actually generated by an external server and not by the tv.

There is much more in the logcat, just not sure it is useful. i'll keep digging

@chimpzilla
Copy link

chimpzilla commented Dec 14, 2023

I've found out a lot more information including how to generate the password for pairing. However I am stuck on the last step of pairing, hopefully somebody can help with this, as I've ran out of ideas.
After pairing an access token is generated (looks like OAUTH maybe) and then you have to reconnect using this token as the password, you can then control the TV.
All of this information is generated from the TV itself, nothing comes from a server on the internet. You can verify this yourself by switching off your internet connection, you can still pair with the TV using the Vidaa app and control it.

So this is how the password and client ID are generated, they are a series of MD5 hashes based on some fixed data, the current unix timestamp and the connecting device's mac address . You can use any mac address, as the TV does not verify this.

You can use this online tool to generate this info yourself:
https://www.miraclesalad.com/webtools/md5.php (Make sure you switch on the "Treat multiple lines as separate strings" & "uppercase hashes")
https://www.unixtimestamp.com/ (get a current unix timestamp)
https://onlinetoolz.net/sum (add up the individual numbers of the time stamp)

These are the series of hashes you need to use:
&vidaa#^app
38D65DC30F45109A369A86FCE866A85B$C0:BD:D1:3D:6E:3E
his9h*i&s%e!r^v0i1c9
1701415028$3D5AEF

These are the results
38D65DC30F45109A369A86FCE866A85B
44DE1F1BC56E2737276E4D8F96E4AB53
3D5AEFF5F89E96E412ACF430C630DE9F
97A11ED3305C23F70B8A335F9D4C0CBF

How you get the hashes:
The 1st line "&vidaa#^app" is fixed.
The 2nd line is made up of "38D65DC30F45109A369A86FCE866A85B$" plus the mac address... "38D65DC30F45109A369A86FCE866A85B$" is fixed.
The 3rd line is mostly fixed, apart from the digit after "his", in this example it's "his9"
This is generated from the unixtime stamp, which in this example was "1701415028", to get 9 you have to add up all the digits 1+7+0+1+4+1+5+0+2+8=29, 9 is the last digit of this sum, 29. (This took me some time to work out as there's no code you can read from the app)
The 4th line is the timestamp+$+ the first 6 digits of the 3rd hash "3D5AEF"
So from this you now have your login details to connect via MQTT

username his$1701415028 (unix timestamp)
client ID :C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001 (client ID 44DE1F is the first six digits of the 2nd hash)
password :97A11ED3305C23F70B8A335F9D4C0CBF (4th hash)

Once you connect in using these login details, you send the following topics, subscribes.
I couldn't get this to work in a windows based MQTT client (I tried MQTT Explorer and MQTTX), I found that it would connect, but that I didn't get any replies and when I subscribed the connection would close.
I've not got much experience of MQTT though

I could get most of it to work by either sending the raw TCP data or using the Android Paho MQTT client (this is what the Vidaa app uses).

The topic contains the MQTT clientID

publish topic :/remoteapp/tv/ui_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/actions/vidaa_app_connect
message: {"app_version":2,"connect_result":0,"device_type":"Mobile App"}
Pin should show on screen.

subscribe: /remoteapp/mobile/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/ui_service/data/authentication
receivedmsg:

publish topic :/remoteapp/tv/ui_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/actions/authenticationcode
message: {"authNum":"5299"}
5299 is the pin that is shown on the TV, when this is sent the pin should vanish from the screen.

subscribe: /remoteapp/mobile/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/ui_service/data/authenticationcode
receivedmsg: {"result":1,"info":""}

or if incorrect pin
receivedmsg: {"result":100,"info":"Wrong authNum!!"}

publish topic:/remoteapp/tv/platform_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/data/gettoken
message:{"refreshtoken":""}

publish topic:/remoteapp/tv/ui_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/actions/authenticationcodeclose
message:

subscribe: /remoteapp/mobile/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/platform_service/data/tokenissuance
receivedmsg:{
"accesstoken": "_ZN5aYxg0DNMirIAXJ5OxWZ8mJaUcdR4GzkHXBofpx0a84hQAcbIaHhMxMhO/4hLf",
"accesstoken_time": "1702028255",
"accesstoken_duration_day": 2,
"refreshtoken": "#ZN5aYxg0DNMirIAXJ5OxWZ8mJaUcdR4GzkHXBofpx0Z5nuorpAkQ9hUjZT8JfRRp",
"refreshtoken_time": "1702028255",
"refreshtoken_duration_day": 30
}

I can get all of this to work, including the "{"result":1,"info":""} message back from the TV, which confirms the pin is correct. But....... the TV never replies with the access token. I can see from the logcat from the Vidaa app that should happen.
I've done a memory-dump of the Android phone and can see that this accesstoken reply does look like it was received from the TV via MQTT (just in case it was generated in some way in the vidaa app).
The next step for me is to make up the USB lead and see what is going on in the TV, if I can, but I've been at this for some weeks now and need to do some other work (Although I hate being beaten).
I've tried doing different orders for the subscribe messages and using different QoS settings. In the logcat the last few publish are sent within a couple of ms of each other. I think that the "codeclose" just removes the pin from the screen, although this goes anyway if you sent the correct pin.
It's a shame the TV disconnects when doing a MITM attack, because then I could verify all the MQTT commands.
If anyone else could try the above using a different client, that might be helpful as it could be some sort of additional setting.
Someone had fun making this all so complicated, for no real reason!

@LeoKlaus
Copy link

You're an absolute madlad! I'll later try to reproduce this with my unit and see how it goes.

Someone had fun making this all so complicated, for no real reason!

It's insane. Hisense could've literally spent less time just providing some official MQTT integration/documentation and turned this utter shitshow into a great unique selling point for their hardware (be it for a very small target audience).

@chimpzilla
Copy link

chimpzilla commented Dec 14, 2023

Update
Hilariously whilst just checking my instructions made sense and could be replicated, I just got the whole thing to work in MQTTX and the TV replied with the tokens. I didn't send any subscribes, the TV just replied. This never worked before when I tried using the MQTTX client, .
I tried the login details in MQTT Explorer and got no reply. I'll try and figure out what is going on, but it confirms 100% that the TV responds with the access token via MQTT. I don't yet understand how the refresh token is used, but one step at a time.

Here's a walkthrough of what was sent and received via the Windows MQTTX client. Received messages in bold
Topic: /remoteapp/tv/ui_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/actions/vidaa_app_connect
{"app_version":2,"connect_result":0,"device_type":"Mobile App"}
2023-12-14 15:01:51:356

Topic: /remoteapp/mobile/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/ui_service/data/authentication
""
2023-12-14 15:01:51:415

Topic: /remoteapp/tv/ui_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/actions/authenticationcode
{"authNum":"2926"}
2023-12-14 15:02:07:548

Topic: /remoteapp/mobile/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/ui_service/data/authenticationcode
{"result":1,"info":""}
2023-12-14 15:02:07:587

Topic: /remoteapp/mobile/broadcast/ui_service/data/hotelmodechange
{"hotel_mode":"off"}
2023-12-14 15:02:07:624

Topic: /remoteapp/tv/platform_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/data/gettoken
{"refreshtoken":""}
2023-12-14 15:03:04:262

Topic: /remoteapp/mobile/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/platform_service/data/tokenissuance
{
"accesstoken": "_7FNfOHs23fiiLEWdLrAvxdSqOu+sgPnlOGBJEKM/W3ZbJRG2GVi6TSW8OdCVYTvt",
"accesstoken_time": "1702566185",
"accesstoken_duration_day": 2,
"refreshtoken": "#7FNfOHs23fiiLEWdLrAvxdSqOu+sgPnlOGBJEKM/W3aq/+fi3l3fgDDMxMPHKnWH",
"refreshtoken_time": "1702566185",
"refreshtoken_duration_day": 30}

@chimpzilla
Copy link

I just tried again in MQTTX and can't get it to respond. I've tried using fresh login details, but nothing comes back from the TV (the pin is displayed on the TV, so it's connected and the messages are sent correctly).
Weird, weird, weird.

@MaxwellJK
Copy link

you are amazing @chimpzilla!
ahh i also couldn't make MQTT Explorer work...i thought i was doing something wrong!
I will try later tonight or tomorrow your procedure with MQTTX and let you know

@chimpzilla
Copy link

you are amazing @chimpzilla! ahh i also couldn't make MQTT Explorer work...i thought i was doing something wrong! I will try later tonight or tomorrow your procedure with MQTTX and let you know

Did MQTT Explorer connect?

@MaxwellJK
Copy link

MaxwellJK commented Dec 14, 2023

Did MQTT Explorer connect?

it did yes but that was the only thing it was doing. no publishing, no subscribing.
Tried with and without TLS (it was connecting in both cases).

@chimpzilla
Copy link

Did MQTT Explorer connect?

it did yes but that was the only thing it was doing. no publishing, no subscribing. Tried with and without TLS (it was connecting in both cases).

Mine won't connect unless it's TLS enabled.
Here's some I just generated that will work for a few hours, if you want to test:
username: his$1702583685
password: 2B9EA0238C4E90CB629D38E272664B68
clientID: C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001

If you post your connection details I can check they are valid?

@MaxwellJK
Copy link

I tried connecting now with your credentials and the connection keeps dropping in mqttx (although it connects).
Yeah, more than happy to share my creds as soon as I understand how i can keep my connection stable

@chimpzilla
Copy link

The refresh token does indeed refresh itself after a day or two. This is even when connected with the access token. I'm yet to see if you can still connect with the access token after 2 days of not connecting or if you need to connect with the refresh token.

@LeoKlaus
Copy link

LeoKlaus commented Jan 6, 2024

The refresh token does indeed refresh itself after a day or two. This is even when connected with the access token.

Interesting. Didn't expect that...

@chimpzilla
Copy link

I've found a bit more out.
If an accessToken is more than 2 days old then you must connect with the refreshToken to get a new accessToken (and new refresh token). You then have to reconnect with the new accessToken.
I've set a rule in my code that if the refreshToken is older than 30 days then pairing must begin again, as I suspect (but can't wait 30 days to find out) that you cannot connect with the refresh token if it's older than 30 days.
There is no real reason for any of this, security via spaghetti!

@LeoKlaus
Copy link

LeoKlaus commented Jan 9, 2024

security via spaghetti

I'll start using this, haha.

@nikagersonlohman
Copy link

Thanks for this! I cannot get it to work yet with my 65U7KQ.

I've done the following:

  1. Downloaded and extracted hi_keys.zip from the mentioned repo
  2. Extracted the access (with an _) and refresh (with a #) tokens from the deviceconnectbean table in comm.db from my Android device (with working Vidaa app)
  3. Extracted the ip-address from the devicebean table (= same as ip mentioned on TV :-) )
  4. Created a credentials.json file:
    { "refreshtoken": "TOKEN_HERE" }

It remains in the waiting loop with disconnect_reason 5.

I have tried the refresh and access tokens in the credentials.json file, neither seems to get it out of the loop.

I did not modify the client_id. Should I get that from somewhere?

What am I missing?

Regards,

Nika.

@LeoKlaus
Copy link

@nikagersonlohman

You'll have to use either one of the scripts posted earlier or use the guide @chimpzilla posted.

You will need the following from a matching set:

  • client id
  • username
  • password (access token)

and the hi_keys, to connect.

Client id, username and password depend on the MAC address of the device you used (though they aren't verified), so you won't be able to use the tokens from your android device without knowing its client id.

@nikagersonlohman
Copy link

nikagersonlohman commented Jan 14, 2024

Cool, thanks!! So here's a python script for that :)

import getmac
import hashlib
import datetime
import time

mac_address = getmac.get_mac_address()
unix_time = str(int(time.time()))

unix_time_sum = sum(int(digit) for digit in unix_time)
unix_time_sum_lastdigit = str(unix_time_sum % 10)

decodedline1 = "&vidaa#^app"
hashline1 = hashlib.md5(decodedline1.encode()).hexdigest().upper()

decodedline2 = hashline1 + "$" + mac_address
hashline2 = hashlib.md5(decodedline2.encode()).hexdigest().upper() 

decodedline3 = "his" + unix_time_sum_lastdigit + "h*i&s%e!r^v0i1c9"
hashline3 = hashlib.md5(decodedline3.encode()).hexdigest().upper()

decodedline4 = unix_time + "$" + hashline3[:6]
hashline4 = hashlib.md5(decodedline4.encode()).hexdigest().upper()

print(decodedline1)
print(decodedline2)
print(decodedline3)
print(decodedline4)

print(hashline1)
print(hashline2)
print(hashline3)
print(hashline4)

username = "his$" + unix_time
client_id = mac_address + "$his$" + hashline2[:6] + "_vidaacommon_001"
password = hashline4

print(username)
print(client_id)
print(password)

@nikagersonlohman
Copy link

nikagersonlohman commented Jan 15, 2024

I am planning to do the whole thing in python so it can be reused for other home automation and such. Initial authentication works with the PIN and such, I am stuck though getting the tokens... going to let it rest for a while, have been trying for hours but can't get it to work. So.... still a "big"work in progress:

import paho.mqtt.client as mqtt
import json
import getmac
import hashlib
import time
import datetime
import sys

tv_ip =         "192.168.178.152"
certfile =      "./rcm_certchain_pem.cer"
keyfile =       "./rcm_pem_privkey.pkcs8"
credfile =      "./credentials.json"
mac_address =   getmac.get_mac_address().upper()
unix_time =     str(int(time.time()))

authjson = {
    "client_id": None,
    "username": None,
    "refreshtoken": None,
    "refreshtoken_time": None,
    "refreshtoken_duration_day": None,
    "accesstoken": None,
    "accesstoken_time": None,
    "accesstoken_duration_day": None
}

global mqtt_message
mqtt_message = "undefined"

def load_authjson(file):
    loaded_json = json.load(file)
    
    authjson["client_id"]                 = loaded_json["client_id"]
    authjson["username"]                  = loaded_json["username"]
    authjson["refreshtoken"]              = loaded_json["refreshtoken"]
    authjson["refreshtoken_time"]         = loaded_json["refreshtoken_time"]
    authjson["refreshtoken_duration_day"] = loaded_json["refreshtoken_duration_day"]
    authjson["accesstoken"]               = loaded_json["accesstoken"]
    authjson["accesstoken_time"]          = loaded_json["accesstoken_time"]
    authjson["accesstoken_duration_day"]  = loaded_json["accesstoken_duration_day"]

def initial_auth():
    unix_time_sum = sum(int(digit) for digit in unix_time)
    unix_time_sum_lastdigit = str(unix_time_sum % 10)

    print("Connecting to Hisense TV...")

    print("")
    decodedline1 = "&vidaa#^app"
    print("Decoded line 1: " + decodedline1)
    hashline1 = hashlib.md5(decodedline1.encode()).hexdigest().upper()
    print("Hashed line 1:  " + hashline1)

    print("")
    decodedline2 = hashline1 + "$" + mac_address
    print("Decoded line 2: " + decodedline2)
    hashline2 = hashlib.md5(decodedline2.encode()).hexdigest().upper() 
    print("Hashed line 2:  " + hashline2)

    print("")
    decodedline3 = "his" + unix_time_sum_lastdigit + "h*i&s%e!r^v0i1c9"
    print("Decoded line 3: " + decodedline3)
    hashline3 = hashlib.md5(decodedline3.encode()).hexdigest().upper()
    print("Hashed line 3:  " + hashline3)

    print("")
    decodedline4 = unix_time + "$" + hashline3[:6]
    print("Decoded line 4: " + decodedline4)
    hashline4 = hashlib.md5(decodedline4.encode()).hexdigest().upper()
    print("Hashed line 4:  " + hashline4)

    authjson["client_id"] = mac_address + "$his$" + hashline2[:6] + "_vidaacommon_001"
    authjson["username"] = "his$" + unix_time
    authjson["refreshtoken"] = hashline4

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        client.connected_flag=True #set flag
        print("")
        print("Connected!")
        client.subscribe("#")

def on_message(client, userdata, message):
    print("")
    print("Message received: ", str(message.payload.decode("utf-8")))
    global mqtt_message
    mqtt_message = json.loads(message.payload.decode("utf-8"))

def on_publish(client, userdata, mid):
    print("")
    print("Published message: " + str(mid))

def on_disconnect(client, userdata, rc):
    print("")
    print("Disconnecting reason:   " + str(rc))
    print("Disconnecting client:   ", client)
    print("Disconnecting userdata: ", userdata)

def get_refresh_token():
    global mqtt_message
    print("")
    print("Connecting to:  " + tv_ip)
    print("With client_id: " + authjson["client_id"])
    print("Username:       " + authjson["username"])
    print("Refresh token:  " + authjson["refreshtoken"])

    client = mqtt.Client(client_id=authjson["client_id"], clean_session=True, userdata=None, protocol=mqtt.MQTTv311, transport="tcp")
    client.tls_set(ca_certs=None, certfile=certfile, keyfile=keyfile, cert_reqs=mqtt.ssl.CERT_NONE, tls_version=mqtt.ssl.PROTOCOL_TLS, ciphers=None)
    client.on_connect = on_connect
    client.on_message = on_message
    # client.on_subscribe = on_subscribe
    client.on_publish = on_publish
    client.on_disconnect = on_disconnect
    client.connected_flag=False
    client.tls_insecure_set(True)
    client.username_pw_set(username=authjson["username"], password=authjson["refreshtoken"])
    client.connect_async(tv_ip, 36669, 60)
    client.loop_start()

    print("")
    while not client.connected_flag: #wait in loop
        print("In wait loop...")
        time.sleep(1)

    # subscribe: /remoteapp/mobile/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/ui_service/data/authentication
        # receivedmsg:
    subscription_topic = "/remoteapp/mobile/" + authjson["client_id"] + "/ui_service/data/authentication"
    print("")    
    print("Subscription topic:   " + subscription_topic)
    client.subscribe(subscription_topic)

    # subscribe: /remoteapp/mobile/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/ui_service/data/authenticationcode
        # receivedmsg: {"result":1,"info":""}
        # or if incorrect pin
        # receivedmsg: {"result":100,"info":"Wrong authNum!!"} 
    subscription_topic = "/remoteapp/mobile/" + authjson["client_id"] + "/ui_service/data/authenticationcode"
    print("")    
    print("Subscription topic:   " + subscription_topic)
    client.subscribe(subscription_topic)

    # publish topic: /remoteapp/tv/ui_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/actions/vidaa_app_connect
        # message: {"app_version":2,"connect_result":0,"device_type":"Mobile App"}
        # Pin should show on screen.
    publish_topic = "/remoteapp/tv/ui_service/" + authjson["client_id"] + "/actions/vidaa_app_connect"
    publish_message = '{"app_version": 2, "connect_result": 0, "device_type": "Mobile App"}'
    print("")    
    print("Publishing topic:   " + publish_topic)
    print("Publishing message: " + publish_message)
    client.publish(publish_topic, publish_message)

    print("")
    while mqtt_message == "undefined":
        print("Waiting for refreshed message...")
        time.sleep(1)
    
    if mqtt_message == "":
        mqtt_message = { "result": 0}

    if mqtt_message["result"] != 1:
        mqtt_message = "undefined"
        pin_code = input("Please enter the PIN: ")

        # publish topic :/remoteapp/tv/ui_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/actions/authenticationcode
            # message: {"authNum":"5299"}
            # 5299 is the pin that is shown on the TV, when this is sent the pin should vanish from the screen.
        publish_topic = "/remoteapp/tv/ui_service/" + authjson["client_id"] + "/actions/authenticationcode"
        publish_message = '{"authNum":"' + pin_code + '"}'
        print("")
        print("Publishing topic:   " + publish_topic)
        print("Publishing message: " + publish_message)
        client.publish(publish_topic, publish_message)
    else:
        print("Already authenticated with PIN!")

    print("")
    while mqtt_message == "undefined":
        print("Waiting for refreshed message...")
        time.sleep(1)
    
    if mqtt_message == "":
        mqtt_message = { "result": 0}

    if mqtt_message["result"] != 1:
        print("Incorrect result received, please fix!")
        sys.exit()

    mqtt_message = "undefined"
    # publish topic:/remoteapp/tv/platform_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/data/gettoken
        # message:{"refreshtoken":""}
    # client.publish("/remoteapp/tv/platform_service/" + client_id + "/data/gettoken", '{"refreshtoken": "' + password + '"}')

# Publishing topic:   /remoteapp/tv/platform_service/98:59:7A:5B:E6:09$his$0861D2_vidaacommon_001/data/gettoken
# Publishing message: {"refreshtoken":""}

    # subscribe: /remoteapp/mobile/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/platform_service/data/tokenissuance
        # receivedmsg:{
        # "accesstoken": "_ZN5aYxg0DNMirIAXJ5OxWZ8mJaUcdR4GzkHXBofpx0a84hQAcbIaHhMxMhO/4hLf",
        # "accesstoken_time": "1702028255",
        # "accesstoken_duration_day": 2,
        # "refreshtoken": "#ZN5aYxg0DNMirIAXJ5OxWZ8mJaUcdR4GzkHXBofpx0Z5nuorpAkQ9hUjZT8JfRRp",
        # "refreshtoken_time": "1702028255",
        # "refreshtoken_duration_day": 30
        # }
    # client.subscribe("/remoteapp/mobile/" + client_id + "/platform_service/data/tokenissuance")

# Subscription topic:   /remoteapp/mobile/98:59:7A:5B:E6:09$his$0861D2_vidaacommon_001/platform_service/data/tokenissuance

    subscription_topic = "/remoteapp/mobile/" + authjson["client_id"] + "/platform_service/data/tokenissuance"
    print("")
    print("Subscription topic:   " + subscription_topic)
    client.subscribe(subscription_topic)

    publish_topic = "/remoteapp/tv/platform_service/" + authjson["client_id"] + "/data/gettoken"
    publish_message = '{"refreshtoken": "' + authjson["refreshtoken"] + '"}'
    print("")
    print("Publishing topic:   " + publish_topic)
    print("Publishing message: " + publish_message)
    client.publish(publish_topic, publish_message)

    # print("")
    # while mqtt_message == "undefined":
    #     print("Waiting for refreshed message...")
    #     time.sleep(1)
    
    # if mqtt_message == "":
    #     mqtt_message = { "result": 0}

    # if mqtt_message["result"] != 1:
    #     print("Incorrect result received, please fix!")
    #     sys.exit()

    # # publish topic:/remoteapp/tv/ui_service/C0:BD:D1:3D:6E:3E$his$44DE1F_vidaacommon_001/actions/authenticationcodeclose
    #     # message:
    # publish_topic = "/remoteapp/tv/ui_service/" + authjson["client_id"] + "/actions/authenticationcodeclose"
    # publish_message = ''
    # print("")
    # print("Publishing topic:   " + publish_topic)
    # print("Publishing message: " + publish_message)
    # client.publish(publish_topic, publish_message)

    print("")
    while mqtt_message == "undefined":
        print("Waiting for refreshed message...")
        time.sleep(1)
    
    if mqtt_message == "":
        mqtt_message = { "refreshtoken": "" }

    if mqtt_message["refreshtoken"] != "":
        print("Refreshtoken received: " + mqtt_message["refreshtoken"])
        authjson["refreshtoken"] = mqtt_message["refreshtoken"]

    # with open(credfile, "w") as file:
    #     json.dump(credentials, file, indent= 4)

    #print("Got new credentials" + mqtt_message + ", terminating...")
    client.loop_stop()
    client.disconnect()

def days_difference(timestamp1, timestamp2):
    # Convert Unix timestamps to datetime objects
    date1 = datetime.utcfromtimestamp(timestamp1)
    date2 = datetime.utcfromtimestamp(timestamp2)

    # Calculate the difference in seconds
    time_difference = abs(date2 - date1).total_seconds()

    # Calculate the difference in days
    days_difference = time_difference / (24 * 3600)

    return days_difference

try:
    file = open(credfile)
except FileNotFoundError:
    print("")
    print('No stored credentials found, starting auth with TV...')
    initial_auth()
else:
    with file:
        load_authjson(file)
        print("Current time:     " + unix_time)
        print("Refresh token:   ", authjson["refreshtoken"])
        print("Refresh time:    ", authjson["refreshtoken_time"])
        print("Refresh duration:", authjson["refreshtoken_duration_day"])

        if authjson["refreshtoken"] == "":
            print('No stored credentials found, starting auth with TV...')
            initial_auth()

        if authjson["refreshtoken"] and authjson["refreshtoken_time"] and authjson["refreshtoken_duration_day"]:
            print('Stored credentials found, checking expiration...')
            if days_difference(unix_time, authjson["refreshtoken_time"]) < authjson["refreshtoken_duration_day"]:
                print('Stored credentials expired, starting auth with TV...')
                initial_auth()

get_refresh_token()

with open(credfile, "w") as file:
    json.dump(authjson, file, indent= 4)

@LeoKlaus
Copy link

@nikagersonlohman We've already managed to produce a working Python script to both obtain the token and refresh it:

Obtaining new token

Refreshing token (second part)

Keep in mind that the TV does have some sort of flooding protection/blacklist, so you might have to use a different MAC address if you've experimented a lot with one device/MAC. This isn't really a problem though as the TV doesn't verify the MAC address.

If you want to spend some more time on this, I'm sure it could be streamlined a lot.
I've ended up using a combination of these scripts with Node-RED to control my TV.

I think the best approach for building a HASS integration would be working with sehaas/ha_hisense_tv and building a custom MQTT bridge that handles the token authentication on its own.
It should be fairly easy to do that using the Node-RED template I provided, just replacing the Fake-Roku with an MQTT in, but I don't use HASS, so I didn't try that.

@nikagersonlohman
Copy link

Wow, this is great again. For some reason it didn't show that entire post with the Obtaining a new token script! All that time wasted trying to create what you guys had created already! We should publish it on a github account to make collaboration easier... I can do that if you guys want?

@nikagersonlohman
Copy link

Note that I have OpenHAB and not HASS and will therefore convert it to javascript (ecmascript) as soon as it works...

@nikagersonlohman
Copy link

I think all that was missing in my script was "hotelmodechange"...

@LeoKlaus
Copy link

We should publish it on a github account to make collaboration easier... I can do that if you guys want?

Sure, just keep in mind that some of of this may be considered intellectual property of Hisense (especially the certificates).

I can't say whether I'll take the time to contribute to this, as I've got everything I wanted working, but I'd surely appreciate the effort.

@zamzon
Copy link

zamzon commented Jan 15, 2024

We should publish it on a github account to make collaboration easier... I can do that if you guys want?

Sure, just keep in mind that some of of this may be considered intellectual property of Hisense (especially the certificates).

I can't say whether I'll take the time to contribute to this, as I've got everything I wanted working, but I'd surely appreciate the effort.

Do you have it perfectly up and running now?

What platform are you using, I use HA and NodeRED, can run on this?

@LeoKlaus
Copy link

Do you have it perfectly up and running now?

What platform are you using, I use HA and NodeRED, can run on this?

I'm using Node-RED with the FakeRoku adapter to be able to set inputs with my Harmony remote, nothing more. This repo contains some more commands to control the TV, they seem to still work with newer TVs.

You can use the scripts I posted earlier to connect via Node-RED. From there on, you'll have to build your own integration for whatever you need.

I guess with HASS, it should be fairly easy to send webhooks to trigger actions through Node-RED, but I'm not familiar with either, so I can't help you there.

@leeandy1
Copy link

I'm in the same boat after (foolishly) letting my 43A6BGTUK update its firmware.

@chimpzilla
Copy link

I'm in the same boat after (foolishly) letting my 43A6BGTUK update its firmware.

That's a 2021 model I think. I wonder if all models are getting this "update"?
If you go to http://:38400/MediaServer/rendererdevicedesc.xml what does the "transport_protocol=" value show?
I've been trying to get my hands on an older model to test with, but if they are all getting the "update" then I don't really need to bother.

@leeandy1
Copy link

Transport protocol is 3160

I contacted Hisense and they sent me a downgrade firmware. I applied it but still no joy in getting access back.

It looks like the downgrade firmware is still running VIDAA 7 as the RemoteNOW app still does not work.

@leeandy1
Copy link

Just to add some more context to this. I am not sure what the firmware was before the OTA update. The OTA update was V0007.06.30F.N1027 I contacted Hisense UK and told them MQTT is now locked down. They sent me V0007.06.30O.N0829. The RemoteNOW still does not work just the VIDAA app. I cannot get MQTT Explorer to connect to the TV.

I have contacted Hisense again to see what they suggest. I also contacted VIDAA who came back with the following:

"Thank you for contacting Vidaa Customer Support. We're so sorry for the late response, Regrettably, it is not publicly available for anyone who wants to integrate with our TV but for the partners we sign with to enhance our platform. We sincerely apologize for any inconvenience that this might cause you. If you are interested in becoming a partner with Vidaa you can contact our team at https://www.vidaa.com/partners/ "

Sounds like this will be a no go unless Hisense can provide the right downgrade software.

@chimpzilla
Copy link

On the TVs I've looked at, >3000 is the new authentication and under 3000 is the older way

@leeandy1
Copy link

leeandy1 commented Feb 3, 2024

Hisense sent another firmware file. I'm now running V0007.06.12R.N0508. MQTT Explorer works as does the RemoteNOW app. I am now having trouble getting the https://github.com/sehaas/ha_hisense_tv integration to work. I just get the spinning wheel and the tv does not bring up a code.

This is so frustrating.

@zamzon
Copy link

zamzon commented Feb 3, 2024

Hisense sent another firmware file. I'm now running V0007.06.12R.N0508. MQTT Explorer works as does the RemoteNOW app. I am now having trouble getting the https://github.com/sehaas/ha_hisense_tv integration to work. I just get the spinning wheel and the tv does not bring up a code.

This is so frustrating.

Could you share the firmware file?

@leeandy1
Copy link

leeandy1 commented Feb 3, 2024

The link will be valid for 7 days:

https://we.tl/t-gvp3a03abx

@chimpzilla
Copy link

chimpzilla commented Feb 15, 2024

Has anybody had any luck getting the picture setting info or channel list from the new firmware?
With the older sets you could publish
/remoteapp/tv/platform_service/clientID/actions/channellist
{"list_para":"1#0","list_name":"Antenna"}

and you would get a list of the current TV channels the TV has.

Also older versions would have the following:
Subscribe
/remoteapp/mobile/broadcast/platform_service/data/picturesetting

Publish
/remoteapp/tv/platform_service/clientID/actions/picturesetting
action: { "action": "get_menu_info" }

But I can't get this to work or figure out what the subscribe would be for it to work?

@jamesmule
Copy link

jamesmule commented Apr 9, 2024

EDIT: RESOLVED

Hey there, I encountered this thread two weeks ago, and managed to control the TV through Home Assistant sensors, switches and number entities using some rudimentary manual YAML configuration. But, as of a few days ago the sendkey topic seems to have stopped working, can anyone confirm that?

The topic is this one (excluding my client id):
/remoteapp/tv/remote_service/00:00:00:00:00:00$his$000000_vidaacommon_001/actions/sendkey

Tested with payloads KEY_POWER and KEY_MUTE among others.

Note that every other topic in the spreadsheet posted by LeoKlaus still works, the sendkey topic used to work until a few days ago and that I'm using two different clients (with different client ids) to control the TV (which also worked fine).

@LeoKlaus
Copy link

LeoKlaus commented Apr 9, 2024

Hey there, I encountered this thread two weeks ago, and managed to control the TV through Home Assistant sensors, switches and number entities using some rudimentary manual YAML configuration. But, as of a few days ago the sendkey topic seems to have stopped working, can anyone confirm that?

The topic is this one (excluding my client id): /remoteapp/tv/remote_service/00:00:00:00:00:00$his$000000_vidaacommon_001/actions/sendkey

Tested with payloads KEY_POWER and KEY_MUTE among others.

Note that every other topic in the spreadsheet posted by LeoKlaus still works, the sendkey topic used to work until a few days ago and that I'm using two different clients (with different client ids) to control the TV (which also worked fine).

Did your TV perform a firmware update by chance? Maybe they changed something.

@jamesmule
Copy link

It's working again, but I can only guess what the problem was. Maybe I was just stupid somewhere.

One of my two access tokens expired a few hours ago, that might be related. Interestingly though, all the other topics kept working on both clients and the sendkey topic stopped working on both clients.

@stevepbuk
Copy link

stevepbuk commented Apr 28, 2024

Hi, Ive tried the above python routine to generate a access token and at first I was joyed as it connected from MQTT Explorer. However, if I publish events they dont seem to action on the TV. I have also tried the same configuration on Home Assistant, and it seems to like the configuration ( doesnt error ) but again it does not appear to be receiving any events or allowing me to publish simple events to the TV. Ive also tried in MQTTX which connects fine but gives the following error when I try to subscribe to anything "Failed to Subscribe TOPIC, Error: Not authorized(Code: 135). Make sure the permissions are correct, and check MQTT broker ACL configuration". I am running a brand new 2023 model - Hisense 55U8KQTUK. However, the scripts that were written on this thread appear to work fine and they are publishing and subscribing with no problem.

Thanks

Steve

@catt0
Copy link

catt0 commented May 5, 2024

I have a Hisense 65E7KQ PRO, bought via Amazon DE in Dec 2023 with software V0002.07.50B.N0715. Thanks to this thread I can connect to it via MQTT. I slightly modified the two scripts provided, call refresh_token.py and it will either create a new set of credentials or refresh an existing one. The credentials will be saved in credentials.json. You will be asked for the PIN code shown on the TV if a fresh set is created. I confirmed I can control and view the TV state via MQTT Explorer.

Some notes, in case they help someone:

  • If you never connected your TV to the internet, manually set its time, mine was stuck in the past so the timestamps for the scripts above never worked
  • If you have not enabled remote control, do so in the Settings -> Remote Control Service menu (accept legalese, no need to set a PIN there)
  • This method works on a TV that never had internet access, all it can do is DNS requests, rest is blocked via router
  • In MQTT Explorer use the credentials from the credentials.json, use the access token as the password, set MQTT Client ID to the client ID from the file
  • In MQTT Explorer subscribing to # does not seem to actually subscribe to everything, use the spreadsheet linked in this thread to figure out what to subscribe to

Next steps (in the medium term) for me are to pretty up this code and try my hand at creating my first HASS integration or modifying an existing one. Not sure how to handle the client certs yet. Sadly you can't easily extract them from the APK.

generate_token.py:

import re, uuid
import hashlib
import time
import paho.mqtt.client as mqtt
import json
from pprint import pprint

reply = None

authentication_payload = None
authentication_code_payload = None
tokenissuance = None

topicTVUIBasepath = None
topicTVPlatformBasepath = None
topicMobileBasepath = None

def cross_sum(n):
   r = 0
   while n:
       r, n = r + n % 10, n // 10
   return r

def stringToHash(input: str):
    result = hashlib.md5(input.encode("utf-8"))
    return result.hexdigest().upper()

def on_connect(client, userdata, flags, rc):
    global topicTVUIBasepath
    global topicTVPlatformBasepath
    global topicMobileBasepath
    if rc == 0:
        client.connected_flag=True #set flag
        print("connected ok")
        
        # Subscribing in on_connect() means that if we lose the connection and
        # reconnect then subscriptions will be renewed.
        client.subscribe("#")

        client.subscribe(topicTVUIBasepath + "actions/vidaa_app_connect")
        client.subscribe(topicMobileBasepath + 'ui_service/data/authentication')
        client.subscribe(topicMobileBasepath + 'ui_service/data/authenticationcode')

        client.subscribe("/remoteapp/mobile/broadcast/ui_service/data/hotelmodechange")
        
        client.subscribe(topicMobileBasepath + 'platform_service/data/tokenissuance')

    else:
        print("Bad connection Returned code=",rc)
        client.bad_connection_flag=True


# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, message):
    print("i'm on message")
    global reply
    print("message received " ,str(message.payload.decode("utf-8")))
    print("message topic=",message.topic)
    print("message qos=",message.qos)
    print("message retain flag=",message.retain)
    reply = message

def on_subscribe(client, userdata, mid, granted_qos):
    print("Subscribed: "+str(mid)+" "+str(granted_qos))

def on_publish(client, userdata, mid):
    print("Published message " + str(mid))

def on_disconnect(client, userdata, rc):
    print("disconnecting reason  "  +str(rc))

def on_log(client, userdata, level, buf):
    print("log: ",buf)

def on_message_msgs(mosq, obj, msg):
    print("MESSAGES: " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))


def on_authentication(mosq, obj, msg):
    global authentication_payload
    authentication_payload = msg

def on_authentication_code(mosq, obj, msg):
    global authentication_code_payload
    authentication_code_payload = msg

def on_tokenissuance(mosq, obj, msg):
    global tokenissuance
    tokenissuance = msg


def write_token_to_creds_file():
    global topicTVUIBasepath
    global topicTVPlatformBasepath
    global topicMobileBasepath
    timestamp = int(time.time())
    #timestamp = 1702583685

    firstHash = stringToHash("&vidaa#^app")

    mac = ':'.join(re.findall('..', '%012x' % uuid.getnode())).upper()
    #mac = "C1:BD:D1:3D:6E:3E"
    print(f'mac {mac}')

    secondHash = stringToHash("38D65DC30F45109A369A86FCE866A85B$" + mac)

    lastDigitOfCrossSum = cross_sum(timestamp)%10

    thirdHash = stringToHash("his"+ str(lastDigitOfCrossSum) +"h*i&s%e!r^v0i1c9")

    fourthHash = stringToHash(str(timestamp) + "$" + thirdHash[:6])

    print(firstHash)
    print(secondHash)
    print(thirdHash)
    print(fourthHash)

    clientID = mac + "$his$" + secondHash[:6] + "_vidaacommon_001"


    client = mqtt.Client(client_id=clientID, clean_session=True, userdata=None, protocol=mqtt.MQTTv311, transport="tcp")


    client.tls_set(ca_certs=None, certfile="./rcm_certchain_pem.cer", keyfile="./rcm_pem_privkey.pkcs8", cert_reqs=mqtt.ssl.CERT_NONE,
        tls_version=mqtt.ssl.PROTOCOL_TLS, ciphers=None)

    client.on_connect = on_connect
    client.on_message = on_message
    # client.on_subscribe = on_subscribe
    client.on_publish = on_publish
    client.on_disconnect = on_disconnect
    # client.on_log = on_log


    client.connected_flag=False

    client.tls_insecure_set(True)

    username = "his$" + str(timestamp)
    print(f'username: {username}')
    print(f'password: {fourthHash}')
    print(f'client_id: {clientID}')

    client.username_pw_set(username=username, password=fourthHash)

    topicTVUIBasepath = "/remoteapp/tv/ui_service/" + clientID + "/"
    topicTVPlatformBasepath = "/remoteapp/tv/platform_service/" + clientID + "/"
    topicMobileBasepath = "/remoteapp/mobile/" + clientID + "/"

    client.message_callback_add(topicMobileBasepath + 'ui_service/data/authentication'          , on_authentication)
    client.message_callback_add(topicMobileBasepath + 'ui_service/data/authenticationcode'      , on_authentication_code)


    client.message_callback_add('/remoteapp/mobile/broadcast/ui_service/data/hotelmodechange'   , on_message_msgs)

    client.message_callback_add(topicMobileBasepath + 'platform_service/data/tokenissuance'     , on_tokenissuance)


    client.connect_async("192.168.65.61", 36669, 60)
    client.loop_start()

    while not client.connected_flag: #wait in loop
        print("In wait loop")
        time.sleep(1)

    print('publishing message to actions/vidaa_app_connect ...')
    client.publish( topicTVUIBasepath + "actions/vidaa_app_connect", '{"app_version":2,"connect_result":0,"device_type":"Mobile App"}')

    print(f'subscribing to {topicMobileBasepath}ui_service/data/authentication ...')
    while authentication_payload is None:
        time.sleep(0.1)

    if authentication_payload.payload.decode() != '""' :
        print('Problems with the authentication message!')
        print(authentication_payload.payload)
        print('Exiting...')
        exit()

    authNum = input("Enter the four digits displayed on your TV: ")

    print(f'publishing message to {topicTVUIBasepath}actions/authenticationcode ...')
    client.publish( topicTVUIBasepath + "actions/authenticationcode", '{"authNum":' + authNum + '}')

    print(f'subscribing to {topicMobileBasepath}ui_service/data/authenticationcode ...')

    client.subscribe(topicMobileBasepath + 'ui_service/data/authenticationcode')

    while authentication_code_payload is None:
        time.sleep(0.1)

    print(authentication_code_payload.payload.decode())
    if json.loads(authentication_code_payload.payload.decode()) != json.loads('{"result": 1,"info": ""}') :
        print('Problems with the authentication message!')
        print(authentication_code_payload.payload)
        print('Exiting...')
        exit()

    print("Success! Getting access token...")
    print(f'publishing message to {topicTVPlatformBasepath}data/gettoken ...')
    client.publish( topicTVPlatformBasepath + "data/gettoken", '{"refreshtoken": ""}')

    print(f'publishing message to {topicTVUIBasepath}actions/authenticationcodeclose ...')
    client.publish( topicTVUIBasepath + "actions/authenticationcodeclose")

    print(f'subscribing to /remoteapp/mobile/broadcast/ui_service/data/hotelmodechange ...')
    client.subscribe('/remoteapp/mobile/broadcast/ui_service/data/hotelmodechange')

    print(f'subscribing to {topicMobileBasepath}platform_service/data/tokenissuance ...')
    client.subscribe(topicMobileBasepath + 'platform_service/data/tokenissuance')

    while tokenissuance is None:
        time.sleep(0.1)

    t = tokenissuance.payload.decode()
    t2 = json.loads(t)
    t2['client_id'] = clientID
    t2['username'] = username
    t2['password'] = fourthHash
    pprint(t2)

    print('token issued...well done!')

    json.dump(t2, open('credentials.json', 'w'))
    print('credentials saved to credentials.json')

    client.loop_stop()
    client.disconnect()

if __name__ == "__main__":
    write_token_to_creds_file()

refresh_token.py:

import paho.mqtt.client as mqtt
import time
import json
from generate_token import write_token_to_creds_file

tv_ip =         "192.168.65.61"
certfile =      "./rcm_certchain_pem.cer"
keyfile =       "./rcm_pem_privkey.pkcs8"

def load_or_generate_creds(rec=False):
    global oldCreds
    try:
        file = open('credentials.json')
    except FileNotFoundError:
        if not rec:
            print('No stored credentials found, starting auth with TV...')
            write_token_to_creds_file()
            load_or_generate_creds(True)
        else:
            print('Unable to generate credentials.')

    else:
        with file:
            oldCreds = json.load(file)

load_or_generate_creds()
refreshtoken = oldCreds["refreshtoken"]
client_id = oldCreds['client_id']
username = oldCreds['username']
password = oldCreds['password']

credentials = ""

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        client.connected_flag=True #set flag
        print("connected ok")
        # Subscribing in on_connect() means that if we lose the connection and
        # reconnect then subscriptions will be renewed.
        client.subscribe("#")
def on_message(client, userdata, message):
    print("message received " ,str(message.payload.decode("utf-8")))
    global credentials
    credentials = json.loads(message.payload.decode("utf-8"))
def on_publish(client, userdata, mid):
    print("Published message " + str(mid))
def on_disconnect(client, userdata, rc):
    print("disconnecting reason  "  +str(rc))

def refresh_token():

    client = mqtt.Client(client_id=client_id, clean_session=True, userdata=None, protocol=mqtt.MQTTv311, transport="tcp")

    client.tls_set(ca_certs=None, certfile=certfile, keyfile=keyfile, cert_reqs=mqtt.ssl.CERT_NONE,
        tls_version=mqtt.ssl.PROTOCOL_TLS, ciphers=None)


    client.on_connect = on_connect
    client.on_message = on_message
    # client.on_subscribe = on_subscribe
    client.on_publish = on_publish
    client.on_disconnect = on_disconnect

    client.connected_flag=False

    client.tls_insecure_set(True)

    client.username_pw_set(username=username, password=password)

    client.connect_async(tv_ip, 36669, 60)
    client.loop_start()

    while not client.connected_flag: #wait in loop
        print("In wait loop")
        time.sleep(1)

    client.subscribe("/remoteapp/mobile/" + client_id + "/platform_service/data/tokenissuance")
    client.publish("/remoteapp/tv/platform_service/" + client_id + "/data/gettoken", '{"refreshtoken": "' + refreshtoken + '"}')


    while credentials == "":
        print("waiting for refreshed credentials...")
        time.sleep(1)


    credentials['client_id'] = client_id
    credentials['username'] = username
    credentials['password'] = password
    with open("credentials.json", "w") as file:
        json.dump(credentials, file, indent= 4)

    print("got new credentials, terminating...")
    client.loop_stop()
    client.disconnect()

    return credentials["accesstoken"]
    #exit()

if __name__ == "__main__":
    refresh_token()

@stevepbuk
Copy link

Thats great thanks. I worked out what my problem was. I had been sending the password instead of the access key in the password field. Now got the same issue you mention in that I cannot subscribe using a wildcard #. Thats fine though as the spreadsheet you mention has all of the useful ones in. I found some more in the source code of this plugin.

https://github.com/sehaas/ha_hisense_tv

Thanks

Steve

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests