Android Question FritzBox Login to get SID Session ID - PHP-Script

Licht2002

Member
Licensed User
Longtime User
Hello!

Form the Website: http://www.wetterstationen.info/for...eckdosen-gesteuert-durch-wetterdaten-per-php/
i get a PHP-Script to login in the Fritzbox and get a Session ID:

B4X:
<?php
// Benutzerspezifische Angaben
$fritzbox_Password    = 'passwd';
$ain = '0000000000';

// Challenge bei der Fritz.box holen
$ch = curl_init('http://fritz.box/login_sid.lua');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$login = curl_exec($ch);
$session_status_simplexml = simplexml_load_string($login);
if ($session_status_simplexml->SID != '0000000000000000')
{
   $SID = $session_status_simplexml->SID;
}
else
// Session ID errechnen aus Challenge, Passwort und MD5-Verschlüsselung
{
   $challenge = $session_status_simplexml->Challenge;
   $response = $challenge . '-' . md5(mb_convert_encoding($challenge . '-' . $fritzbox_Password, "UCS-2LE", "UTF-8"));
   curl_setopt($ch, CURLOPT_POSTFIELDS, "response={$response}&page=/login_sid.lua");
   $sendlogin = curl_exec($ch);
   $session_status_simplexml = simplexml_load_string($sendlogin);
   if ($session_status_simplexml->SID != '0000000000000000')
       {
       $SID = $session_status_simplexml->SID;
       }
   else
       {
       echo "Fehler: Login fehlgeschlagen";
       return;
       }
}
curl_close($ch);

//  Einschalten (setswitchon)
$import = file_get_contents('https://fritz.box/webservices/homeautoswitch.lua?ain='.$ain. '&switchcmd=setswitchon&sid='.$SID.'');

//  Ausschalten (setswitchoff)
/*
$import = file_get_contents('https://fritz.box/webservices/homeautoswitch.lua?ain='.$ain. '&switchcmd=setswitchoff&sid='.$SID.'');
*/


// von der Fritz.box abmelden
$logout = file_get_contents('https://fritz.box/home/home.lua?sid='.$SID.'&logout=1');
?>

After getting the SID - i will be able to switch the DECT Wireless Plug from AVM: https://www.amazon.de/AVM-Intelligente-Steckdose-FRITZ-DECT/dp/B00AQ9E77M/ref=sr_1_1?ie=UTF8&qid=1474630991&sr=8-1&keywords=fritz dect 200

Is it possible to do this in B4A?

Thanks for your HELP!!!

Tom
 

DonManfred

Expert
Licensed User
Longtime User
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
The md5 code i found did not worked for me. I´m just be curious about to do to and i tried to get the sid from my fritzbox.
i wrapped a lib but at the end it was the md5 implentation of this lib which does send the correct response-string to be used with a okhttpcall

In fact only one mthod of the lib is needed to get the SID.
But as i could see... It should be possible with the lib to enable a gueswifi and some other things...

Give it a try. Note once you got the SID you should be able to build okHttputil jobs which will change your homeautomation....

Hope it helps

B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim ain As String
    Dim pw As String
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

    Private btngetsid As Button
    Private lblsid As Label
    Private SID As String
    Dim FritzCon As FritzBoxConnector
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")
    SID = ""
    ain = "0000000000"
    pw = "dein passwort hier"
    FritzCon.Initialize("","fritz.box")



End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub


Sub btngetsid_Click
    Dim job As HttpJob
    job.Initialize("getsid",Me)
    job.Download("http://fritz.box/login_sid.lua")   
End Sub
Sub JobDone (Job As HttpJob)
   Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
   If Job.Success = True Then
      Select Job.JobName
         Case "Login"
            Dim result As String = Job.GetString
                        Log("login = "&result)
                        Dim XOMBuilder1 As XOMBuilder
                       XOMBuilder1.Initialize("XOMBuilder1")
                        XOMBuilder1.BuildFromString(result, "", Null)                       
         Case "getsid"
            'print the result to the logs
            Dim result As String = Job.GetString
                        Log("getsid = "&result)
                        Dim XOMBuilder1 As XOMBuilder
                       XOMBuilder1.Initialize("XOMBuilder1")
                        XOMBuilder1.BuildFromString(result, "", Null)                       
                        ' Weiter geht´s in der Auswertung des XML -> Event XOMBuilder1_BuildDone
      End Select
   Else
      Log("Error: " & Job.ErrorMessage)
      ToastMessageShow("Error: " & Job.ErrorMessage, True)
   End If
   Job.Release
End Sub
Sub XOMBuilder1_BuildDone(XOMDocument1 As XOMDocument, Tag As Object)
  If XOMDocument1.IsInitialized Then
      Log("XOMDocument is initialized")
    Dim RootElement As XOMElement
    RootElement=XOMDocument1.RootElement
    Log("Root.Value="&RootElement.Value)
    Dim childs As XOMElements
    childs=RootElement.GetChildElements

        Log("childsSize="&childs.Size)
        If childs.Size > 0 Then
            Dim SessionInfo As Map
            SessionInfo.Initialize
            For i = 0 To childs.Size -1
                Dim child As XOMElement = childs.GetElement(i)
                'login = <?xml version="1.0" encoding="utf-8"?><SessionInfo><SID>c5678acaad2604d4</SID><Challenge>ed04cdb0</Challenge><BlockTime>0</BlockTime><Rights><Name>Dial</Name><Access>2</Access><Name>App</Name><Access>2</Access><Name>HomeAuto</Name><Access>2</Access><Name>BoxAdmin</Name><Access>2</Access><Name>Phone</Name><Access>2</Access><Name>NAS</Name><Access>2</Access></Rights></SessionInfo>
                If child.LocalName = "SID" Then
                    SessionInfo.Put("SID",child.Value)           
                End If
                If child.LocalName = "Challenge" Then
                    SessionInfo.Put("Challenge",child.Value)           
                End If
                If child.LocalName = "BlockTime" Then
                    SessionInfo.Put("BlockTime",child.Value)           
                End If
                If child.LocalName = "Rights" Then
                    SessionInfo.Put("Rights",child.Value)                   
                End If
                'Log("child.tostring = "&child.ToString)
                'Log("child.LocalName = "&child.LocalName)
                'Log("child.value = "&child.Value)
                Dim rights As XOMElements = child.GetChildElements
                Log("SizeOf(rights)="&rights.Size)
                If rights.Size Mod 2 = 0 Then
                    Log("mod2=0")
                    For o = 0 To rights.Size -1 Step 2
                        Dim rightn As XOMElement = rights.GetElement(o)
                        'Log("right.tostring = "&rightn.ToString)
                        'Log("right.LocalName = "&rightn.LocalName)
                        'Log("right.value = "&rightn.Value)

                        Dim rightv As XOMElement = rights.GetElement(o+1)
                        'Log("right.tostring = "&rightv.ToString)
                        'Log("right.LocalName = "&rightv.LocalName)
                        'Log("right.value = "&rightv.Value)

                        SessionInfo.Put(rightn.Value,rightv.Value)                   

                    Next
                End If

            Next
            Log("SessionInfo folgt")
            Log(SessionInfo)
            If SessionInfo.Get("SID") <> "0000000000000000" Then
                Log("Session known")                   
                Log("SID = "&SessionInfo.Get("SID"))                   
                SID = SessionInfo.Get("SID")
                lblsid.Text = SID
            Else
                Log("Session Unknown!")
                ' Session ID errechnen aus Challenge, Passwort und MD5-Verschlüsselung
                Dim response As String = FritzCon.getResponse(SessionInfo.Get("Challenge"),pw)

                Log("Fritzcon.response="&response)
                
                Dim req As HttpJob
                req.Initialize("Login",Me)
                req.Download("http://fritz.box/login_sid.lua?username=&response="&response)
            End If
        End If
   Else
     '   XOMDocument1 will be uninitialized if an error has occurred
     Log("An error has occured and the XOMDocument has NOT been initialized")
     Log(LastException.Message)
   End If
End Sub
 

Attachments

  • FritzBoxApiV1.0.zip
    17.2 KB · Views: 453
  • FritzboxConnector.zip
    9.1 KB · Views: 472
Last edited:
Upvote 0

Licht2002

Member
Licensed User
Longtime User
The md5 code i found did not worked for me. I´m just be curious about to do to and i tried to get the sid from my fritzbox.[/CODE]

Hello DonManfred,

thx for the answer.... with your help, i found a solution.....!!!

With some Java - i can do the MD5-Hash....


B4X:
.......
    Dim nativeMe As JavaObject
.......

                    md5  = Dect_Job1.GetString.SubString2(Dect_Job1.GetString.IndexOf("<Challenge>")+11,Dect_Job1.GetString.IndexOf("</Challenge>")) & "-" & nativeMe.RunMethod("getMd5Hash",Array("PASSWORD"))
                    S_ON = "http://fritz.box/login_sid.lua?user=USER_NAME&response=" & md5
                    Dect_Job2.Initialize("Dect_Job2", Me)
                    Dect_Job2.Download(S_ON)

....
#If Java

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public String getMd5Hash(String input) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes());
        BigInteger number = new BigInteger(1, messageDigest);
        String md5 = number.toString(16);

        while (md5.length() < 32)
            md5 = "0" + md5;

        return md5;
    } catch (NoSuchAlgorithmException e) {
//        Log.e("MD5", e.getLocalizedMessage());
        return null;
    }
}

#End If

Thx for your help!

Tom
 
Upvote 0
Top