I want to authenticate an user in Python(2.6 or 2.7) / C code .
I have to create a simple authentication module which will take username and password as input and will validate user (like PAM module for UNIX).
Any way to do it ?
Are you looking for something like LogonUser?, to authenticates local user, for example:
#!python
# -*- coding: utf-8 -*-
from os import environ
from ctypes import windll, byref, POINTER, FormatError, GetLastError
from ctypes.wintypes import (
LPCWSTR, WCHAR, DWORD, HANDLE, BOOL
)
MAX_COMPUTERNAME_LENGTH = 15
LOGON32_LOGON_NETWORK_CLEARTEXT = 8
LOGON32_PROVIDER_DEFAULT = 0
CloseHandle = windll.Kernel32.CloseHandle
CloseHandle.argtypes = [HANDLE]
CloseHandle.restype = BOOL
LogonUser = windll.Advapi32.LogonUserW
LogonUser.argtypes = [LPCWSTR, LPCWSTR, LPCWSTR, DWORD, DWORD, POINTER(HANDLE)]
LogonUser.restype = BOOL
if __name__ == '__main__':
username = 'MyUsername'
password = 'MyPassword'
token = HANDLE()
status = LogonUser(username,
environ['COMPUTERNAME'],
password,
LOGON32_LOGON_NETWORK_CLEARTEXT,
LOGON32_PROVIDER_DEFAULT,
byref(token))
error = GetLastError()
if status:
print('OK, successes')
CloseHandle(token)
else:
print(FormatError(error))
Related
Not wx, gtk3, pyqt etc...
I need something like:
cef.Initialize(settings=settings)
window_info = cef.WindowInfo()
browser = cef.CreateBrowserSync(url="localhost:8080/", window_title="Hello World!" icon="myicon.png")
On Linux execute xseticon program programmtically using os.system() function or similar, see: http://www.leonerd.org.uk/code/xseticon/ .
On Windows use ctypes built-in Python module to execute native win32 functions. Example code below. The _hWnd variable holds window handle which can be obtained by calling browser.GetWindowHandle().
from ctypes import *
from ctypes.wintypes import *
from os import path
import platform
LRESULT = c_int64 if platform.architecture()[0] == "64bit" else c_long
SendMessage = windll.user32.SendMessageW
SendMessage.restype = LRESULT
SendMessage.argtypes = [HWND, UINT, WPARAM, LPARAM]
GetModuleHandle = windll.kernel32.GetModuleHandleW
GetModuleHandle.restype = HMODULE
GetModuleHandle.argtypes = [LPCWSTR]
IMAGE_ICON = 1
LR_LOADFROMFILE = 0x00000010
LR_CREATEDIBSECTION = 0x00002000
LoadImage = windll.user32.LoadImageW
LoadImage.restype = HANDLE
LoadImage.argtypes = [HINSTANCE, LPCWSTR, UINT, c_int, c_int, UINT]
RelPath = lambda file : path.join(path.dirname(path.abspath(__file__)), file)
def AlterIcon(_hWnd, lpszIcon):
WM_SETICON = 0x0080
ICON_BIG = 1
hModel = GetModuleHandle(None)
hIcon = LoadImage(hModel,
RelPath(lpszIcon),
IMAGE_ICON,
0, 0,
LR_LOADFROMFILE | LR_CREATEDIBSECTION)
SendMessage(_hWnd, WM_SETICON, ICON_BIG, hIcon)
Ref: http://qaru.site/questions/7837596/how-to-include-image-in-message-box-using-ctypes-in-python
I am working on Python 3 and tried installing pam, which was successful. It installed the pam-0.1.4 version.
C:\Users\anjan>pip install pam
Collecting pam
Downloading https://files.pythonhosted.org/packages/d6/cb/73c7725f4c7ee14205d85c6777a44f9b33e51d31fd5fc1bb0aa7f35cf8d2/pam-0.1.4.tar.gz
Building wheels for collected packages: pam
Running setup.py bdist_wheel for pam ... done
Stored in directory: C:\Users\anjan\AppData\Local\pip\Cache\wheels\24\8d\30\48fca5978b858d699565ee0cde875798229022bbb4e86e8b43
Successfully built pam
Installing collected packages: pam
Successfully installed pam-0.1.4
Next when I try to import pam it throws out the following syntax error. Looks like the pam.py file is still on Python2.x.
Does anyone know how to resolve this issue?
>>> import pam
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\anjan\Anaconda3\lib\site-packages\pam.py", line 129
print authenticate(getpass.getuser(), getpass.getpass())
^
SyntaxError: invalid syntax
The pam.py file looks like as shown below.
# (c) 2007 Chris AtLee <chris#atlee.ca>
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php
"""
PAM module for python
Provides an authenticate function that will allow the caller to authenticate
a user against the Pluggable Authentication Modules (PAM) on the system.
Implemented using ctypes, so no compilation is necessary.
"""
__all__ = ['authenticate']
from ctypes import CDLL, POINTER, Structure, CFUNCTYPE, cast, pointer, sizeof
from ctypes import c_void_p, c_uint, c_char_p, c_char, c_int
from ctypes.util import find_library
LIBPAM = CDLL(find_library("pam"))
LIBC = CDLL(find_library("c"))
CALLOC = LIBC.calloc
CALLOC.restype = c_void_p
CALLOC.argtypes = [c_uint, c_uint]
STRDUP = LIBC.strdup
STRDUP.argstypes = [c_char_p]
STRDUP.restype = POINTER(c_char) # NOT c_char_p !!!!
# Various constants
PAM_PROMPT_ECHO_OFF = 1
PAM_PROMPT_ECHO_ON = 2
PAM_ERROR_MSG = 3
PAM_TEXT_INFO = 4
class PamHandle(Structure):
"""wrapper class for pam_handle_t"""
_fields_ = [
("handle", c_void_p)
]
def __init__(self):
Structure.__init__(self)
self.handle = 0
class PamMessage(Structure):
"""wrapper class for pam_message structure"""
_fields_ = [
("msg_style", c_int),
("msg", POINTER(c_char)),
]
def __repr__(self):
return "<PamMessage %i '%s'>" % (self.msg_style, self.msg)
class PamResponse(Structure):
"""wrapper class for pam_response structure"""
_fields_ = [
("resp", POINTER(c_char)),
("resp_retcode", c_int),
]
def __repr__(self):
return "<PamResponse %i '%s'>" % (self.resp_retcode, self.resp)
CONV_FUNC = CFUNCTYPE(c_int,
c_int, POINTER(POINTER(PamMessage)),
POINTER(POINTER(PamResponse)), c_void_p)
class PamConv(Structure):
"""wrapper class for pam_conv structure"""
_fields_ = [
("conv", CONV_FUNC),
("appdata_ptr", c_void_p)
]
PAM_START = LIBPAM.pam_start
PAM_START.restype = c_int
PAM_START.argtypes = [c_char_p, c_char_p, POINTER(PamConv),
POINTER(PamHandle)]
PAM_END = LIBPAM.pam_end
PAM_END.restpe = c_int
PAM_END.argtypes = [PamHandle, c_int]
PAM_AUTHENTICATE = LIBPAM.pam_authenticate
PAM_AUTHENTICATE.restype = c_int
PAM_AUTHENTICATE.argtypes = [PamHandle, c_int]
def authenticate(username, password, service='login'):
"""Returns True if the given username and password authenticate for the
given service. Returns False otherwise
``username``: the username to authenticate
``password``: the password in plain text
``service``: the PAM service to authenticate against.
Defaults to 'login'"""
#CONV_FUNC
def my_conv(n_messages, messages, p_response, app_data):
"""Simple conversation function that responds to any
prompt where the echo is off with the supplied password"""
# Create an array of n_messages response objects
addr = CALLOC(n_messages, sizeof(PamResponse))
p_response[0] = cast(addr, POINTER(PamResponse))
for i in range(n_messages):
if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF:
pw_copy = STRDUP(str(password))
p_response.contents[i].resp = pw_copy
p_response.contents[i].resp_retcode = 0
return 0
handle = PamHandle()
conv = PamConv(my_conv, 0)
retval = PAM_START(service, username, pointer(conv), pointer(handle))
if retval != 0:
# TODO: This is not an authentication error, something
# has gone wrong starting up PAM
PAM_END(handle, retval)
return False
retval = PAM_AUTHENTICATE(handle, 0)
e = PAM_END(handle, retval)
return retval == 0 and e == 0
if __name__ == "__main__":
import getpass
print authenticate(getpass.getuser(), getpass.getpass())
print is a function in Python 3.
Change it to
print(authenticate(getpass.getuser(), getpass.getpass()))
# ^ Note the braces that make it a function call
The way you have it written is valid only in Python 2.
Pam 0.1.4 is for python2, hence the error. There is a pam available for python3 , but it is called as simplepam -0.1.5 . I guess this should be a probable fix for my question.
[link] (pypi.org/project/simplepam)
i am working on an api for whatsapp, i am using Yowsup.
when i use Yowsup Cli client i manage to login to the whatsapp account and send and receive messages from it.
when i try to use the following script, it return "Auth Failed!".
import sys
import os
import logging
import time
import shutil
import Queue
from collections import defaultdict
from Yowsup.Common.debugger import Debugger
from Yowsup.connectionmanager import YowsupConnectionManager
from py_utils import logutils
from py_utils import executable_utils
from py_utils import exception_utils
from py_utils.cli_utils import actions_handler
COUNTRY_CODE = "COUNTRY_NUM"
PHONE_NUMBER = "MYNUMBER"
# IDENTITY = ""
PASSWORD = 'MY_PASS_WORD'
LOGIN = COUNTRY_CODE + PHONE_NUMBER
import argparse, sys, os, csv
from Yowsup.Common.utilities import Utilities
from Yowsup.Common.debugger import Debugger
from Yowsup.Common.constants import Constants
from Yowsup.Contacts.contacts import WAContactsSyncRequest
from Yowsup.connectionmanager import YowsupConnectionManager
import threading,time, base64
########## DO NOT COMMIT THIS FILE WITH YOUR CREDENTIALS ###########
#.....................WhatsApp Account Config.......................
nickname = "lamaaaaaaa"
username = LOGIN
password = PASSWORD
id = "" # Not required
#....................................................................
# Degug is False by default if you add -d you will set it to True
Debugger.enabled = True if '-d' in sys.argv else False
password = base64.b64decode(bytes(password.encode('utf-8')))
def login(username, password):
print "[] Logging in as %s (%s)\n" % (nickname, username)
methodsInterface.call("auth_login", (username, password))
def onAuthSuccess(username):
print("Authed!!\n\n")
methodsInterface.call("ready")
methodsInterface.call("presence_sendAvailableForChat", (nickname,))
def onAuthFailed(username, err):
print("Auth Failed!")
########################### BIND EVENTS #############################
connectionManager = YowsupConnectionManager()
signalsInterface = connectionManager.getSignalsInterface()
methodsInterface = connectionManager.getMethodsInterface()
connectionManager.setAutoPong(True)
signalsInterface.registerListener("auth_success", onAuthSuccess)
signalsInterface.registerListener("auth_fail", onAuthFailed)
#####################################################################
login(username, password)
The problem is the the access token need to be update.
in the Yowsup package there under comon \ constans.py
there a need to update the tokanData to :
tokenData = {
"v": "2.12.53",
"r": "S40-2.12.53",
"u": "WhatsApp/2.12.53 S40Version/14.26 Device/Nokia302",
"t": "PdA2DJyKoUrwLw1Bg6EIhzh502dF9noR9uFCllGk1416435341393{phone}",
"d": "Nokia302"
# "v": "2.12.15",
# "r": "S40-2.12.15",
# "u": "WhatsApp/2.12.15 S40Version/14.26 Device/Nokia302",
# "t": "PdA2DJyKoUrwLw1Bg6EIhzh502dF9noR9uFCllGk1391039105258{phone}",
# "d": "Nokia302"
}
you can see the difference between what i had and what i need to use
Now my code works with a normal c library, but I need to use a .so library from Caen and I get Segmentation fault. This is the code:
from ctypes import *
lib = CDLL('./libcaenhvwrapper.so.5.56')
lib.CAENHVInitSystem.restype = c_int
lib.CAENHVInitSystem.argtypes = [c_int, c_int, c_char_p, c_char_p, c_char_p]
lib.CAENHVGetError.restype = c_int
CAENHV_SYSTEM_TYPE_t = c_int
sy1527 = CAENHV_SYSTEM_TYPE_t(0)
sy2527 = CAENHV_SYSTEM_TYPE_t(1)
sy4527 = CAENHV_SYSTEM_TYPE_t(2)
sy5527 = CAENHV_SYSTEM_TYPE_t(3)
n568 = CAENHV_SYSTEM_TYPE_t(4)
v65xx = CAENHV_SYSTEM_TYPE_t(5)
n1470 = CAENHV_SYSTEM_TYPE_t(6)
v8100 = CAENHV_SYSTEM_TYPE_t(7)
link = c_int
LINKTYPE_TCPIP = link(0)
LINKTYPE_RS232 = link(1)
LINKTYPE_CAENET = link(2)
LINKTYPE_USB = link(3)
LINKTYPE_OPTLINK = link(4)
LINKTYPE_USB_VCP = link(5)
string15=c_char*15
address=string15('1','3','7','.','1','3','8','.','1','3','.','2','0','3','\0')
userName = c_char_p('user')
passwd = c_char_p('user')
ret_init = lib.CAENHVInitSystem(0, 0, address, userName, passwd)
when I try to call the function I get a segmentation fault. I think the types are correctly defined. Below you can see a piece of code which works ok.
from ctypes import *
lib2 = CDLL('/lib64/libc.so.6')
string15=c_char*15
address=string15('1','3','7','.','1','3','8','.','1','3','.','2','0','3','\0')
address1=create_string_buffer('137.138.13.203')
address2=c_char_p('137.138.13.200')
userName = c_char_p('user')
passwd = c_char_p('user')
a= lib2.strncmp(address, userName, c_int(4))
a= lib2.strncmp(userName, address, 4)
a= lib2.strncmp(address2, address, 15)
lib2.printf('%d\n', ret_init)
lib2.printf('%s\n', address)
lib2.printf('%s\n', address1)
lib2.printf('%s\n', address2)
lib2.printf('%d\n', lib2.strlen(address))
lib2.printf('%d\n', lib2.strlen(address1))
lib2.printf('%d\n', lib2.strlen(adrress2))
From a quick search:
CAENHVRESULT CAENHVInitSystem(
const char *SystemName, // In
int LinkType,
void *Arg,
const char *UserName,
const char *Password
);
First parameter id definitively a "pointer to char", you should declare it like that:
lib.CAENHVInitSystem.argtypes = [c_char_p, c_int, c_int, c_char_p, c_char_p, c_char_p]
In addition:
ret_init = lib.CAENHVInitSystem(0, 0, address, userName, passwd)
# ^
You pass NULL as SystemName (as NULL is ((void*)0) on most systems). According to the doc I quickly read, this is not explicitly supported.
This is the first function with parameter SystemName to call, and it must be called for all the HV power supplies the user wants to control
I've been trying to use the digi Advanced Device Discovery protocol library with python using ctypes.
the context:
Windows 7 x64
python 2.7.5
dll library
here's my current code:
guid = (0xbf6db409,0xc83d,0x44a3,0xa3,0x6d,0x21,0x79,0x7d,0x2f,0x73,0xf9)
class ADDP():
from ctypes import Structure
class GUID(Structure):
from ctypes.wintypes import DWORD,WORD,BYTE
_fields_ = [("Data1",DWORD),
("Data2",WORD),
("Data3",WORD),
("Data4",BYTE * 8)]
def __init__(self, guid):
from ctypes import windll, c_void_p, c_byte, pointer,c_char,POINTER
from ctypes.wintypes import HANDLE
import ctypes
self.dll = windll.LoadLibrary("D:\\Lib\\addp.dll")
self.guid = self.GUID()
self.guid.Data1 = guid[0]
self.guid.Data2 = guid[1]
self.guid.Data3 = guid[2]
self.guid.Data4 = (c_byte * 8)(guid[3],guid[4],guid[5],guid[6],guid[7],guid[8],guid[9],guid[10])
addpopen = self.dll[1]
addpopen.argtypes = [POINTER(self.GUID),]
addpopen.restype = c_void_p
#print addpopen.restype
self.handler = addpopen(pointer(self.guid))
if self.handler == None:
raise RuntimeError()
self.opened = False
else:
self.opened = True
def isOpen(self):
return self.opened
def Discover(self):
from ctypes import c_int
srch = self.dll[6]
srch.restype = c_int
print srch(self.handler,10,10)
def Close(self):
close = self.dll[3]
close.restype = None
self.opened = False
#print close(self.handler)
conn = ADDP(guid)
#print conn.handler
conn.Discover()
#conn.Close()
print conn.handler
i searched a lot for how to handle a handle returned from a c function, but couldn't find much about it, i read the ctypes docs for a while, and then inspected the header file too..
the handle is defined in the header file with
typedef void* addp_handle_t;
so i assumed i had to set 'restype' to 'c_void_p', the function always returns 'None'
its specified in the header file that it returns 'None' when an error has occurred, else it return the handle to ADDP session.
another thing, this dll does not export functions by name... i had to, more or less, guess what function is what by expected bytes in arguments.
any ideas on this?
i've found a project on google code but apparently it didn't go far...
if you need any other details, just say