Python IMAP proxy connection - python

I tried to login to IMAP5 server through a SOCKS5 proxy using python 3.5, but it doesn't login and shows this error:
command: LOGIN => Autologout internal error, we will remember you as ffcd2fca-96a9-4c64-89d5-361123783232
If i am not using proxy, then everything is ok.
I have some questions
1.Is it because of the proxy server and it forbids IMAP4 connection?
2.How can I solve that?
import ssl, time
from socks import create_connection
from socks import PROXY_TYPE_SOCKS4
from socks import PROXY_TYPE_SOCKS5
from socks import PROXY_TYPE_HTTP
from imaplib import IMAP4
from imaplib import IMAP4_PORT
from imaplib import IMAP4_SSL_PORT
from filter import get_user_pass
__author__ = "sstevan"
__license__ = "GPLv3"
__version__ = "0.1"
class SocksIMAP4(IMAP4):
"""
IMAP service trough SOCKS proxy. PySocks module required.
"""
PROXY_TYPES = {"socks4": PROXY_TYPE_SOCKS4,
"socks5": PROXY_TYPE_SOCKS5,
"http": PROXY_TYPE_HTTP}
def __init__(self, host, port=IMAP4_PORT, proxy_addr=None, proxy_port=None,
rdns=True, username=None, password=None, proxy_type="socks5"):
self.proxy_addr = proxy_addr
self.proxy_port = proxy_port
self.rdns = rdns
self.username = username
self.password = password
self.proxy_type = SocksIMAP4.PROXY_TYPES[proxy_type.lower()]
IMAP4.__init__(self, host, port)
def _create_socket(self):
return create_connection((self.host, self.port), proxy_type=self.proxy_type, proxy_addr=self.proxy_addr,
proxy_port=self.proxy_port, proxy_rdns=self.rdns, proxy_username=self.username,
proxy_password=self.password)
class SocksIMAP4SSL(SocksIMAP4):
def __init__(self, host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None, proxy_addr=None,
proxy_port=None, rdns=True, username=None, password=None, proxy_type="socks5"):
if ssl_context is not None and keyfile is not None:
raise ValueError("ssl_context and keyfile arguments are mutually "
"exclusive")
if ssl_context is not None and certfile is not None:
raise ValueError("ssl_context and certfile arguments are mutually "
"exclusive")
self.keyfile = keyfile
self.certfile = certfile
if ssl_context is None:
ssl_context = ssl._create_stdlib_context(certfile=certfile,
keyfile=keyfile)
self.ssl_context = ssl_context
SocksIMAP4.__init__(self, host, port, proxy_addr=proxy_addr, proxy_port=proxy_port,
rdns=rdns, username=username, password=password, proxy_type=proxy_type)
def _create_socket(self):
sock = SocksIMAP4._create_socket(self)
server_hostname = self.host if ssl.HAS_SNI else None
return self.ssl_context.wrap_socket(sock, server_hostname=server_hostname)
def open(self, host='', port=IMAP4_PORT):
SocksIMAP4.open(self, host, port)
def connect_proxy(imap_server, imap_port, proxy_addr, proxy_port, proxy_type, email, password):
mailbox = SocksIMAP4SSL(host=imap_server, port=imap_port,
proxy_addr=proxy_addr, proxy_port=proxy_port, proxy_type=proxy_type)
try:
mailbox.login(email, password)
print("We are here")
print("OK ",)
except Exception as e:
print(e)
return False
print(mailbox.state)
mailbox.logout()
return True
if __name__ == "__main__":
imap_server = "imap.rambler.ru"
imap_port = 993
proxy_addr = "188.120.224.172"
proxy_port = 59923
proxy_type = "socks5"
email, password = get_user_pass("pm#mail11.rambler.ru:11")
if email is not None:
resp = connect_proxy(imap_server, imap_port, proxy_addr, proxy_port, proxy_type, email, password)
#resp = connect(email, password, "smtp.rambler.ru")
time.sleep(1)
EMAIL:PASSWORD pair is for test. Don't steal it:)

As I understood it was either Rambler's bug or a tiny feature to prevent some malicious users, like I am, from brute forcing accounts.
If anyone would ever see this thread and have some solutions, ideas or such problem, feel free to contact me.

Related

Unexpected indentation when return in python

when I try to return but I got an error in 2nd return signup_result & return login_result
https://github.com/microsoft/pyright/blob/main/docs/configuration.md#reportUndefinedVariable
"return" can be used only within a functionPylance
here is utils.py
class CognitoResponse(object):
def __init__(self, access_token, refresh_token, cognito_user_id=None):
self.access_token = access_token
self.refresh_token = refresh_token
self.cognito_user_id = cognito_user_id
def cognito_signup(username: str, password: str):
return signup_result
# In order to get the ID and authenticate, use AWS Cognito
client = boto3.client('cognito-idp', region_name=os.environ.get('COGNITO_REGION_NAME'))
try:
response = client.sign_up(
ClientId=os.environ.get('COGNITO_USER_CLIENT_ID'),
Username=username,
Password=password
)
except Exception as e: # Generally, will trigger upon non-unique email
raise HTTPException(status_code=400, detail=f"{e}")
user_sub = response['UserSub']
# This will confirm user registration as an admin without a confirmation code
client.admin_confirm_sign_up(
UserPoolId=os.environ.get('USER_POOL_ID'),
Username=username,
)
# Now authenticate the user and return the tokens
auth_response = client.initiate_auth(
ClientId=os.environ.get('COGNITO_USER_CLIENT_ID'),
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username,
'PASSWORD': password
}
)
access_token = auth_response['AuthenticationResult']['AccessToken']
refresh_token = auth_response['AuthenticationResult']['RefreshToken']
signup_result = utils.CognitoResponse(
access_token=access_token,
refresh_token=refresh_token,
cognito_user_id=user_sub
)
return signup_result
def cognito_login(username: str, password: str):
return login_result
client = boto3.client('cognito-idp', region_name=os.environ.get('COGNITO_REGION_NAME'))
# Authenticate the user and return the tokens
try:
auth_response = client.initiate_auth(
ClientId=os.environ.get('COGNITO_USER_CLIENT_ID'),
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username,
'PASSWORD': password
}
)
except Exception as e: # Generally, will trigger upon wrong email/password
raise HTTPException(status_code=400, detail=f"{e}")
access_token = auth_response['AuthenticationResult']['AccessToken']
refresh_token = auth_response['AuthenticationResult']['RefreshToken']
login_result = utils.CognitoResponse(
access_token=access_token,
refresh_token=refresh_token
)
return login_result
I also try to tab 2 times to avoid indentation error in return signup_result & return login_result but still got the same error Unexpected indentationPylance
def cognito_login(username: str, password: str):
return login_result
client = boto3.client('cognito-idp', region_name=os.environ.get('COGNITO_REGION_NAME'))
# Authenticate the user and return the tokens
try:
auth_response = client.initiate_auth(
ClientId=os.environ.get('COGNITO_USER_CLIENT_ID'),
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username,
'PASSWORD': password
}
)
# lots more code...
The cognito_login() function contains only one line of code return login_result because that is the only code that is indented underneath the function.
The rest of the following code is not indented underneath the function, therefore it is not part of the function.
Indentation is very important in Python.
Your code should likely be formatted as follows:
def cognito_login(username: str, password: str):
#return login_result remove this as the next lines of code need to run
client = boto3.client('cognito-idp', region_name=os.environ.get('COGNITO_REGION_NAME'))
# Authenticate the user and return the tokens
try:
auth_response = client.initiate_auth(
ClientId=os.environ.get('COGNITO_USER_CLIENT_ID'),
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username,
'PASSWORD': password
}
)
# lots more code...

Assert multiple methods being called, only constructor works

I'm trying to test the following function
def send_mail(config, message, raw_object):
smtp_config = config['handlers']['smtp']
session = smtplib.SMTP(smtp_config['host'], smtp_config['port'])
if smtp_config['tls']:
session.starttls()
session.login(smtp_config['from'], smtp_config['password'])
for to in smtp_config['to']:
mail = MIMEMultipart()
mail['From'] = smtp_config['from']
mail['To'] = to
mail['Subject'] = message
body = yaml.safe_dump(raw_object)
mail.attach(MIMEText(body, 'plain'))
try:
session.sendmail(smtp_config['from'], to, mail.as_string())
logging.info(f"Handler:SMTP {to}: {message}")
except smtplib.SMTPException as exc:
logging.error("SMTPException:")
logging.error(exc)
session.quit()
I have the following test
from unittest import TestCase
from unittest.mock import patch
from kubewatcher.handlers import send_mail
class Test(TestCase):
#patch("smtplib.SMTP")
def test_handle__send_mail(self, smtp):
from_ = "from"
password = "password"
host = "host"
port = 587
tls = True
to = ["to"]
config = {
"handlers": {
"smtp": {
"from": from_,
"password": password,
"host": host,
"port": port,
"tls": tls,
"to": to
}
}
}
message = "message"
raw_object = {}
send_mail(config, message, raw_object)
smtp.assert_called_once_with(host, port)
smtp.starttls.assert_called_once()
smtp.login.assert_called_once_with(from_, password)
The first assertion, smtp.assert_called_once_with(host, port), works just fine. But the entire test fails with the following error
...
AssertionError: Expected 'starttls' to have been called once. Called 0 times.
Here's the code you're testing:
session = smtplib.SMTP(smtp_config['host'], smtp_config['port'])
if smtp_config['tls']:
session.starttls()
session.login(smtp_config['from'], smtp_config['password'])
This test is working:
smtp = patch("smtplib.SMTP") # Sorta; this is just shorthand
smtp.assert_called_once_with(host, port)
The problem is here:
smtp.starttls.assert_called_once()
But it's actually correct for it to fail. Your code isn't calling smtplib.SMTP.starttls, but session.starttls, which is the thing that smtplib.SMTP returns.
You can work around that with something like:
from unittest.mock import patch, Mock
mock_session = Mock() # This is the thing we'll be inspecting later
smtp.return_value = mock_session # `smtplib.SMTP` will return this object
send_mail(config, message, raw_object)
smtp.assert_called_once_with(host, port)
mock_session.starttls.assert_called_once()
mock_session.login.assert_called_once_with(from_, password)

Getting "Invalid server address" error while trying to fetch from Windows Server 2012 r2

I want to fetch user details from Active Directory of Windows Server 2012 r2 from Python Scripting... This code is showing Invalid server address. Any ideas?
import sys
from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES,
AUTO_BIND_NO_TLS, SUBTREE
from ldap3.core.exceptions import LDAPCursorError
server_name = 'MyServerName'
domain_name = 'MyDomainName'
user_name = 'MyName'
password = 'MyPassword'
format_string = '{:25} {:>6} {:19} {:19} {}'
print(format_string.format('Users', 'Logins', 'Last Login', 'Expires', 'Description'))
server = Server(server_name, get_info=ALL)
conn = Connection(server, user='{}\\{}'.format(domain_name, user_name), password=password, authentication=NTLM,auto_bind=True)
print(conn.result)
conn.search('dc={},dc=com'.format(domain_name), '(objectclass=User)',attributes=[ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES])
for e in conn.entries:
try:
desc = e.description
except LDAPCursorError:
desc = ""
print(format_string.format(str(e.name), str(e.logonCount), str(e.lastLogon)[:19], str(e.accountExpires)[:19], desc))

ImapLib get gmail id mail(python)

Sorry for my english. For example i have link like this
https://mail.google.com/mail/u/0/?source=sync&tf=1&view=pt&th=1614fcf57d5cb6ec1&search=all
where 1614fcf57d5cb6ec1 it uuid message. By this link i can view pdf mail. For work with mail i use imaplib. I try get this uuid gmail message like this:
mail.get('Message-id')
but it give me id like this: 3CB8978E-60DD-41B1-AA2E-0685219513F3#happyplugs.com
My question: Hav i can get id gmail message use imaplib?
UPD:
IMAP_SERVER = 'imap.gmail.com'
IMAP_PORT = '993'
IMAP_USE_SSL = True
def __init__(self):
print("MailBox __init__")
self.user = '123#gmail.com'
self.password = '123'
if IMAP_USE_SSL:
self.imap = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
else:
self.imap = imaplib.IMAP4(IMAP_SERVER, IMAP_PORT)
def __enter__(self):
print("MailBox __enter__")
self.imap.login(self.user, self.password)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.imap.close()
self.imap.logout()
def get_google_id():
self.imap.select('Inbox')
status, response = self.imap.search(None, 'ALL')
if status == 'OK':
items = response[0].split()
for email_id in reversed(items):
status, response = self.imap.fetch(email_id, "(RFC822)")
if status == 'OK':
email_body = response[0][1]
mail = email.message_from_bytes(email_body)
id_mess = mail.get('Message-id') //this give me not gmail mail id
imaplib has a separate set of functions to operate on IMAP UIDs.
status, response = self.imap.uid('search', None, "ALL")
for uid in reversed(response[0].split()):
status, response = self.imap.uid('fetch', uid, '(RFC822)')

Instantiating geopy.geocoders.GoogleV3 with proxies causes exception

I am trying to call GoogleV3 geolocator like this:
geolocator = GoogleV3(proxies={"http": "http://user:password#ip:port"})
address, (latitude, longitude) = geolocator.geocode('address to geocode')
and it raises:
AttributeError: OpenerDirector instance has no __call__ method
What am I doing wrong? How to fix it?
It is not possible in current implementation of GoogleV3 to pass user and password variables directly to urllib2.opener (GoogleV3 uses urllib2 behind the scenes).
Here is example how urllib2.opener should be called:
proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:
opener.open('http://www.example.com/login.html')
Sadly, but current GoogleV3 implementation does not use urllib2.ProxyBasicAuthHandler .
So, you need to extend it by modifying source: https://github.com/geopy/geopy/blob/master/geopy/geocoders/base.py
On the top add:
from urlparse import urlparse
then find 'if self.proxies is None:' code and replace it with:
if self.proxies is None:
self.urlopen = urllib_urlopen
else:
params = urlparse(proxies[1])
host = params.get('hostname')
username = params.get('username')
password = params.get('password')
if host and username and password:
proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
proxy_auth_handler.add_password(None, host, username, password)
self.urlopen = build_opener(
ProxyHandler(self.proxies, proxy_auth_handler),
)

Categories