Mikrotik Auto Login Script

Posted: November 11, 2011 in Hack!, Technical

Unfortunately, I had to subscribe to some Internet provider and found that he uses Mikrotik Proxy. First of all he restricted my access to a single MAC address, however I access the network now through 2 laptops and desktop machine simultaneously 😀 What was really annoying is that I have to create a session with the server by logging in using a username and password using their web interface every time I start my machine, so no internet connectivity unless I open my browser and login to their server..Boring :S I tried to login using Python/httplib2 using my plain username and password but it did not pay. So I inspected the Login web interface and found that the password is salted (Some HEX numbers and my password in between) then MD5ed before it is sent to server…interesting!

It was like this:

<script type="text/javascript" src="/md5.js"></script>
	<script type="text/javascript">
	<!--
	    function doLogin() {
		document.sendin.username.value = document.login.username.value;
		document.sendin.password.value = hexMD5('\330' + document.login.password.value + '\155\153\216\266\076\244\006\261\251\237\164\021\307\047\212\015');
		document.sendin.submit();
		return false;
	    }
	//-->
	</script>

At first I manually MD5ed my “salted” password as I found in the Login page html using Python/md5 module and tried to send it programmatically , But it failed again!

I noticed that the salt changed when I refreshed the page, so at the beginning of my script I grab the Login page html/content and using Python/re REGEX module I extracted the salt from the javascript code and added my password in between and using Python/simplejson I JSONed my POST request payload, But it failed again:S

I suspected that I miss some thing I can not see through Google Chrome Web Inspector Network sniffer, So I tried Wireshark..yes Wireshark😀 to sniff myself and found that my login POST request payload/content is encoded not JSONed, which I did not notice since Chrome Inspector viewed my POST request payload in human readable format, then I changed my code to encode the POST request content to be encoded using Python/urllib.urlencode, tried again and it SUCCEEDED this time 😉

Added the Python shebang at the start of script and added it to the Ubuntu startup programs list and my username/password passed, so I get automatically logged in every time I boot my Ubuntu 😀

You can check my code here  https://github.com/montaro/mikrotik-autologin/

Comments
  1. ahmedkamalkim0 says:

    Hacker spirit 😉 nice work

  2. Rehan Zafar says:

    very nice post dude keep it up

  3. seeker says:

    some one help me… i could not get you

  4. Montaro says:

    Just download my repo https://github.com/montaro/mikrotik-autologin/archive/master.zip
    and find away depends on your OS, to run this in your machine startup:
    $python path/mtlogin.py username password

  5. after i try..
    always show comment is ‘seems to be already logged in’
    but i not yet login…
    sorry..my english is not so good..
    thank’s

  6. sodozoi says:

    how to make it work on windows xp, any help would be very much appreciative. thanks

  7. Montaro says:

    I’m really sorry that I do not have Windows installed on my machine and I even I’m not behind a proxy anymore so I’m sorry to say I can not help any more to make it executable exe.
    You can check how to run a Python script on Windows from here http://stackoverflow.com/questions/4621255/how-do-i-run-a-python-program-in-the-command-prompt-in-windows-7

  8. setterlee says:

    Looks like perfect but… in my case, didnt work. maybe some update was made it on the miktotik router… this is my login page:

    Ingreso – HotSpot V.1.0

     

    Usuario

     
     

    Clave

     

     

     

      

    <p class=".:

    Estimado usuario, A partir del 01 de Mayo 2014, Internet Hogar Bsf. 280.
    DATOS BANCARIOS, PAGOS: 
            
    Cuentas Corrientes: 

    BANESCO:: 0134-0346-50-3461054342                                   
    PRINTER-NET-SERVICE, C.A.          
                                             RIF: J-31754459-5

    REPORTE DE PAGO, Escribanos por:                     
    ADMINISTRACION@PNS.COM.VE

    <p class="Abra sus puertas a un nuevo mercado que hara crecer a su empresaa tu hogar o oficina.:

     

    INTERNET BSF. 200:

    0241 – 8328046             LUNES A VIERNES: 9:00AM A 12:00PM.   1:00PM A 5:00PM.                 
                          &nbsp  REPORTE DE FALLAS:    0414-4395448&nbsp                       

     

     

     

     

  9. setterlee says:

    uppsss. sorry… this the link of my login page… https://dl.dropboxusercontent.com/u/12543437/login.html

  10. Montaro says:

    @setterlee, Thanks!
    I checked the login part in your provided HTML and seems the same as what was in my case.
    What is the output of running the script?

  11. setterlee says:

    this is the output:

    setterlee@Ubuntu-Desktop:~/validate_conection$ ./mtlogin.py nuñezts marnu88
    file: “/tmp/login.html” truncated
    salted password: �marnu88�Ǐp�_b���la
    hashed password: 30631cbb328e1e4e798bd04e46a33b00
    Traceback (most recent call last):
    File “./mtlogin.py”, line 81, in
    main()
    File “./mtlogin.py”, line 77, in main
    login(username, hex_hash_password)
    File “./mtlogin.py”, line 54, in login
    raise Exception(‘Login Failed’)
    Exception: Login Failed
    setterlee@Ubuntu-Desktop:~/validate_conection$

    I don’t know if the special character (ñ) on the username cause the fail on the process, but that was the username assigned to me by the ISP.

    Thanks for your help…

  12. setterlee says:

    I added this line to the code to validate the issue with the special character — > # coding=utf-8

  13. setterlee says:

    I found another solution with python and selenium. Here the code:

    #!/usr/bin/python
    # coding=utf-8
    import time
    import codecs
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys

    browser = webdriver.Firefox()
    browser.get(‘file:///home/likewise-open/EPA000/eve0011737/Descargas/page/page.html’)

    elem = browser.find_elements_by_name(‘username’)
    elem[1].send_keys(codecs.decode(‘nuñestz’,”utf-8″))
    elem = browser.find_elements_by_name(‘password’)
    elem[1].send_keys(‘12345678’ + Keys.RETURN)

    browser.quit()

    • Montaro says:

      I like this simple solution, how could you run this script, in a headless browser?

      • setterlee says:

        Well, in linux with the xvfb program you can set the display environment variable to 99 and the script will be executed in a headless browser. I will share the code in github, I will let you know went I upload the code

  14. Peter says:

    Really cool. I was just about to write exactly that program when i tried to connect my headless RasPi to a hotel network utilizing a Mikrotik Hotspot.
    You saved me from the pain doing it!
    Your solution worked right away for me after editing the IP address in the code.

    • Montaro says:

      @Peter, I’m really happy to hear that! Good luck.

      • Peter says:

        Everybody should be aware that you have to adjust this line in the code to the login URL of your Mikrotik hotspot in order to make it work for you:

        URL = ‘http://10.0.0.2/login’

    • Montaro says:

      You are right, The README should be enhanced, will try to do it and your contribution as a pull request is most welcome 🙂

  15. VIRkid says:

    Hello , I’m a newbie coder . i didn’t understand that base8 part in your code .. can you please explain that ? 🙂 thanks

  16. Akash khan says:

    Sir User asifm is not allowed to login is comming on my Mikrotic routeros need help

  17. mkhattab123 says:

    Thanks for this. I was contemplating multiple solutions for this. I’m using an OpenWRT router so my options are limited. I think a combination of curl and some bash tricks should do the work if Python isn’t an option.

    For desktop machines, another option could be PhantomJS which is basically a headless, scriptable web browser. It would be relatively easy at that point to populate the login form using standard DOM manipulation or jQuery.

  18. great job ,man.i tried to do the same with cURL and worked on it for hours but i couldn’t figure out the hexMD5 thing which got me here when i tried to google it.thanx a lot

  19. Isai hernandez says:

    excuse my ignorance but where this code should go in the mikrotik? I want to login by scanning QR code but the code only enters the user name but no password.. can someone please help me I would appreciate it very much this is my e-mail abuelo085@hotmail.com

    • Montaro says:

      This code should run as a script on startup so whenever you start a browser you do not need to login to Mikrotik with username and password

  20. toro says:

    Traceback (most recent call last):
    File “./main.py”, line 80, in
    main()
    File “./main.py”, line 76, in main
    login(username, hex_hash_password)
    File “./main.py”, line 53, in login
    raise Exception(‘Login Failed’)
    Exception: Login Failed

    but login sukses how solve this status
    my login page https://goo.gl/dHd2i7

  21. 899 says:

    Thank for this very useful!

  22. b911135 says:

    Thanks man, tried scripting it in bash but kept hitting a wall. Teamed this up with cron and I’ll never have to login again!

  23. mohsen says:

    thanks bro .. but is that work auto i mean if microtik restart or logout my pc that script will make re-log if no internet ??
    sorry for bad english

  24. Armando says:

    Hi, I keep getting an error

    File “mtlogin.py”, line 80, in
    main()
    File “mtlogin.py”, line 66, in main
    truncate_file(output)
    File “mtlogin.py”, line 18, in truncate_file
    f = open(file, ‘w+’)
    FileNotFoundError: [Errno 2] No such file or directory: ‘/tmp/login.html’

    I had to modify some things to work with Python 3 but thats all, if you could help?

    Thanks

  25. Peter says:

    Hey Armando,

    maybe you do not have write access to /tmp/login.html or you don’t even have a /tmp directory?
    Adjust the file name in line 13
    13: output = ‘/tmp/login.html’
    to your liking.

    Hope that helps,
    Peter

    • Armando says:

      Thanks! It was the permissions! I moved the file and it worked well kind of. It works on telling me I’m already logged in but it doesnt do the login yet. I replaced some libs for the equivalent on py3.

      Now I get

      File “mtlogin.py”, line 73, in main
      print (‘salted password: %s’ % salted)
      File “C:\Users\arman\AppData\Local\Programs\Python\Python35\lib\encodings\cp437.py”, line 19, in encode
      return codecs.charmap_encode(input,self.errors,encoding_map)[0]
      UnicodeEncodeError: ‘charmap’ codec can’t encode character ‘\xdd’ in position 17: character maps to

      On Pastebin its the modified script http://pastebin.com/ppfVRrqD

      Thanks

  26. Peter says:

    Armando,

    it seems your console is not UTF8-aware. ‘salted’ seems to contain a 0xdd character that does not map to your console charset (Windows codepage 437 I assume). So you need to either convert to hex or whatever is printable on your console or simply skip printing it altogether.

    Peter

  27. […] Mikrotik Auto Login Script | yet another neo.. Ahmed El Refaey […]

Leave a reply to Montaro Cancel reply