GithubHelp home page GithubHelp logo

api-client-python's Introduction

Gophish Python API Client

Gophish was built from the ground-up to be API-first. This means that we build out the API endpoints for all of our features, and the UI is simply a wrapper around these endpoints.

To interface with Gophish using Python, we've created a gophish client library.

If you want to access the API directly, please refer to our API Documentation

Installation

To install the gophish library, simply run the command:

pip install gophish

Quickstart

Getting up and running with the Python library is quick and easy.

To start, simply create a client using the API key found in the Settings page.

from gophish import Gophish

api_key = 'API_KEY'
api = Gophish(api_key)

Now you're ready to start using the API!

Full Documentation

You can find the full Python client documentation here.

api-client-python's People

Contributors

blue-boo avatar cschwartz avatar felddy avatar glennzw avatar hiteshpatel0101 avatar jordan-wright avatar martindube avatar quelsan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

api-client-python's Issues

Installation via pip does not install required dependencies

Installing gophish-0.2.5 via pip does not pull in the required dependencies. Below is the terminal output showing a virtual environment before and after an attempted install. The final block of output shows a failure when running from gophish import Gophish as described in the README.md

(🐍test)markf@bumpkin /tmp/test ❱ pip list installed 
Package    Version
---------- -------
pip        19.1.1 
setuptools 41.0.1 
wheel      0.33.4 
───────────────────────────────────────────────────────────────────────────────────────────── 16:13:25
(🐍test)markf@bumpkin /tmp/test ❱ pip install --no-cache gophish
Collecting gophish
  Downloading https://files.pythonhosted.org/packages/29/5b/b5297e1ad605287cc6e523c43947f44c091cf54bc0d056ac77d107421e71/gophish-0.2.5-py3-none-any.whl
Installing collected packages: gophish
Successfully installed gophish-0.2.5
───────────────────────────────────────────────────────────────────────────────────────────── 16:13:37
(🐍test)markf@bumpkin /tmp/test ❱ pip list installed 
Package    Version
---------- -------
gophish    0.2.5  
pip        19.1.1 
setuptools 41.0.1 
wheel      0.33.4 
───────────────────────────────────────────────────────────────────────────────────────────── 16:13:41
(🐍test)markf@bumpkin /tmp/test ❱ python
Python 3.7.2 (default, Mar 10 2019, 12:20:05) 
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from gophish import Gophish
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/markf/.pyenv/versions/test/lib/python3.7/site-packages/gophish/__init__.py", line 1, in <module>
    from .client import Gophish
  File "/Users/markf/.pyenv/versions/test/lib/python3.7/site-packages/gophish/client.py", line 1, in <module>
    import requests
ModuleNotFoundError: No module named 'requests'
>>> 

Dependencies are outdated

The dependencies certifi,requests and urllib3 have newer versions. Now I get the following errors:

ERROR: After October 2020 you may experience errors when installing or updating packages. This is because pip will change the way that it resolves dependency conflicts.

We recommend you use --use-feature=2020-resolver to test your packages with the new resolver before it becomes the default.

gophish 0.5.1 requires certifi==2020.6.20, but you'll have certifi 2020.11.8 which is incompatible.
gophish 0.5.1 requires requests==2.24.0, but you'll have requests 2.25.0 which is incompatible.
gophish 0.5.1 requires urllib3==1.25.10, but you'll have urllib3 1.26.2 which is incompatible.

Perhaps it would be a good idea to specify the requirements of the package in a range: "requests>=2,<3"

That way the required dependencies don't need to be updated in setup.py every time that there is a minor update of a package.

Dependecies are outdated

There are newer versions for dependencies that are required to install this package (appdirs, packaging, pyparsing and six).

Having newer version of these packages installed in the environment causes a warning when trying to install gophish.

CSRF protection breaking breaking state changing actions

When using the latest version of the API client (0.2.5) and Gophish (0.7.1),
state changing requests requests, for example "POST /api/templates/", fail with with status code 403. In addition, the server returns an error message stating that the wrong CSRF token has been submitted.

As the API supports bearer type authentication and requests are submitted using the content type "application/json", there should be no need for the CSRF tokens in this context.

Another possibility, while not as clean, is to reconfigure the underlying "requests" session to store and submit the CSRF token cookie value, but this may have other consequences.

Envelope_sender of V12.0 not included

What version of Gophish are you using?: 12.0

Brief description of the issue: The documentation is not updated and does not include the added envelope_sender in V.12.0. Additionally, the envelope_sender can not be requested via the Python wrapper, it is not included in the template processed by the Python wrapper.

What are you expecting to see happen? : The Python wrapper shall return the envelope_sender when requesting a specific campaign / the template of it.

What do you see: A direct API call is possible and returns the envelope_sender, but the Python wrapper is not updated.

Attachment model missing __init__

I was trying to programmatically build templates with attachments and found that I couldn't do it due to an error in the models.py file. I modified it on my own end and it works perfectly now. I will submit a pull request with the update.

Error in Creating and Sending Campaign using API

I am facing a problem with invalid JSON structure

def GoSend(group):
    pages = api.pages.get()
    for page in pages:
        if (page.name == 'test'):
            toSendPage = page
    templates = api.templates.get()
    for template in templates:
        if (template.name == 'Key'):
            toSendTemplate = template
    senders = api.smtp.get()
    for sender in senders:
        if (sender.name == 'UWP keygen'):
            toSendSmtp = sender
    # toSendGroup = [Group(name=group.name)]
    # toSendPage = Page(name='test')
    # toSendTemplate = Template(name='Key')
    # toSendsmtp = SMTP(name='UWP keygen')
    toSendUrl = "<redacted>"
    campaign = Campaign(
    name=group.name, groups=group, page=toSendPage, 
    template=toSendTemplate, smtp=toSendSmtp, url=toSendUrl)
    result = api.campaigns.post(campaign)
    debug("[*] {} GoSend complete".format(ln()))
    return result

I am getting the following error :

.
.
.
File "/usr/local/lib/python3.7/dist-packages/gophish/api/campaigns.py", line 20, in post
    return super(API, self).post(campaign)
  File "/usr/local/lib/python3.7/dist-packages/gophish/api/api.py", line 92, in post
    raise Error.parse(response.json())
gophish.models.Error: Invalid JSON structure

Error when posting a new group

I am parsing a csv file of names, emails, & departments. I want to create groups by department.

I create a list of Users, then post the group.
grp_targ.append(User(first_name=targ.name.split(' ')[0], last_name=targ.name.split(' ')[2:], email=targ.email, position=targ.title))
print "[+] Creating group " + current_group + " with " + str(grp_targ)
new_group = Group(name=current_group, targets=grp_targ)
resp = api.groups.post(new_group)

When I do this, I receive the following error:
File "GoPhish_Script.py", line 79, in parse_group_file
resp = api.groups.post(new_group)
File "../2.7/lib/python2.7/site-packages/gophish/api/groups.py", line 14, in post
return super(API, self).post(group)
File "../2.7/lib/python2.7/site-packages/gophish/api/api.py", line 60, in post
response = self.api.execute("POST", self.endpoint, json=(resource.as_dict()))
File "../2.7/lib/python2.7/site-packages/gophish/models.py", line 27, in as_dict
val = [e.as_dict() for e in val]
File "../2.7/lib/python2.7/site-packages/gophish/models.py", line 27, in as_dict
val = [e.as_dict() for e in val]
AttributeError: 'str' object has no attribute 'as_dict'

Oddly enough, if the group has a dash in the string it imports fine. Some of our groups are Dept - Location and these import but it bombs out when getting to a single or multiple word department.

GoPhish version 0.5.0

Thank you for any help.

Creating a new Template without Attachments fails

Hi,
when playing with the API I encountered the following issue:
When posting a new template without attachments to a GoPhish 7.1 instance, the following code taken from the example

template = Template(name='Test Template', html='<html><body>Click <a href="{{.URL}}">here</a></body></html>')
template = api.templates.post(template)

fails with the message *** TypeError: 'NoneType' object is not iterable.

Replacing the definition of template with the somewhat hacky

template = Template(name='Test Template',html='<html><body>Click <a href="{{.URL}}">here</a></body></html>', attachments=[Attachment.parse({"name":"a", "type":"a", "content":"a"})])

does not trigger the error.

Upon digging into it, I found that GoPhish returns the following JSON as a response to the POST above:

{
  "id": 18,
  "name": "mail_1",
  "subject": "",
  "text": "",
  "html": "test",
  "modified_date": "2018-11-01T21:00:10.314402993Z",
  "attachments": null
}

which fails to deserialize in Template.parse, due to attachments being null.

A quick fix would be changing the line above to

elif key == 'attachments' and val:

, alternatively GoPhish itself could return an empty array instead of null.

I'm not sure what GoPhish's behaviour is in similar cases and thus what the appropriate fix would be.

If you got a suggestion, I'd love to provide a pull request to resolve this.

Best,
Christian

TimelineEntry not documented in API Docs

Hi, I've found by reading the gophish python API documentation that the TimelineEntry model is not documented is any way.

Users/Developers who need to use that model may be uncomfortable with reading the source code of the Gophish python API in order to understand properties and methods of that class.

Missing "api_key" parameter in requests (breaks API)

Thanks for the awesome project and all the affort you put in it!

It seems that the current API release doesn't work, because no requests seems to send the API key with it. Basic example from the official documenation:

from gophish import Gophish
from gophish.models import *

api_key = 'd667f0e43b7a2ac5bc9438ae059...'
api = Gophish(api_key)

templates = api.templates.get()
print (templates)

Resulting error (tested with python 3.8.1):

Traceback (most recent call last):
  File "gophish_init.py", line 7, in <module>
    templates = api.templates.get()
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\gophish\api\templates.py", line 12, in get
    return super(API, self).get(resource_id=template_id)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\gophish\api\api.py", line 88, in get
    return self.request("GET",
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\gophish\api\api.py", line 60, in request
    raise Error.parse(response.json())
gophish.models.Error: API Key not set

I had a look into the code and it seems as the "api_key" parameter, which needs to be appended at in the request URL, is not set anywhere.
I fixed it by adding the following to api.py:57:

        if resource_action:
            endpoint = self._build_url(endpoint, resource_action)
            
        # append api_key to request
        endpoint = endpoint + "?api_key=" + self.api.api_key
        
        response = self.api.execute(method, endpoint, json=body)
        if not response.ok:
            raise Error.parse(response.json())

Hope that helps to fix the issue.

Basic Group POST (Documentation exemple) don't work in python ...

Gophish Version : 0.12.1
Gophish Python API Version : 0.5.1
Python Version: 3.11

If i try the basic exemple with my server
`from gophish import Gophish
from gophish.models import *

api_key = 'MyKey'
api_srv = 'https://MyServer/api'

api = Gophish(api_key, host=api_srv)

targets = [
User(first_name='John', last_name='Doe', email='[email protected]'),
User(first_name='Jane', last_name='Doe', email='[email protected]')]

group = Group(name='Doe Company', targets=targets)
group = api.groups.post(group)
print (group.id)`

I get the following error:
Traceback (most recent call last): File "/home/notme/scripts/TestApi.py", line 14, in <module> group = api.groups.post(group) ^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/gophish/api/groups.py", line 15, in post return super(API, self).post(group) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/gophish/api/api.py", line 106, in post raise Error.parse(response.json()) ^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/requests/models.py", line 898, in json return complexjson.loads(self.text, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 525, in loads return _default_decoder.decode(s) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 375, in decode raise JSONDecodeError("Extra data", s, end, len(s)) simplejson.errors.JSONDecodeError: Extra data: line 1 column 5 - line 2 column 1 (char 4 - 19)

Is there any wrong with the example or with the API ?

SMTP Documentation is Wrong

The model attributes for SMTP profiles has the wrong documentation. This page has a list that I think is for Email Templates instead of SMTP profiles.

    id (int) The smtp ID
    name (str) The smtp name
    html (str) The smtp HTML
    text (str) The smtp HTML
    modified_date (optional: datetime.datetime) The scheduled time for smtp launch
    attachments (list(models.Attachment)) The optional email attachments

I think the real list should be based on these lines. I'd be happy to update and submit a pull request, but I'm not sure where/if that's possible with Gitbook.

Feature request - API endpoint to get campaign IDs for given API Key

It would be really useful to have an endpoint that returns a list of just the IDs associated with an API key. For a user with a large number of large campaigns, hitting the URL:

/api/campaigns/

takes a long time to return. A new endpoint would be useful where it returns the IDs and perhaps the names of the campaigns. This payload would be much smaller.

(Background: I am playing around with exporting all data as a CSV from a python script at the command line. With this new endpoint I can find out all my campaign IDs quickly, then iterate over them to get the data. Currently the only way to do this would be to pull all the data down with the above URL/endpoint. This isn't the only time I've wished this endpoint existed, so I am sure others would make use of it.)

Edit: alternatively, add a flag to the /api/campaigns/ endpoint where you just get the basics, and not populate the "results" and "timeline" arrays, nor the "template" contents. Might be a more elegant way of doing it whilst keeping a RESTful approach to the URLs.

Thanks

the document -- the example

hey man !
I don't know how to use the api-client-python, and I read your document,
but, there is always error message ,when I use the same code . It's better to write more.

from gophish import Gophish: starts webserver?!?

when I run "from gophish import Gophish" in python, it starts a webserver on 127.0.0.1:8000 instead of running through the rest of the code.

using:
Python 2.7.16
gophish 0.3.0 installed via pip.

Any ideas?

Cannot create a campaign with the python client

Hi!,

i'm having trouble setting up a new campaign in gophish.
here's the script i use :

_def Ajout_Campagne(): #Funtion to ceate a new campaign

#user input for the campaign name
name = raw_input ("Quel nom voulez vous donner a votre campagne? ")

#user input to select a group to use with the campaign
print "quel groupe voulez vous associer Γ  cette campagne? voici une liste des groupes exisans: "
#function used for listing existing groups
ListeGroupe()
group = raw_input("Groupe?: ")
groups = [Group(name=group)]
print groups

#it goes the same way for all needed settings for a valid campaign: template,smtp,page and URL

    print "Quel template voulez-vous utiliser pour cette campagne? voici une liste des template existants: "
    ListeTemplate()
    templ = raw_input ("Template? ")
    template = Template(name=templ)
    print template

    print "Quel profil SMTP souhaitez-vous utiliser? voici la liste de l'existant: "
    ListeSender()
    smtp = raw_input("profil? ")
    profile = SMTP(name=smtp)
    print profile

    print ("quelle Page de parking voulez-vous utiliser? " )
    parking = raw_input ("Page? ")
    page = Page(name=parking)
    print page

    urlph = raw_input (" Quel est l'url de votre page de traking? ")


    campaign = Campaign(name=name, groups=groups, page=page,template=template, profile=profile)
    print campaign
    bob = api.campaigns.post(campaign)
    print bob_

When i use this script i get an error 400 in gophish logs which mean bad request.. but i can't see what i'm doing wrong since I followed your guide ;)

By the way, in the gophish.models.Group section you might want to change:

targets = [
Target(first_name='John', last_name='Doe', email='[email protected]'),
Target(first_name='Jane', last_name='Doe', email='[email protected]')]

Target --> User since Target isn't defined in models.py

Best regards,

Robin

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.