Perl // Python General discussions about Perl and Python.

InterN0T Affiliates:
EvilZonepy1337

SirCapsAlot.NET

Reply
 
LinkBack Thread Tools Display Modes
  #1  
Old 4th February 2010, 22:33
irenicus09's Avatar
 
Join Date: Dec 2009
Location: United Nations (:
Posts: 63
Rep Power: 3
Reputation: 14
irenicus09 is on the way to become something
[Python] User Management System (New!)

Hi guys! Last night I started coding in python & ended up creating a simple user management system....its not that polished/complete yet...more features like reading & writing files, m5 encryption could have been implemented...but due to lack of time I couldn't implement those features in it....btw I consider myself a beginner in python....so this is great progress for me :)

Code:
#! /usr/bin/env python
#Author: 1R3N1CU5

import sys, os, time
from hashlib import md5


class user_management():

    def __init__(self, user="", pw="", set_user="", set_pw="", database={}, choice=""):
      self.user = user
      self.pw = pw
      self.database = database
      self.choice = choice
      self.set_user = set_user
      self.set_pw = set_pw
       
    
    
    
    def clear(self):    #Clears Screen
        if os.name in ['nt', 'win32', 'dos']:
            os.system('cls')
        else:
            os.system('clear')

    
    def menu(self):     #Prints Menu
        print '\n'
        print '-'*50
        print 'Please Select:\n'
        print '-'*50
        print '1) Register User'
        print '2) Login'
        print '3) Exit'
        print '='*50,'\n\n'
      
  
  

    def select(self):   #Main Function of the class. User Selects Option.
        while True:
            self.menu()
            try:
                self.choice = raw_input ('You Entered: ').strip()
            except (KeyboardInterrupt, IOError):
                print '\nAborted! Exiting..'
                time.sleep(2)
                break
      
            if (self.choice in '123'):
                if (self.choice == '1'):
                    self.clear()
                    self.register()
                    self.clear()
                    print '\n'
                    print '*'*50
                    print 'New User Successfully Registered!'
                    print '^'*50
                    
                elif (self.choice == '2'):
                    self.clear()
                    self.error_chk()
                elif (self.choice == '3'):
                    self.clear()
                    self.roll_credits()
                    break
            else:
                self.clear()
                print 'Invalid Input! Try Again..\n\n'
  

    def register(self):     #Registers New User
        self.set_user = (raw_input ('Please Enter User Name: ')).strip()
        self.set_pw = (raw_input ('\nPlease Enter Password %s: ' % (self.set_user))).strip()
        self.data_entry(self.set_user, self.set_pw)

  
    def data_entry(self, set_user, set_pw):     #Stores User Data
        self.user = set_user
        self.pw = set_pw
        self.database = {self.user:self.pw}
        return self.database


    def error_chk(self):    #Checks whether User is Authorised
        name = raw_input('Enter Username: ').strip()
        password = raw_input('Enter Password: ').strip()
        while True:
            if (name in self.database.keys()):
                print ('Username Valid! Checking Password for %s..' % (name))
                time.sleep(2)
                if (password == self.database[name]):
                    print '[+] Access Granted!'
                    self.login()
                    break
                else:
                    print 'Password Incorrect!\n'
                    print 'Returning to Main Menu..'
                    time.sleep(2)
                    self.clear()
                    break
            else:
                print '[-] Acess Denied!\n'
                break


    def login(self):
        print '\nFeature not implemented yet!\n\n'
        print 'Returning to Main Menu..'
        time.sleep(2)
        


    def roll_credits(self):
        print '\n\t', '-'*50, '\n\tQuitting...', '\n\t', '-'*50
        print '\n\tGot Suggestions? Bugs? Email me at : '
        print '\n\tirenicus_timberlake@yahoo.com \n'
        print '\t','='*50
        time.sleep(3)
        

  
if __name__ == '__main__':
    global mng
    mng = user_management()
    mng.select()
Special thanks to S3myon for helping me from the start, & his coding techniques inspired & helped me learn a lot!
Reply With Quote
  #2  
Old 5th February 2010, 10:13
s3my0n's Avatar
InterN0T Crew
 
Join Date: Sep 2009
Location: /home/s3my0n/
Posts: 373
Blog Entries: 3
Rep Power: 8
Reputation: 227
s3my0n has made his way up the systems3my0n has made his way up the systems3my0n has made his way up the system
Re: [Python] User Management System (New!)

Nice brave start in OOP but the way you used classes are a bit wrong ^^

I'll edit your code a bit. Just one note please remember that variables passed to __init__ are passed in when you invoke the class.

If you set for functions to recieve variable then please make sure that that function recieves those variables. In your above example you didn't pass anything to function __init__().

mng = user_management() invokes the class.

use this:
class user_management(object):

Try this in IDLE to understand how classes work:

Code:
IDLE 2.6.4      ==== No Subprocess ====
>>> class Manager(object):
    def __init__(self, name, password):
        self.name = name
        self.password = password
        print '\n Created instance for %s' % self.name
    def updatePass(self, newpass):
        self.password = newpass
        print '\n Updated password for %s' % self.name

        
>>> jack = Manager()
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    jack = Manager()
TypeError: __init__() takes exactly 3 arguments (1 given)
>>> jack = Manager('jack', 'myweakpass')

 Created instance for jack
>>> jack.name
'jack'
>>> jack.password
'myweakpass'
>>> aria = Manager('aria', 'str0ng3rp4ss')

 Created instance for aria
>>> aria.password
'str0ng3rp4ss'
>>> aria.updatePass('h4ck3d')

 Updated password for aria
>>> aria.password
'h4ck3d'
>>>
__________________
Quote:
Computers are incredibly fast, accurate, and stupid; humans are incredibly slow, inaccurate and brilliant; together they are powerful beyond imagination.
-Albert Einstein
Reply With Quote
  #3  
Old 5th February 2010, 11:29
MaXe's Avatar
Studying shellcode..
 
Join Date: Jun 2008
Location: Sweden - Ljusdal
Posts: 3,404
Blog Entries: 36
Rep Power: 10
Reputation: 198
MaXe has made his way up the systemMaXe has made his way up the system
Re: [Python] User Management System (New!)

Very cool, however where is the user data stored? Is it a file-based database which I
think it is, or is it a real database that it uses? I am just wondering since I'm not expert ;-)
__________________

Quote:
Originally Posted by Norph
MaXe, I really doubt that you are able to browse ANY site more than 2 minutes before you start pwning it xD
Reply With Quote
  #4  
Old 5th February 2010, 11:49
s3my0n's Avatar
InterN0T Crew
 
Join Date: Sep 2009
Location: /home/s3my0n/
Posts: 373
Blog Entries: 3
Rep Power: 8
Reputation: 227
s3my0n has made his way up the systems3my0n has made his way up the systems3my0n has made his way up the system
Re: [Python] User Management System (New!)

Quote:
Originally Posted by MaXe View Post
Very cool, however where is the user data stored? Is it a file-based database which I
think it is, or is it a real database that it uses? I am just wondering since I'm not expert ;-)
At the moment the user data is stored in ram, not written on the harddrive, so when the program exits all the data will be lost.
__________________
Quote:
Computers are incredibly fast, accurate, and stupid; humans are incredibly slow, inaccurate and brilliant; together they are powerful beyond imagination.
-Albert Einstein
Reply With Quote
  #5  
Old 5th February 2010, 11:51
irenicus09's Avatar
 
Join Date: Dec 2009
Location: United Nations (:
Posts: 63
Rep Power: 3
Reputation: 14
irenicus09 is on the way to become something
Re: [Python] User Management System (New!)

Thanks for the advice S3myon, I got some brief idea about what u meant....which is to not use extra variables to update, but rather make the update function do it automatically.. I'd understand OOP better if u'd modify my code in ur spare time ^^

@ Maxe: It holds the database in virtual memory...soon I hope to make it store all that data & verify users from files stored earlier!
Reply With Quote
  #6  
Old 5th February 2010, 12:51
MaXe's Avatar
Studying shellcode..
 
Join Date: Jun 2008
Location: Sweden - Ljusdal
Posts: 3,404
Blog Entries: 36
Rep Power: 10
Reputation: 198
MaXe has made his way up the systemMaXe has made his way up the system
Re: [Python] User Management System (New!)

Quote:
Originally Posted by s3my0n View Post
At the moment the user data is stored in ram, not written on the harddrive, so when the program exits all the data will be lost.
Well it's some nice code but it is pretty much useless then No offence intended

@irenicus90: Make sure to encrypt the files if it's possible. (best security coding practice)
__________________

Quote:
Originally Posted by Norph
MaXe, I really doubt that you are able to browse ANY site more than 2 minutes before you start pwning it xD
Reply With Quote
  #7  
Old 5th February 2010, 15:35
s3my0n's Avatar
InterN0T Crew
 
Join Date: Sep 2009
Location: /home/s3my0n/
Posts: 373
Blog Entries: 3
Rep Power: 8
Reputation: 227
s3my0n has made his way up the systems3my0n has made his way up the systems3my0n has made his way up the system
Re: [Python] User Management System (New!)

Here you go:

Code:
http://forum.intern0t.net/perl-python/2225-python-login-system-md5-encryption.html
I hope the comments will explain it a bit more, if you are still not sure about anything just ask ;)
__________________
Quote:
Computers are incredibly fast, accurate, and stupid; humans are incredibly slow, inaccurate and brilliant; together they are powerful beyond imagination.
-Albert Einstein
Reply With Quote
  #8  
Old 7th February 2010, 18:52
irenicus09's Avatar
 
Join Date: Dec 2009
Location: United Nations (:
Posts: 63
Rep Power: 3
Reputation: 14
irenicus09 is on the way to become something
Re: [Python] User Management System (New!)

Hi guys, I've finally completed the next version of the user management system I posted previously, it is quite similar to S3myon's program, but there are a few minor differences..
The program auto loads the database at start from current directory & uses SHA-512 encryption mechanism instead of MD5. You don't have to specify any directories or anything as long as the user_data.txt file is in the current directory (even if there's no user_data.txt file it will work). The program itself is kind of resistant to bruteforce attacks since program execution pauses for a few seconds due to invalid login... the program is very user friendly, it's fool proof, noob proof, error proof u just cant make it crash unless u break ur computer/pull the plug!


Code:
#! /usr/bin/env python
#Author: 1R3N1CU5
#Special Thanks to S3myon!

import sys, os, time
from hashlib import sha512


class user_management():

    def __init__(self, database={}, choice=""):
      self.database = database
      self.choice = choice
      self.title()
      self.initial_check()
      

    
    def clear(self):    # Clears Screen
        if os.name in ['nt', 'win32', 'dos']:
            os.system('cls')
        else:
            os.system('clear')



    def title(self):    # Title function prints welcome screen.
        self.clear()
        print'\t    ___________________________________________'
        print'\t   |                                           |'
        print'\t   |  Welcome To Account Manager Version 1.1   |'
        print'\t   |                                           |'
        print'\t   |                                           |'
        print'\t   |       Copyright 2010 (c) by 1R3N1CU5      |'
        print'\t   |                                           |'
        print'\t   |                                           |'
        print'\t   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^'
        print'\n\n\n'
        time.sleep(3)
        self.clear()

    
    
    def menu(self):     # Prints Menu
        print '\n'
        print '-'*50
        print 'Please Select:\n'
        print '-'*50
        print '1) [Register New User]'
        print '2) [View Registered Accounts]'
        print '3) [Login]'
        print '4) [Exit]'
        print '='*50,'\n\n'
      

  
    def select(self):   # Main Function of the class. User Selects Option.
        while True:
            self.menu()
            try:
                self.choice = raw_input ('You Entered: ').strip()
            except (KeyboardInterrupt, IOError):
                print '\nAborted! Exiting..'
                time.sleep(2)
                break
            if (self.choice in '1234'):
                if (self.choice == '1'):
                    self.clear()
                    self.register()
                elif (self.choice == '2'):
                    self.clear()
                    self.data_check()
                    self.clear()
                elif (self.choice == '3'):
                    self.clear()
                    self.error_chk()
                    self.clear()
                elif (self.choice == '4'):
                    self.roll_credits()
                    break
                elif (self.choice == ''):
                    self.clear()
                    print '[Invalid Input! Try Again..]\n'    
            else:
                self.clear()
                print '[Invalid Input! Try Again..]\n'
  


    def register(self):     # Registers New User
        try:
            while True:
                print '^'*50
                print 'Welcome To User Registration!'
                print '*'*50
                print '\n\n'
                set_user = (raw_input ('Please Enter User Name: ')).strip()
                if (self.database.has_key(set_user) == True):
                    print '\n\n'
                    print '^'*50
                    print '\n\t\t[User Already Registered]\n'
                    print '='*50
                    time.sleep(2)
                    self.clear()
                    continue
                elif (set_user == ""):
                    print '\n\n'
                    print '^'*50
                    print '\n\t\t[Invalid Username]\n'
                    print '='*50
                    time.sleep(1)
                    self.clear()
                    continue
                else:       
                    set_pw = (raw_input ('\nPlease Enter Password %s: ' % (set_user))).strip()
                if (set_pw == ""):
                    print '\n\n'
                    print '^'*50
                    print '\n\t\t[Invalid Password]\n'
                    print '='*50
                    time.sleep(1)
                    self.clear()
                    continue
                self.data_entry(set_user, set_pw)
                self.clear()
                print '\n'
                print '*'*50
                print 'New User Successfully Registered!'
                print '^'*50
                break
        except (KeyboardInterrupt):
            self.clear()
            print '^'*50
            print '[Returning to Main Menu]'
            print '*'*50
            print '\n\n'
            time.sleep(2)
            self.clear()
            

    def pass_encryption(self, pw):      # Encrypts User Password using SHA512
        p = sha512()
        p.update(pw)
        secure_pass = p.hexdigest()
        return secure_pass


  
    def data_entry(self, set_user, set_pw):     # Stores User Data
        user = set_user
        pw = set_pw
        sec_pass = self.pass_encryption(pw)
        f = open ('user_data.txt', 'a+')
        j = '%s=%s\n' % (user, sec_pass)
        f.write(j)
        f.close()
        temp_data = {user:sec_pass}
        self.database.update(temp_data)
        temp_data.clear()
        return self.database



    def initial_check(self):    # Initially Checks Local data for Registered Users.
        self.clear()
        print '\n\n'
        print '^'*50
        print '\t[Checking Local Data..]\n'        
        print '='*50
        time.sleep(2)
        db = {}
        a = open('user_data.txt', 'a+')
        c = [i.strip() for i in a.readlines()]
        for i in c:
            j = i.split('=')
            db[j[0]] = j[1]
        self.database.update(db)
        db.clear()
        self.clear()
        return self.database

 
    
    def data_check(self):       # Allows Users to View Registered Users.
        print '^'*50
        print 'Welcome to Account Management!'
        print '*'*50, '\n'
        print 'Total %d Account(s) Registered' % len(self.database) 
        print '_'*50, '\n\n'
        print '[Checking Account Details..]\n'
        count = 0
        time.sleep(2)
        self.clear()
        if (len(self.database)>0):
            temp_list = self.database.keys()
            print '[Registered Users]'
            print '-'*50
            for junk_val in temp_list[:]:
                count +=1
                print '%d. %s' % (count, junk_val)
            junk_val2 = raw_input('\n\n\t\t<Print Any Key To Continue>')
        else:
            print '[No User Registered]\n'
            print '\n\n[Returning to Main Menu]\n'
            print '='*50
            time.sleep(2)
            


    def error_chk(self):    # Checks whether User is Authorised.
        try:
            name = raw_input('Enter Username: ').strip()
            password = raw_input('\nEnter Password: ').strip()
        
            while True:
                if (name in self.database.keys()):
                    print ('\n\n[Username Valid! Checking Password for %s..]' % (name))
                    time.sleep(2)
                    if (self.database[name] == self.pass_encryption(password)):
                        print '^'*50
                        print '[+] Access Granted!'
                        print '*'*50
                        time.sleep(1)
                        self.login()
                        break
                    else:
                        print '\n\n[Password Incorrect]\n'
                        print '[Returning to Main Menu]'
                        time.sleep(2)
                        self.clear()
                        break
                else:
                    print '\n\n[-] Acess Denied!\n'
                    time.sleep(1)
                    self.clear()
                    break
        except (KeyboardInterrupt):
            self.clear()
            print '^'*50
            print '[Returning to Main Menu]'
            print '*'*50
            print '\n\n'
            time.sleep(2)
            self.clear()
            


    def login(self):        # Login Function can be later integrated to allow users access to your program
        print '\n[Feature not implemented yet!]\n\n'
        print '[Returning to Main Menu]'
        time.sleep(3)
        


    def roll_credits(self):
        self.clear()
        print '\n\t', '^'*50, '\n\tQuitting...', '\n\t', '-'*50
        print '\n\tGot Suggestions? Bugs? Email me at : '
        print '\n\tirenicus_timberlake@yahoo.com \n'
        print '\t','*'*50
        time.sleep(3)

    

if __name__ == '__main__':
    global mng
    mng = user_management()
    mng.select()
Once again thanks to S3myon for helping me learn python from the start!

Have fun messing with the source code, and do let me know if u find any bugs/suggestions!

Last edited by irenicus09; 7th February 2010 at 19:11.
Reply With Quote
  #9  
Old 8th February 2010, 10:39
s3my0n's Avatar
InterN0T Crew
 
Join Date: Sep 2009
Location: /home/s3my0n/
Posts: 373
Blog Entries: 3
Rep Power: 8
Reputation: 227
s3my0n has made his way up the systems3my0n has made his way up the systems3my0n has made his way up the system
Re: [Python] User Management System (New!)

OK, let me just correct few mistakes if you don't mind ^^

OK, let's start from the top:

Code:
class user_management():
    def __init__(self, database={}, choice=""):
        self.database = database
        self.choice = choice
        self.title()
        self.initial_check()
Here you didn't pass anything to user_management, that's alrite for now, but in future versions of python you will have to put 'object' or another class name into class declaration like this:
Code:
class user_management(object):
Next subfunction __init__ is a constructor of a class. It is called when the class is first initialised:
Code:
mng = user_management()
In your program you made it so __init__ recieves 2 variables, but because you didn't put 'object' when you declared the class, the compiler didn't give any error.

In your code 'database={}, choice=""' are not needed in __init__() because you don't really use them. Instead your class should look like this:
Code:
class user_management(object):
    def __init__(self):
        self.database = {}
        self.choice = ""
        self.title()
        self.initial_check()
Next:
Code:
def select(self):   # Main Function of the class. User Selects Option.
        while True:
            self.menu()
            try:
                self.choice = raw_input ('You Entered: ').strip()
            except (KeyboardInterrupt, IOError):
                print '\nAborted! Exiting..'
                time.sleep(2)
                break
In the above code you named the user input variable 'self.choice' . As you might know self refers to the variable the class was assgined to at instantation which is 'mng'.

Now because in your program you don't need to call 'self.choice', outside of your class, or outside the subfunction 'select(self)', there's no need to call it 'self.choice'. Instead it's better to do this:
Code:
def select(self):   # Main Function of the class. User Selects Option.
        while True:
            self.menu()
            try:
                choice = raw_input ('You Entered: ').strip()
            except (KeyboardInterrupt, IOError):
                print '\nAborted! Exiting..'
                time.sleep(2)
                break
Remember, you don't have to name every variable in a class 'self.*' as the self is only useful for outside of that class usage.

Next this:
Code:
if (self.choice in '1234'):
                if (self.choice == '1'):
                    self.clear()
                    self.register()
                elif (self.choice == '2'):
                    self.clear()
                    self.data_check()
                    self.clear()
                elif (self.choice == '3'):
                    self.clear()
                    self.error_chk()
                    self.clear()
                elif (self.choice == '4'):
                    self.roll_credits()
                    break
                elif (self.choice == ''):
                    self.clear()
                    print '[Invalid Input! Try Again..]\n'    
            else:
                self.clear()
                print '[Invalid Input! Try Again..]\n'
There's nothing woring with that, but for cleanliness of code and less typing this is a good way to do it:
Code:
choices = {'1':self.register
               '2':self.data_check
               '3':self.error_chk}

if (choice in '123'):
    self.clear()
    choices[choice]() #here is the instantation of a function
    self.clear()
elif (choice == '4'):
    self.roll_credits()
    break
elif (choice == ''):
    self.clear()
    print '[Invalid Input! Try Again..]\n'    
else:
    self.clear()
    print '[Invalid Input! Try Again..]\n'
All of the rest code in the class is alrite, some of the tips above could be implemented to them. If you didn't know, any variable with prefix 'self' in the class can be used by any function in the class. For example:

Code:
class Test(object):
    def __init__(self, string):
        self.whattosay = string
    def sayit(self):
        print self.whattosay #variable defined in __init__ function

i = raw_input('\nWhat to say?: ')
nprint = Test(i) #passing i to __init__()
nprint.sayit() #will print whatever i is
And last thing:
Code:
if __name__ == '__main__':
    global mng
    mng = user_management()
    mng.select()
The only reason I made mng global so functions outside the class can access that variable. Since you don't have any function outside of your class, you dont need to make mng global.
Code:
if __name__ == '__main__':
    mng = user_management()
    mng.select()
Well, I think that's the least of it. Learn more about classes and how to use them efficiently. Remember, classes are methods, like int('90') is a class, where value '90' is passed to int()'s __init__(self, stringnumber).
__________________
Quote:
Computers are incredibly fast, accurate, and stupid; humans are incredibly slow, inaccurate and brilliant; together they are powerful beyond imagination.
-Albert Einstein
Reply With Quote
  #10  
Old 11th February 2010, 09:18
irenicus09's Avatar
 
Join Date: Dec 2009
Location: United Nations (:
Posts: 63
Rep Power: 3
Reputation: 14
irenicus09 is on the way to become something
Re: [Python] User Management System (New!)

Thanks for the advice s3myon! I'm climbing the python world one step at a time ^^
Btw I found Qt (GUI designer) to be pretty interesting, especially the Qt Creator in ubuntu....

Oh another thing, do u think its possible to expand our previous 'Simple Text Encryption' program, perhaps reconstruct it so that it can encrypt a text file (using a random cypher generator), and store the file's info like username, password as header in an encrypted form(sha512/md5) in the encrypted file itself and make the encrypted file an executable file....the point being that only the authorised user can decrypt the file without having the need to use additional program(s) to decrypt the file (portable self decrypting file)

What type of mechanism needs to be involved to accomplish the task mentioned above? The program needs to be coded with some strong security foundation in mind so that the encapsulated data is not read through hex editor or reverse engineering. The program needs to be coded very efficiently so that it's lightweight, occupying only a few kbs in the encrypted file itself.....

This can be a Special Group project and released on other forums on behalf of the intern0t coding team as a final binary program, and if it is approved by everyone here, and we succeed in creating it, it will bring a lot of good coders from other forums too & above all recognition...

To accomplish that we need to be in touch through other methods like irc, messenger, etc ^^

Let me know what u guys think about it!

Last edited by irenicus09; 11th February 2010 at 09:30.
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
[Hint] How to delete user password. Except1onX Security Tutorials and Guides 7 11th February 2010 09:37
[python] Login System with MD5 Encryption s3my0n Perl // Python 2 7th February 2010 16:24
[Article] M$ to Cut time Bing Stores User Data agriloan Security News and Feeds 0 19th January 2010 21:13
[Article] Wireless IPS Vender adding Performance Management to Software agriloan Security News and Feeds 0 21st December 2009 21:51
[Show Off] WarFTPD 1.65 USER BoF ~ Metasploit Module MaXe General Hacking Discussions 6 11th October 2008 19:36


All times are GMT +2. The time now is 13:54.
Copyright ©2007 - Forever, InterN0T & Teh Unkwon

Hosted by 1and1