Python3, MariaDB, OpenVPN Password Check fails - python

os.eviron['username'] is sent from OpenVPN, but for debugging I changed it to "test" as user in the Database.
os.eviron['password'] is sent from OpenVPN, but for debugging I changed it to the working password "password", and everything worked as designed.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import mysql.connector as database
import sys
import hashlib
from config import DB_NAME, DB_ADMIN, DB_PASSWORD, DB_HOST, HASH_ALGORITHM, HASH_SALTY
connection = database.connect(
user=DB_ADMIN,
password=DB_PASSWORD,
host=DB_HOST,
database=DB_NAME
)
cursor = connection.cursor()
hash_func = getattr(hashlib, HASH_ALGORITHM)
salty = hash_func(HASH_SALTY.encode("utf-8")).hexdigest()
ovpnuser = (os.environ['username'])
ovpnuser = "SELECT * FROM users WHERE usernames = '" + ovpnuser + "';"
cursor.execute(ovpnuser)
result = cursor.fetchone()
if result is None:
sys.exit(1)
id, usernames, passwords = result
passw = (os.environ['password'] + salty) #Salt this mofo
if hash_func(passw.encode("utf-8")).hexdigest() != passwords:
sys.exit(1)
sys.exit(0)
Now that I use OpenVPN to call this plugin as you see it now, it returns sys.exit(1) Failed to authenticate. I've tried to debug it, but I can't get ovpn to print and errors from connections or calls to this plugin. I even added echo to write to a log file in the python code, and it didn't work.
Any thoughts?

Related

How to pass the value of the variable in db connect string in python

Below is my config.py file
ABC_TEST01_JJ = {"username" : 'NONE',"password" : 'NINU', "dsn" : 'ABC_TEST01_JJ', "port" : 1512, "encoding" : 'UTF-8'}
and this my python test.py script
import cx_Oracle
import config
connection = None
try:
env = input("Enter Environment name : ")
connection = cx_Oracle.connect(
config.format(env)["username"],
config.format(env)["password"],
config.format(env)["dsn"],
encoding=config.format(env)["encoding"])
# show the version of the Oracle Database
print(connection.version)
except cx_Oracle.Error as error:
print(error)
finally:
# release the connection
if connection:
connection.close()
I want to provide the env name as a prompt value and that value will go to config.env["username"] and it will pull all values from the config file but the issue is it is not taking the value of env name in config.format(env)["username"]. Not sure how to pass the value of variable env to there?
Import isn't for text files, see importing external ".txt" file in python
You could try something like:
conf.ini:
[Dev Site]
username = NONE
password = NINU
dsn = ABC_TEST01_JJ
port = 1512
encoding = UTF-8
[CJ]
username = cj
password = cj
dsn = localhost/orclpdb1
port = 1521
encoding = UTF-8
and use it like this in Python 3 (the module names are different in Python 2):
import cx_Oracle
from configparser import ConfigParser
parser = ConfigParser()
parser.read('conf.ini')
try:
env = input("Enter Environment name : ") or 'Dev Site'
print(env)
username = parser.get(env, 'username')
password = parser.get(env, 'password')
dsn = parser.get(env, 'dsn')
encoding = parser.get(env, 'encoding')
connection = cx_Oracle.connect(username, password, dsn, encoding=encoding)
# show the version of the Oracle Database
print(connection.version)
except cx_Oracle.Error as error:
print(error)
finally:
# release the connection
if connection:
connection.close()
Output is like:
$ python test.py
Enter Environment name : CJ
CJ
19.3.0.0.0
If you want to access environment variables instead of using a config file, you can do something like:
import os
connection = cx_Oracle.Connection(os.environ.get("PYTHON_USERNAME"),
os.environ.get("PYTHON_PASSWORD"), os.environ.get("PYTHON_CONNECTSTRING"))

How to make Python automatically allow port through Windows firewall

I have an FTP server which I would like to be able to send to my personal Windows 10 computers stationed around my area (different IPs) to access files, and in order to access them, I need to allow the ports through the firewalls. Instead of doing this, is there any way to have my Python program use some other port that doesn't need to bypass the firewall OR bypass the firewall altogether?
Server.py
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import urllib.request
import mysql.connector
sqlpass = ""
version = "1.3"
def ftp_main():
mydb = mysql.connector.connect(
host="",
port="3306",
user="",
passwd=sqlpass,
database=""
)
mycursor = mydb.cursor()
mycursor.execute("SELECT Username, Password FROM FtpInfo")
myresult = mycursor.fetchall()
Username, Password = myresult[0]
print(Username + " " + Password)
external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')
print(external_ip)
authorizer = DummyAuthorizer()
# Define a new user having full r/w permissions and a read-only
# anonymous user
authorizer.add_user(Username, Password, '.', perm='elradfmwMT')
authorizer.add_anonymous('.')
# Instantiate FTP handler class
handler = FTPHandler
handler.authorizer = authorizer
handler.masquerade_address = external_ip
handler.passive_ports = range(60000, 60999)
# Define a customized banner (string returned when client connects)
handler.banner = "FTP Server v" + version
address = ('', 1000)
server = FTPServer(address, handler)
# start ftp server
server.serve_forever()
ftp_main()
I'm not aware of any native Python way to configure Windows firewall.
Though you can simply execute Windows netsh command from Python using os.system.
See How to open ports on Windows firewall through batch file.

Issues with python script

I have run into another problem now, with below given code i am unable to login, it still says Access is Denied, even though the username and password is correct .No errors on the console. Looks like i am missing something after the connection.
All i am trying to do here is modify the TODO section so that it runs the computed query against my Oracle database after connecting and a successful login, it should show the results from permissions table.
import cgi
import cx_Oracle
print("Content-type: text/html\n")
print("<title>Test</title>")
print("<body><center>")
try:
# get post data
form = cgi.FieldStorage()
name = form['name'].value if 'name' in form else ''
pwd = form['pwd'].value if 'pwd' in form else ''
permissions = []
# query to check password and get permissions
query = "SELECT PERMISSIONS FROM USERS WHERE NAME='{}' and PWD='{}'".format(name, pwd)
# TODO: connect to database and run query
host = '123.abc.com'
port = 1521
SID = 'orcl'
dsn_tns = cx_Oracle.makedsn(host, port, SID)
connection = cx_Oracle.connect('abuser', 'userpass', dsn_tns)
curs = connection.cursor()
result = curs.execute(query)
# TODO section ends
if len(permissions) > 0:
print("<H1>Access granted. You have the following permissions: {}.</H1>".format(permissions[0][0]))
else:
print("<H1>Access denied.</H1>")
connection.close()
except cx_Oracle.DatabaseError as e:
# for ease of debugging
print("Database Error: {}".format(e))
print("<br>Query: {}".format(query))
print("""
<form action="../login.html" method="GET">
<input type="submit" value="Back to Login">
</form>
""")
print('</center></body>')
Your indent is too great starting on line 36 (I guess you uploaded partial source code), where it starts host =
There is an extra indent in the line starting with host. Indents in Python usually follow the :. The below code should fix the indentation error that you are getting. More about this here - http://www.diveintopython.net/getting_to_know_python/indenting_code.html
import cgi
import cx_Oracle
print("Content-type: text/html\n")
print("<title>Test</title>")
print("<body><center>")
try:
# get post data
form = cgi.FieldStorage()
name = form['name'].value if 'name' in form else ''
pwd = form['pwd'].value if 'pwd' in form else ''
permissions = []
# query to check password and get permissions
query = "select permissions from users where name='{}' and pwd='{}'".format(name, pwd)
# Connect to database and run query
host = '123.abc.com'
port = 1521
SID = 'orcl'
dsn_tns = cx_Oracle.makedsn(host, port, SID)
connection = cx_Oracle.connect('abcuser', 'abcuserpassword', dsn_tns)
results = connection.execute(query)
# TODO section ends
if len(permissions) > 0:
print("<H1>Access granted. You have the following permissions: {}.</H1>".format(permissions[0][0]))
else:
print("<H1>Access denied.</H1>")
except cx_Oracle.DatabaseError as e:
# for ease of debugging
print("Database Error: {}".format(e))
print("<br>Query: {}".format(query))

Torndb (ERROR:root:Error connecting to MySQL on localhost)

I'm attempting to develop a web app using tornado/torndb and am running into some issues with my database interactions. I've written a "Database" class which wraps torndb in order to provide some common database functionality for my web app. When invoking any of the methods from the Database class I've written there seems to be a problem with the connection to the database:
"ERROR:root:Error connecting to MySQL on localhost"
My constructor opens the connection so I'm a bit confused as to why I see this message after the connection has been opened. I expect this is a scoping and/or GC issue that I am not understanding. The goal is to to create the Database object once and thus just have that
single connection persist throughout the life of the server, the db is stored
The following code snippet does work as expected which led me to the scoping or GC issue possibly:
#!/usr/bin/python
import torndb
class Database:
def __init__(self):
try:
self.__dbh = torndb.Connection(
'localhost',
'mydb',
user = 'myuser',
password = 'mypass')
except Exception as e:
print e
def user_add(self, user, email, passwd):
insert = "INSERT INTO users (username, email, passwd) VALUES " + \
"(%s, %s, %s)" % (user, email, passwd)
rowid = 0
try:
rowid = self.__dbh.execute(insert)
except Exception as e:
print e
if rowid is 0:
return (False, 'User exists');
return (True, None)
if __name__ == "__main__":
print 'Testing'
raw_input('Hit enter to connect to the DB')
d = Database();
users = []
raw_input('Hit enter to create some users')
for i in range(5):
users.append(str(i))
d.user_add(users[i], users[i], users[i])
<- snip ->
The issue is when I try to create a Database object from anywhere other than the main of the module that defines the Database class, for example:
import tornado.ioloop
import tornado.httpserver
import tornado.web
from register import Register
from logon import Logon
from db import Database
class Application(tornado.web.Application):
def __init__(self):
resources = [
(r"/logon", Logon),
(r"/register", Register)
]
self.db = Database()
tornado.web.Application.__init__(self, resources)
try:
self.db.user_add('testuser', 'testemail', 'password')
except Exception as e:
print e
if __name__ == "__main__":
app = Application()
# Start the server.
server = tornado.httpserver.HTTPServer(app)
server.listen(8080)
tornado.ioloop.IOLoop.instance().start()
The above when executed prints (due to the call to self.__dbh.execute()):
ERROR:root:Error connecting to MySQL on localhost
Some other bits of information:
I can connect to the db from the console without any issues.
I'm following this example https://github.com/facebook/tornado/blob/master/demos/blog/blog.py#L60
torndb version is 2.4.1, torndb version is LATEST (pulled using pip).
Questions:
Why is there a difference when I create my Database object in the main of the module that defines the class compared to creating the Database object anywhere else?
The problem was due to the string arguments passed to the query not being escaped, with the following change it works:
def user_add(self, user, email, passwd):
insert = "INSERT INTO users (username, email, passwd) VALUES " + \
"(\'%s\', \'%s\', \'%s\')" % (user, email, passwd)
rowid = 0
try:
rowid = self.__dbh.execute(insert)
except Exception as e:
print e
if rowid is 0:
return (False, 'User exists');
return (True, None)

POSTGRESQL: Connect remote server to host database with Python

Using Python/Psycopg2/PopstgreSQL and Cron.
I'd like to take remote server information(see below) and add it into a PostGreSQL database on the host computer.
Using #!/usr/bin/python
import socket
import commands
import string
import os
hostname = socket.gethostname()
print hostname
ip = commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]
print ip
os = commands.getoutput("lsb_release -d")
print os[13:34]
kernel = commands.getoutput("uname -p")
print kernel
reboot = commands.getoutput("who -b")
print reboot[22:38]
This is the 'connect to database' script:
#!/usr/bin/python
import psycopg2
import sys
try:
conn = psycopg2.connect('host=*** dbname=*** user=*** password=***')
print "Connected to Database"
except:
print "No Connection"
cur = conn.cursor()#cursor_factory=psycopg2.extras.DictCursor)
try:
cur.execute('SELECT * FROM new')
rows = cur.fetchall()
print "\n Show: \n"
for row in rows:
print " ", row
except:
print "Not Working"
I'm able to connect, I'm able to pull the data. I need to combine the two scripts and insert the returned information into the database.
Your local python script would have these lines:
import psycopg2 as db
remote_connection = db.connect('host=that_host dbname=that_db user=user password=pwd')
local_connection = db.connect('host=localhost dbname=local_db user=user password=pwd')

Categories

Resources