tcl/expect magic ssh dictionary password


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting tcl/expect magic ssh dictionary password
# 1  
Old 07-30-2012
tcl/expect magic ssh dictionary password

Hi gurus, I am trying to do some expect/TCL magic. My goal is to write some kind of password guessing script (nearly similar to dictionary attack against ssh). I read that this could be possible with expect/TCL, I am newbie in this language, its function and its terms so please be patient Smilie


The normal process of logging onto server looks like this:
Code:
SU-capitan:/home/unix/wakatana# ssh strom
This server is production server

wakatana's password: [TYPING CORRECT PASSWORD "unix"]
Authentication successful.
Your password has expired.  You are now forced to change it.
Last login: Fri Jul 27 2012 15:24:13 +0100 from capitan
Sun Microsystems Inc.   SunOS 5.10

Please note the following:
This server is production server

TERM = (unknown) [TYPED "xterm" AND PRESSED ENTER]
[SCREEN CLEARS AND SHELL APPEARS AS EXPECTED]
strom:/home/unix/wakatana$

However (probably due to ssh configuration - correct me if i am wrong) if I make typo in password typing I have another two chances:
Code:
SU-capitan:/home/unix/wakatana# ssh strom
This server is production server

wakatana's password:
wakatana's password:
wakatana's password:
warning: Authentication failed.
Disconnected; no more authentication methods available (No further authentication methods available.).
SU-capitan:/home/unix/wakatana#

So my goal is to try several passwords during login (it would be great to leverage all three chances for typing correct password, to prevent multiple connecting/disconnecting) and save some kind of report of this activity (for further processing).


My 1st attempt was following lines. Problem with this is that this solution "works" only if correct password is in pass1 variable, however I am still not able to catch the output in friendly format. In fact the output is not as straightforward that I can determine if login was successful or not.

Code:
SOURE CODE:
-------------
#!/usr/local/bin/expect
set pass1 "unix1\n";
set pass2 "unix2\n";
set pass3 "unix\n";
set machine [lindex $argv 0];

spawn ssh -q "${machine}" "exit";
expect {
            -re "(P|p)assword:" {send ${pass1}; puts ${pass1}}
            -re "(P|p)assword:" {send ${pass2}; puts ${pass2}}
            -re "(P|p)assword:" {send ${pass3}; puts ${pass3}}
}
interact;


RESULT1:
---------
SU-capitan:/home/unix/wakatana# ./tcl1.tcl strom # pass1 contains WRONG pass
spawn ssh -q strom exit
wakatana's password: unix1

wakatana's password: [AT THIS POINT IT HANGS AND PRESSING ENTER IS REQUIRED]
wakatana's password: [AT THIS POINT IT HANGS AND PRESSING ENTER IS REQUIRED]


RESULT2:
---------
SU-capitan:/home/unix/wakatana# ./tcl1.tcl strom # pass1 contains CORRECT pass
spawn ssh -q strom exit
wakatana's password: unix

unix

Your password has expired.  You are now forced to change it.
TERM = (unknown) [TYPED "xterm" AND PRESSED ENTER]
[SCREEN CLEARS AND SHELL APPEARS AS EXPECTED]




2nd try was just simple script which uses exp_continue that is still unclear to me (and I would appreciate if somebody could clear it), however it throws some errors:
Code:
SOURCE CODE:
--------------
#!/usr/local/bin/expect
set pass1 "unix\n";

set machine [lindex $argv 0];

spawn ssh -q "${machine}" "exit" ;
expect {
                -re "(P|p)assword:" { send ${pass1}; exp_continue}
}
            
puts "PASSWORD: ${pass1}"
interact;

RESULT1:
---------
SU-capitan:/home/unix/wakatana# ./tcl2.tcl strom # pass1 contains correct pass
spawn ssh strom exit
This server is production server

wakatana's password:
Authentication successful.
Your password has expired.  You are now forced to change it.
PASSWORD: unix

spawn_id: spawn id exp4 not open
    while executing
"interact"
    (file "./tcl2.tcl" line 13)
SU-capitan:/home/unix/wakatana#




3rd try was this, still some errors and awful output useless for further processing:
Code:
SOURCE CODE:
--------------
#!/usr/local/bin/expect
set pass1 "unix\n";
set machine [lindex $argv 0];

spawn ssh -q "${machine}" "exit" ;
expect {
                -re "(P|p)assword:" { send ${pass1}; puts "PASSWORD: ${pass1}"; exp_continue}
}
interact;


RESULT:
--------
SU-capitan:/home/unix/wakatana# ./tcl3.tcl strom
spawn ssh -q strom exit
wakatana's password: PASSWORD: unix


Your password has expired.  You are now forced to change it.
spawn_id: spawn id exp4 not open
    while executing
"interact"
    (file "./tcl3.tcl" line 11)


4th try, after reading somewhere that expect consists of: "expect pattern action pattern action..." and action can include another expect command. But after closer look it is obvious that even if all three passwords will be wrong as a correct solution will be propagated pass3. Also this solutions throws error because it will "expect" password even if the previous (eg. pass2) attempt matched (see Result bellow)

Code:
SOURCE CODE:
--------------
#!/usr/local/bin/expect
global var "";
set pass1 "unix1\n";
set pass2 "unix\n";
set pass3 "unix2\n";
set machine [lindex $argv 0];

spawn ssh -q "${machine}" "exit" ;
expect {

            
            -re "(P|p)assword:" {
            send ${pass1};
            #puts ${pass1};
            set var ${pass1};
            expect {
                        -re "(P|p)assword:" {
                        send ${pass2};
                        #puts ${pass2};
                        set var ${pass2};
                        expect {
                        -re "(P|p)assword:" {
                        send ${pass3};
                        #puts ${pass3};
                        set var ${pass3};
                        }
                        }
                        }
            }
            }
}
puts "CORRECT PASSWORD IS: ${var}"
interact;




RESULT:
--------
SU-capitan:/home/unix/wakatana# ./tcl4.tcl strom
spawn ssh -q strom exit
wakatana's password:
wakatana's password:
Your password has expired.  You are now forced to change it.
CORRECT PASSWORD IS: unix

spawn_id: spawn id exp4 not open
    while executing
"interact"
    (file "./tcl4.tcl" line 33)

Questions
1. How does expect knows when is typing of input possible (when I can invoke send) ?
- eg. Is expect capable to process also text that appears on screen but (user) input is not expected (in normal circumstances) ?
- or in other words, how expect know if app has input available or requires user interaction or what is the correct name

2. Does TCL=Expect ?
- or expect uses TCL ?

3. Does expect supports some kind of looping
- eg. If same text appears on screen which will match "expect" pattern (requesting password) the different "send" action will be called (passing next element from array)?
- in other words: How to "expect" same pattern for several times but "send" another string

4. Does expect supports something opposite to regexp, or negation of regexp ?
- eg. expecting some string in loop and calling send (passing password) but do another action if expect wont match string (password was guessed or chances expired)
- in other words: How to "expect" same pattern for several times and "send" another string but after not matching "expect"

5. In my situation, when I just want to know right password (connecting to server and after exiting) is command "interact" (or statement or whatever it is called) required ?

6. What exactly does exp_continue doing ? It seems like if it wont wait for requested input until "send" is invoked, is there some timeout or something similar ?
- eg. is possible to invoke "exp_continue" to repeat "send" but with different arguments and when "expect" wont match the exp_continue will break ?

7. Is possible to do some basic if else construction in input matching (in "expect")
- I would also handle following message "continue connecting yes/no"

I hope you understand what I am trying to say. If somebody cloud help I hope it will be helpful also for other expect/TCL newbies. Thank you very much.
# 2  
Old 07-30-2012
Kindly ensure you don't go and use this for malacious purposes. Bear in mind that most production environments will have some kind of log parsing program in place to catch (and sometimes blacklist) stuff like this.

Code:
1. How does expect knows when is typing of input possible (when I can invoke send) ?

It scans input as it comes, to actually view exactly what it's seeing and how it's responding add "exp_internal 1" to the top of the script. Beware, the output will be quite verbose.

Code:
eg. Is expect capable to process also text that appears on screen but (user) input is not expected (in normal circumstances) ?
- or in other words, how expect know if app has input available or requires user interaction or what is the correct name

As soon as it sees a matching regex/pattern it'll go ahead and send whatever is within the expect statement. If nothing matches it will literally wait forever or execute the timeout branch if you have one specified.

Code:
2. Does TCL=Expect ?
- or expect uses TCL ?

The latter.

Code:
3. Does expect supports some kind of looping
- eg. If same text appears on screen which will match "expect" pattern (requesting password) the different "send" action will be called (passing next element from array)?
- in other words: How to "expect" same pattern for several times but "send" another string

Use exp_continue and have it read the next line of your dictionary file in every attempt. It does also support looping.

Code:
4. Does expect supports something opposite to regexp, or negation of regexp ?
- eg. expecting some string in loop and calling send (passing password) but do another action if expect wont match string (password was guessed or chances expired)
- in other words: How to "expect" same pattern for several times and "send" another string but after not matching "expect"

You can expect multiple expressions, e.g

Code:
            spawn ssh ${SSHOpts} ${UserName}@${server}
            expect {
                "timed out" {
                    logWrite ${oFile} ${server} "ERROR: Timed out"
                    continue
                }
                "reset by peer" {
                    logWrite ${oFile} ${server} "ERROR: Connection reset"
                    continue
                }
                "failure in name resolution" {
                    logWrite ${oFile} ${server} "ERROR: Host not found"
                    wait
                    continue
                }
                "(yes/no)?" {
                    send "yes\r"
                    exp_continue
                }
                "*word:" {
              ..........

Code:
5. In my situation, when I just want to know right password (connecting to server and after exiting) is command "interact" (or statement or whatever it is called) required ?

If you don't throw an interact it will close the spawn_id, in this case your SSH session, and it will disconnect you. Whether or not that's intended behavior is up to you.

Code:
6. What exactly does exp_continue doing ? It seems like if it wont wait for requested input until "send" is invoked, is there some timeout or something similar ?
- eg. is possible to invoke "exp_continue" to repeat "send" but with different arguments and when "expect" wont match the exp_continue will break ?

exp_continue doesn't ever break, it forces a re-evaluation of the previous expect statement. Definitely possible to send different things with this, as mentioned above.

Code:
7. Is possible to do some basic if else construction in input matching (in "expect")
- I would also handle following message "continue connecting yes/no"

Yes, as stated prior, expect supports regex matching and multiple patterns in a single expect statement.
# 3  
Old 08-01-2012
Hi Jayd512,
sorry for inconvience, my aim was not to give clue to somebody of how to crack passwords.
I just wondered about using expect scripts. Unfortunatelly you can easy abuse those information for cracking passwords. I really needed those information for "password cracking"
(but all in therms of legal - I needet to automate process of password guessing on server in our company because of old admin set passwords and forgot which password on which server Smilie.
Although thanks for warning I will try not to post similar posts.




Thank you very much Vryali, you post helped me to move big step forward. You can be calm I did not abuse those information, just needed them all in therms of legal (a lot of them I will be using to something completly different (automating interactive commands), but the ssh password prompting gives great oportunity to ask lot of expect examples)
I have some more questions (If you dont mind)

1. Seems like in example that You have posted "continue" and "exp_ontinue" performs the same action (they both works as a "goto" to "expect" statement from which was invoked (Correct me if I am wrong))
- also read in man pages tat "continue" acts like any other classic "continue" statement which is used eg. in awk also, read that it sets TCL_CONTINUE what does this mean practically ?
- so what is difference between continue and exp_continue ?

2. Is adding "-re" to "expect" necessary, I read somewhere that "-re" enables regular expression evaluating.

3. Is possible to supress any output of TCL instead of lines that I want explicitly printed on screen eg. with puts function ?
- I used redirection in spawning of ssh ("2>&1>/dev/null") but expect also outputs some text, here is some discussion probably regarding this question but is unclear to me
https://www.unix.com/shell-programmin...sword-arg.html


Following questions may be related:

4. Please look at following post https://www.unix.com/shell-programmin...cant-stop.html
In 1st post user "radioactive9" "expect" the following string: "~]$ " two times. He complains about infinite looping which seems logic to me (because of string "~]$ " matched above in code and '{send "passwd\r" ; exp_continue}' is invoked again ). How does frappa's suggested 'send "exit\r\r' help in this situation ?

- In another words if i expect two same strings, the first one (code above) is always matched ?
- Also in 4th post there are two "expect" and in both is the "default" branch, which "default" branch will be called ?


5. Previous questions points me to another question; how to face situation when I need to "expect" same string but in different circumstances ? The previous link (1st post) explains well what I mean. My guess is to use another "expect" in particular superior "expect" (One problem I see is how to jump to most superior code), one code for thousand examples.

Code:
# SOME CODE HERE
expect {
"~]$ " {send "passwd\r";  expect {
													"(current) UNIX password:" {send "Password\r" ; exp_continue}
													"New UNIX password:" {send "P@ssw0rd\r" ; exp_continue}
													"Retype new UNIX password:" {send "P@ssw0rd\r" ; exp_continue}
													"~]$ " {send "exit\r"}											
													
													# ??? HOW TO JUMP TO MOST SUPERIOR "expect" ???
													
													# 1st SOLUTION:
													# "~]$ " {send "exit\r"; "break;" }
													
													# 2nd SOLUTION
													# "~]$ " { send "exit\r"; }
													# default { break; }
											  }
		 }
}
# SOME CODE HERE

Is this correctapproach ?


6. You have said that expect uses "send" action as it sees matching pattern from "expect", so how to overcome situation where pattern matches but input is not desired (end expect after all "send" some string) ? Is this really treaten as error ? (expect will "send" another string after input will be requested - correct me if I am wrong)
- eg. can be some kind of sleep issued ?
- are there used any buffers ?



7. I found somewhere on internet "set timeout -1", "match_max 100000", or using "send --" or even "send -s" instead of classic "send". Also I found that "send_user" could be used to send any output to user, dont ou know some site where those functions are explained cause eg. "match_max" confuses me what does buffer size stands for ?


Thank you very much for yor help.
# 4  
Old 08-01-2012
We do not allow topics about hacking.
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Tcl / expect need to attempt telnet if failed ssh

Morning and Happy New Year to all. I am in a situation where I need to connect to a list of devices that are using either telnet or ssh. I want to try to telnet, if I receive any of the following I want to attempt ssh : "Connection refused" "Connection timed out" timeout expiration ... (3 Replies)
Discussion started by: popeye
3 Replies

2. Shell Programming and Scripting

SFTP or scp with password in a batch script without using SSH keys and expect script

Dear All, I have a requirement where I have to SFTP or SCP a file in a batch script. Unfortunately, the destination server setup is such that it doesn't allow for shell command line login. So, I am not able to set up SSH keys. My source server is having issues with Expect. So, unable to use... (5 Replies)
Discussion started by: ss112233
5 Replies

3. Shell Programming and Scripting

Passing Password to SSH without using expect in a Script

How can I pass password in SSH command without using expect in a shell program. I don't have expect installed on my Solaris server. #!/bin/bash ssh user@hotname (how to supply pass in script?:wall:) Experts please help its very urgent. Shrawan Kumar Sahu (4 Replies)
Discussion started by: ss135r
4 Replies

4. UNIX for Dummies Questions & Answers

Expect/Tcl help

hi, I am new in Expect. I have a question about expect timeout. suppose I have a structure of expect { ".."{ send"............"} timeout{ ............... } } The silly question is if I reach timeout, how can I store the error message showing on the screen to... (2 Replies)
Discussion started by: allenxiao7
2 Replies

5. Shell Programming and Scripting

Help with TCL/Expect in Solaris 5.3

I'm having this problem with a very simple tcl expect script that is running on Solaris 5.3 with TCL version 8.4.7 and expect version 5.0. below is the simplified version of the code snippet, which I think has everything to illustrate the problem, the full version is at the very bottom in... (0 Replies)
Discussion started by: pinchharmonic
0 Replies

6. Shell Programming and Scripting

tcl/expect

Can someone identify what is the problem here?. no children while executing "exp_wait -nowait -i -1" (procedure "logOptions" line 45) invoked from within "logOptions" (procedure "doExecute" line 98) invoked from within "doExecute" (procedure "main" line 32) ... (7 Replies)
Discussion started by: calsum
7 Replies

7. Shell Programming and Scripting

Tcl expect HELP

In the following "for" loop I assume the the script will expect "anyway", "first" NOT in any paticular order and send "yes" when there found, breaking out of the loop when "$prompt" is found. The way it is working is like 3 individual expect lines, and they MUST be in cronological order. ANY help... (0 Replies)
Discussion started by: dave_m
0 Replies

8. UNIX for Dummies Questions & Answers

Expect/Tcl help?

Does anyone know of an expect/tcl forum that is as helpful as this one is for shell scripting? Or if anyone has any expect knowledge, can you please provide some guidance on how to write to a local error log based on output from a ssh session? I have something like this: foreach host... (2 Replies)
Discussion started by: earnstaf
2 Replies

9. Shell Programming and Scripting

Expect with tcl/tk

hai all, i have an tcl script in which i have been reading the DUT Command prompt of an cisco switch as DUT Command Prompt : cisco* and running the test case of stp now the problem is if i have given any blank space in between the cisco or at the startup then the Expect is not identifying the... (0 Replies)
Discussion started by: sanjustudy
0 Replies
Login or Register to Ask a Question