Documentation
¶
Overview ¶
Package models implements the types and structs needed in gophish.
Index ¶
- Constants
- Variables
- func AddEvent(e *Event, campaignID int64) error
- func AuthCodeOptions(im *IMAP) []oauth2.AuthCodeOption
- func CompleteCampaign(id int64, teamID int64) error
- func DeleteCampaign(id int64) error
- func DeleteGroup(g *Group) error
- func DeleteIMAP(uid int64) error
- func DeletePage(id int64, teamID int64) error
- func DeleteSMTP(id int64, teamID int64) error
- func DeleteTag(id int64, teamID int64) error
- func DeleteTemplate(id int64, teamID int64) error
- func DeleteUser(id int64) error
- func DeleteWebhook(id int64) error
- func EnsureEnoughAdmins() error
- func ExchangeOAuthCode(ctx context.Context, im *IMAP, redirectURL, code string) (*oauth2.Token, error)
- func ExecuteTemplate(text string, data interface{}) (string, error)
- func GenerateMailLog(c *Campaign, r *Result, sendDate time.Time) error
- func GetValidAccessToken(ctx context.Context, im *IMAP) (string, error)
- func IncrementNonCampaignEmails(im *IMAP, n uint32) error
- func LockMailLogs(ms []*MailLog, lock bool) error
- func OAuthConfig(im *IMAP, redirectURL string) (*oauth2.Config, error)
- func Ping() error
- func PostCampaign(c *Campaign, uid int64, teamID int64) error
- func PostEmailRequest(s *EmailRequest) error
- func PostGroup(g *Group) error
- func PostIMAP(im *IMAP, uid int64) error
- func PostPage(p *Page) error
- func PostSMTP(s *SMTP) error
- func PostTag(t *Tag) error
- func PostTeam(t *Team) error
- func PostTemplate(t *Template) error
- func PostWebhook(wh *Webhook) error
- func PutGroup(g *Group) error
- func PutPage(p *Page) error
- func PutSMTP(s *SMTP) error
- func PutTag(t *Tag) error
- func PutTemplate(t *Template) error
- func PutUser(u *User) error
- func PutWebhook(wh *Webhook) error
- func RecordLoginError(im *IMAP, loginErr error) error
- func ScrubCampaign(id int64, teamID int64) error
- func Setup(c *config.Config) error
- func StoreOAuthToken(im *IMAP, tok *oauth2.Token) error
- func SuccessfulLogin(im *IMAP) error
- func TaggedIDs(taggableType string, teamID int64, names []string) ([]int64, error)
- func UnlockAllMailLogs() error
- func UpdateTarget(tx *gorm.DB, target Target) error
- func ValidateTemplate(text string) error
- type Attachment
- type BaseRecipient
- type Campaign
- func GetCampaign(id int64, teamID int64) (Campaign, error)
- func GetCampaignMailContext(id int64, teamID int64) (Campaign, error)
- func GetCampaignPhishContext(id int64, teamID int64) (Campaign, error)
- func GetCampaigns(teamID int64) ([]Campaign, error)
- func GetCampaignsToAutoComplete(t time.Time) ([]Campaign, error)
- func GetQueuedCampaigns(t time.Time) ([]Campaign, error)
- type CampaignMeta
- type CampaignRates
- type CampaignReport
- type CampaignResults
- type CampaignStats
- type CampaignSummaries
- type CampaignSummary
- type CampaignTiming
- type Dialer
- type EmailRequest
- func (s *EmailRequest) Backoff(reason error) error
- func (s *EmailRequest) Error(err error) error
- func (s *EmailRequest) Generate(msg *gomail.Message) error
- func (s *EmailRequest) GetDialer() (mailer.Dialer, error)
- func (s *EmailRequest) GetSendRate() int
- func (s *EmailRequest) GetSmtpFrom() (string, error)
- func (s *EmailRequest) Success() error
- func (s *EmailRequest) Validate() error
- type Event
- type EventDetails
- type EventError
- type Flash
- type Group
- type GroupSummaries
- type GroupSummary
- type GroupTarget
- type Header
- type IMAP
- type MailLog
- func (m *MailLog) Backoff(reason error) error
- func (m *MailLog) CacheCampaign(campaign *Campaign) error
- func (m *MailLog) Error(e error) error
- func (m *MailLog) Generate(msg *gomail.Message) error
- func (m *MailLog) GetDialer() (mailer.Dialer, error)
- func (m *MailLog) GetSendRate() int
- func (m *MailLog) GetSmtpFrom() (string, error)
- func (m *MailLog) Lock() error
- func (m *MailLog) Success() error
- func (m *MailLog) Unlock() error
- type Page
- type Permission
- type PhishingTemplateContext
- type ReportBucket
- type Response
- type Result
- func (r *Result) GenerateId(tx *gorm.DB) error
- func (r *Result) HandleClickedLink(details EventDetails) error
- func (r *Result) HandleEmailBackoff(err error, sendDate time.Time) error
- func (r *Result) HandleEmailError(err error) error
- func (r *Result) HandleEmailOpened(details EventDetails) error
- func (r *Result) HandleEmailReport(details EventDetails) error
- func (r *Result) HandleEmailReportAt(details EventDetails, reportedTime time.Time) error
- func (r *Result) HandleEmailSent() error
- func (r *Result) HandleFormSubmit(details EventDetails) error
- func (r *Result) Resend() error
- func (r *Result) UpdateGeo(addr string) error
- type Role
- type SMTP
- type StageTiming
- type Tag
- type Target
- type Team
- type Template
- type TemplateContext
- type User
- type ValidationContext
- type Webhook
Constants ¶
const ( IMAPAuthTypeBasic = "basic" IMAPAuthTypeOAuth2 = "oauth2" )
IMAP authentication types - see IMAP.AuthType.
const ( OAuthProviderGoogle = "google" OAuthProviderMicrosoft = "microsoft" OAuthProviderCustom = "custom" )
OAuth2 providers supported for IMAP authentication - see IMAP.OAuthProvider and oauth_imap.go.
const ( CampaignInProgress string = "In progress" CampaignQueued string = "Queued" CampaignCreated string = "Created" CampaignEmailsSent string = "Emails Sent" CampaignComplete string = "Completed" EventSent string = "Email Sent" EventSendingError string = "Error Sending Email" EventOpened string = "Email Opened" EventClicked string = "Clicked Link" EventDataSubmit string = "Submitted Data" EventReported string = "Email Reported" EventProxyRequest string = "Proxied request" StatusSuccess string = "Success" StatusQueued string = "Queued" StatusSending string = "Sending" StatusUnknown string = "Unknown" StatusScheduled string = "Scheduled" StatusRetry string = "Retrying" Error string = "Error" )
const ( // RoleAdmin is used for Gophish system administrators. Users with this // role have the ability to manage all objects within Gophish, as well as // system-level configuration, such as users and URLs. RoleAdmin = "admin" // RoleUser is used for standard Gophish users. Users with this role can // create, manage, and view Gophish objects and campaigns. RoleUser = "user" // RoleAuditor is used for read-only accounts. Users with this role can // view their team's objects and campaign results, but cannot create or // modify anything. This is enforced globally by the EnforceViewOnly // middleware, which rejects any state-changing API request from an // account without the PermissionModifyObjects permission. RoleAuditor = "auditor" // PermissionViewObjects determines if a role can view standard Gophish // objects such as campaigns, groups, landing pages, etc. PermissionViewObjects = "view_objects" // PermissionModifyObjects determines if a role can create and modify // standard Gophish objects. PermissionModifyObjects = "modify_objects" // PermissionModifySystem determines if a role can manage system-level // configuration. PermissionModifySystem = "modify_system" )
const ( TaggableTemplate = "template" TaggablePage = "page" TaggableSMTP = "smtp" TaggableCampaign = "campaign" TaggableGroup = "group" )
Taggable type identifiers stored in taggables.taggable_type. These are stable string keys, deliberately not derived from Go type names, so renaming a struct never silently detaches existing tags.
const DefaultAdminUsername = "admin"
DefaultAdminUsername is the default username for the administrative user
const DefaultIMAPFolder = "INBOX"
const DefaultIMAPFreq = 60 // Every 60 seconds
const DefaultMySQLConnMaxLifetime = 5 * time.Minute
DefaultMySQLConnMaxLifetime bounds how long a pooled MySQL connection is reused before being recycled, so it gets refreshed before the MySQL server's own wait_timeout (default 8h, but often lower on shared hosting) closes it out from under us.
const DefaultMySQLMaxOpenConns int = 25
DefaultMySQLMaxOpenConns is the default connection pool size used for MySQL when conf.DBMaxOpenConns isn't set. Unlike SQLite, MySQL handles concurrent connections natively.
const InitialAdminApiToken = "GOPHISH_INITIAL_ADMIN_API_TOKEN"
InitialAdminApiToken is the environment variable that specifies the API token to seed the initial root login instead of generating one randomly
const InitialAdminPassword = "GOPHISH_INITIAL_ADMIN_PASSWORD"
InitialAdminPassword is the environment variable that specifies which password to use for the initial root login instead of generating one randomly
const MaxDatabaseConnectionAttempts int = 10
const PreviewPrefix = "preview-"
PreviewPrefix is the standard prefix added to the rid parameter when sending test emails.
const RecipientParameter = "rid"
RecipientParameter is the URL parameter that points to the result ID for a recipient.
Variables ¶
var ErrCampaignNameNotSpecified = errors.New("campaign name not specified")
ErrCampaignNameNotSpecified indicates there was no template given by the user
var ErrEmailNotSpecified = errors.New("no email address specified")
ErrEmailNotSpecified is thrown when no email is specified for the Target
var ErrFromAddressNotSpecified = errors.New("no From Address specified")
ErrFromAddressNotSpecified is thrown when there is no "From" address specified in the SMTP configuration
var ErrGroupNameNotSpecified = errors.New("group name not specified")
ErrGroupNameNotSpecified is thrown when a group name is not specified
var ErrGroupNotFound = errors.New("group not found")
ErrGroupNotFound indicates a group specified by the user does not exist in the database
var ErrGroupNotSpecified = errors.New("no groups specified")
ErrGroupNotSpecified indicates there was no template given by the user
var ErrHostNotSpecified = errors.New("no SMTP Host specified")
ErrHostNotSpecified is thrown when there is no Host specified in the SMTP configuration
var ErrIMAPHostNotSpecified = errors.New("no IMAP host specified")
ErrIMAPHostNotSpecified is thrown when there is no Host specified in the IMAP configuration
var ErrIMAPInvalidAuthType = errors.New("invalid IMAP authentication type")
ErrIMAPInvalidAuthType is thrown when AuthType is neither "basic" nor "oauth2"
var ErrIMAPPasswordNotSpecified = errors.New("no password specified")
ErrIMAPPasswordNotSpecified is thrown when there is no Password specified in the IMAP configuration
var ErrIMAPPortNotSpecified = errors.New("no IMAP port specified")
ErrIMAPPortNotSpecified is thrown when there is no Port specified in the IMAP configuration
var ErrIMAPUsernameNotSpecified = errors.New("no username specified")
ErrIMAPUsernameNotSpecified is thrown when there is no Username specified in the IMAP configuration
var ErrInvalidCCAddress = errors.New("invalid CC address because it is not an email address")
ErrInvalidCCAddress is thrown when the SMTP CC field contains a value that is not a valid email address
var ErrInvalidFromAddress = errors.New("invalid SMTP From address because it is not an email address")
ErrInvalidFromAddress is thrown when the SMTP From field in the sending profiles containes a value that is not an email address
var ErrInvalidHost = errors.New("invalid SMTP server address")
ErrInvalidHost indicates that the SMTP server string is invalid
var ErrInvalidIMAPFreq = errors.New("invalid polling frequency")
ErrInvalidIMAPFreq is thrown when the frequency for polling the IMAP server is invalid
var ErrInvalidIMAPHost = errors.New("invalid IMAP server address")
ErrInvalidIMAPHost indicates that the IMAP server string is invalid
var ErrInvalidIMAPPort = errors.New("invalid IMAP port")
ErrInvalidIMAPPort indicates that the IMAP Port is invalid
var ErrInvalidOAuthProvider = errors.New("invalid OAuth provider")
ErrInvalidOAuthProvider is thrown when OAuthProvider isn't one of the supported providers
var ErrInvalidSendByDate = errors.New("the launch date must be before the \"send emails by\" date")
ErrInvalidSendByDate indicates that the user specified a send by date that occurs before the launch date
var ErrInvalidSendRate = errors.New("send rate cannot be negative")
ErrInvalidSendRate indicates that a negative send rate was provided
var ErrMaxSendAttempts = errors.New("max send attempts exceeded")
ErrMaxSendAttempts is thrown when the maximum number of sending attempts for a given MailLog is exceeded.
var ErrModifyingOnlyAdmin = errors.New("cannot remove the only administrator")
ErrModifyingOnlyAdmin occurs when there is an attempt to modify the only user account with the Admin role in such a way that there will be no user accounts left in Gophish with that role.
var ErrNameNotSpecified = errors.New("name can't be empty")
ErrNameNotSpecified indicates there was no name specified
var ErrNoTargetsSpecified = errors.New("no targets specified")
ErrNoTargetsSpecified is thrown when no targets are specified by the user
var ErrOAuthClientIDNotSpecified = errors.New("no OAuth client ID specified")
ErrOAuthClientIDNotSpecified is thrown when OAuth2 auth is selected without specifying a client ID
var ErrOAuthClientSecretNotSpecified = errors.New("no OAuth client secret specified")
ErrOAuthClientSecretNotSpecified is thrown when OAuth2 auth is selected without specifying a client secret
var ErrOAuthEndpointNotSpecified = errors.New("no OAuth authorization/token URL specified")
ErrOAuthEndpointNotSpecified is thrown when the custom OAuth provider is selected without specifying both the authorization and token URLs
var ErrOAuthNotConnected = errors.New("no OAuth2 account connected - complete the OAuth authorization flow first")
ErrOAuthNotConnected is returned by GetValidAccessToken when the IMAP config is set to OAuth2 auth but no account has been connected yet (no refresh token stored) - the admin needs to complete the /oauth/imap/authorize flow first.
var ErrOAuthProviderNotSpecified = errors.New("no OAuth provider specified")
ErrOAuthProviderNotSpecified is thrown when OAuth2 auth is selected without specifying a provider
var ErrOAuthScopesNotSpecified = errors.New("no OAuth scopes specified")
ErrOAuthScopesNotSpecified is thrown when the custom OAuth provider is selected without specifying the OAuth scopes to request
var ErrOAuthSecretKeyNotConfigured = errors.New("OAuth2 requires secret_key to be configured in config.json")
ErrOAuthSecretKeyNotConfigured is thrown when OAuth2 auth is selected but the server has no secret_key configured in config.json - OAuth2 tokens are encrypted at rest and can't be stored without it. Caught here, at save time, so the admin finds out before going through the provider's consent screen rather than after
var ErrOAuthTenantIDNotSpecified = errors.New("no OAuth tenant ID specified")
ErrOAuthTenantIDNotSpecified is thrown when the Microsoft OAuth provider is selected without specifying a tenant ID
var ErrPageNameNotSpecified = errors.New("Page Name not specified")
ErrPageNameNotSpecified is thrown if the name of the landing page is blank.
var ErrPageNotFound = errors.New("page not found")
ErrPageNotFound indicates a page specified by the user does not exist in the database
var ErrPageNotSpecified = errors.New("no landing page specified")
ErrPageNotSpecified indicates a landing page was not provided for the campaign
var ErrResultNotEligibleForResend = errors.New("only results with a status of Error can be resent")
ErrResultNotEligibleForResend is returned when trying to resend a result that isn't currently in an Error status.
var ErrSMTPNotFound = errors.New("sending profile not found")
ErrSMTPNotFound indicates a sending profile specified by the user does not exist in the database
var ErrSMTPNotSpecified = errors.New("no sending profile specified")
ErrSMTPNotSpecified indicates a sending profile was not provided for the campaign
var ErrTagNameNotSpecified = errors.New("tag name not specified")
ErrTagNameNotSpecified is thrown when a tag name is blank.
var ErrTeamNameNotSpecified = errors.New("Team name not specified")
ErrTeamNameNotSpecified is thrown when a team is created without a name.
var ErrTemplateMissingParameter = errors.New("need to specify at least plaintext or HTML content")
ErrTemplateMissingParameter is thrown when a needed parameter is not provided
var ErrTemplateNameNotSpecified = errors.New("template name not specified")
ErrTemplateNameNotSpecified is thrown when a template name is not specified
var ErrTemplateNotFound = errors.New("template not found")
ErrTemplateNotFound indicates the template specified does not exist in the database
var ErrTemplateNotSpecified = errors.New("no email template specified")
ErrTemplateNotSpecified indicates there was no template given by the user
var ErrURLNotSpecified = errors.New("URL can't be empty")
ErrURLNotSpecified indicates there was no URL specified
var MaxSendAttempts = 8
MaxSendAttempts set to 8 since we exponentially backoff after each failed send attempt. This will give us a maximum send delay of 256 minutes, or about 4.2 hours.
Functions ¶
func AuthCodeOptions ¶ added in v0.18.0
func AuthCodeOptions(im *IMAP) []oauth2.AuthCodeOption
AuthCodeOptions returns the provider-specific options for the authorization-code request (AuthCodeURL).
Microsoft: prompt=select_account Google: prompt=consent
func CompleteCampaign ¶
CompleteCampaign effectively "ends" a campaign. Any future emails clicked will return a simple "404" page.
func DeleteCampaign ¶
DeleteCampaign deletes the specified campaign
func DeleteGroup ¶
DeleteGroup deletes a given group by group ID and user ID
func DeleteIMAP ¶
DeleteIMAP deletes the existing IMAP in the database.
func DeletePage ¶
DeletePage deletes an existing page in the database. An error is returned if a page with the given team id and page id is not found.
func DeleteSMTP ¶
DeleteSMTP deletes an existing SMTP in the database. An error is returned if a SMTP with the given team id and SMTP id is not found.
func DeleteTag ¶ added in v0.18.0
DeleteTag removes a tag and all of its object links within the team. The linked objects themselves are left untouched.
func DeleteTemplate ¶
DeleteTemplate deletes an existing template in the database. An error is returned if a template with the given team id and template id is not found.
func DeleteUser ¶
DeleteUser deletes the given user account. To ensure that there is always at least one user account with the Admin role, this function will refuse to delete the last Admin.
This only removes the account itself - campaigns, pages, templates, groups, and sending profiles the user created are team-owned (visible to and editable by every team member, see rbac.go's design note), so they're left in place for the rest of the team rather than cascade-deleted.
func DeleteWebhook ¶
DeleteWebhook deletes an existing webhook in the database. An error is returned if a webhook with the given id isn't found.
func EnsureEnoughAdmins ¶
func EnsureEnoughAdmins() error
EnsureEnoughAdmins ensures that there is more than one user account in Gophish with the Admin role. This function is meant to be called before modifying a user account with the Admin role in a non-revokable way.
func ExchangeOAuthCode ¶
func ExchangeOAuthCode(ctx context.Context, im *IMAP, redirectURL, code string) (*oauth2.Token, error)
ExchangeOAuthCode exchanges an OAuth2 authorization code (as received on the /oauth/imap/callback redirect) for a token, via the SSRF-restricted HTTP client.
func ExecuteTemplate ¶
ExecuteTemplate creates a templated string based on the provided template body and data.
func GenerateMailLog ¶
GenerateMailLog creates a new maillog for the given campaign and result. It sets the initial send date to match the campaign's launch date.
func GetValidAccessToken ¶
GetValidAccessToken returns a currently-valid OAuth2 access token for the IMAP config, transparently refreshing (and persisting the refreshed token) if the cached one is expired or about to expire. Returns ErrOAuthNotConnected if no account has been connected yet.
func IncrementNonCampaignEmails ¶
IncrementNonCampaignEmails adds n to the count of emails reported through this mailbox that did not match a known Gophish campaign
func LockMailLogs ¶
LockMailLogs locks or unlocks a slice of maillogs for processing.
func OAuthConfig ¶
OAuthConfig builds the oauth2.Config for the IMAP config's provider, ready to use for the authorization-code flow.
func Ping ¶
func Ping() error
Ping verifies that the database connection is alive. Used by the /readyz endpoint for Kubernetes-style readiness probes.
func PostCampaign ¶
PostCampaign inserts a campaign and all associated records into the database. uid is the creating user (attribution only); teamID determines which team's templates/pages/groups/sending profiles the campaign can draw from, and which team the resulting campaign belongs to.
func PostEmailRequest ¶
func PostEmailRequest(s *EmailRequest) error
PostEmailRequest stores a SendTestEmailRequest in the database.
func PostTag ¶ added in v0.18.0
PostTag creates a new tag for the team. Tags are usually created implicitly by tagging an object, but the explicit endpoint lets the UI pre-create a tag (e.g. to assign a color).
func PostTemplate ¶
PostTemplate creates a new template in the database.
func PostWebhook ¶
PostWebhook creates a new webhook in the database.
func PutPage ¶
PutPage edits an existing Page in the database. Per the PUT Method RFC, it presumes all data for a page is provided.
func PutSMTP ¶
PutSMTP edits an existing SMTP in the database. Per the PUT Method RFC, it presumes all data for a SMTP is provided.
func PutTag ¶ added in v0.18.0
PutTag renames and/or recolors an existing tag. The unique (team_id, name) index enforces name collisions, surfaced to the caller as gorm.ErrDuplicatedKey.
func PutTemplate ¶
PutTemplate edits an existing template in the database. Per the PUT Method RFC, it presumes all data for a template is provided.
func PutWebhook ¶
PutWebhook edits an existing webhook in the database.
func RecordLoginError ¶
RecordLoginError records a failed IMAP login attempt, incrementing the consecutive error count and storing the error message
func ScrubCampaign ¶ added in v0.18.0
ScrubCampaign permanently anonymizes a campaign's results and events, leaving the aggregate outcome data intact. This is how anonymous campaigns are realized (see #57) and is irreversible.
Recipient identity is not simply blanked but replaced with a stable, non-PII pseudonym derived from each result's RId: names become a placeholder, and the email, which the reporting UI uses to group events by recipient, becomes the pseudonym in both the result and its events, so each recipient keeps a distinct, correctly separated timeline.
func Setup ¶
Setup initializes the database and runs any needed migrations.
First, it establishes a connection to the database, then runs any migrations newer than the version the database is on.
Once the database is up-to-date, we create an admin user (if needed) that has a randomly generated API key and password.
func StoreOAuthToken ¶
StoreOAuthToken encrypts and persists the given token onto the IMAP config, as a result of either the initial authorization-code exchange or a later refresh.
IMAP has no primary key (see PostIMAP), so this can't go through db.Save() - like SuccessfulLogin, it targets the row explicitly by user_id via an Updates map (whose keys are literal column names, not Go field names).
func SuccessfulLogin ¶
SuccessfulLogin records a successful IMAP login, resetting the consecutive error backoff and clearing any previously recorded error
func TaggedIDs ¶ added in v0.18.0
TaggedIDs returns the ids of objects of the given type in the team that carry at least one of the named tags (OR semantics). An empty name set returns no ids.
func UnlockAllMailLogs ¶
func UnlockAllMailLogs() error
UnlockAllMailLogs removes the processing lock for all maillogs in the database. This is intended to be called when Gophish is started so that any previously locked maillogs can resume processing.
func UpdateTarget ¶
UpdateTarget updates the given target information in the database.
func ValidateTemplate ¶
ValidateTemplate ensures that the provided text in the page or template uses the supported template variables correctly.
Types ¶
type Attachment ¶
type Attachment struct {
Id int64 `json:"-"`
TemplateId int64 `json:"-"`
Content string `json:"content"`
Type string `json:"type"`
Name string `json:"name"`
// contains filtered or unexported fields
}
Attachment contains the fields and methods for an email attachment
func (*Attachment) ApplyTemplate ¶
func (a *Attachment) ApplyTemplate(ptx PhishingTemplateContext) (io.Reader, error)
ApplyTemplate parses different attachment files and applies the supplied phishing template.
func (Attachment) Validate ¶
func (a Attachment) Validate() error
Validate ensures that the provided attachment uses the supported template variables correctly.
type BaseRecipient ¶
type BaseRecipient struct {
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Position string `json:"position"`
}
BaseRecipient contains the fields for a single recipient. This is the base struct used in members of groups and campaign results.
func (*BaseRecipient) FormatAddress ¶
func (r *BaseRecipient) FormatAddress() string
FormatAddress returns the email address to use in the "To" header of the email
type Campaign ¶
type Campaign struct {
Id int64 `json:"id"`
UserId int64 `json:"-"`
TeamId int64 `json:"-" gorm:"column:team_id"`
Name string `json:"name" gorm:"not null"`
CreatedDate time.Time `json:"created_date"`
LaunchDate time.Time `json:"launch_date"`
SendByDate time.Time `json:"send_by_date"`
CompletedDate time.Time `json:"completed_date"`
TemplateId int64 `json:"-"`
Template Template `json:"template"`
PageId int64 `json:"-"`
Page Page `json:"page"`
Status string `json:"status"`
Results []Result `json:"results,omitempty"`
// Groups is only used as transient input when creating a campaign
// (expanded into Results at creation time); there's no persisted
// campaign<->group relation for gorm to manage.
Groups []Group `json:"groups,omitempty" gorm:"-"`
Events []Event `json:"timeline,omitempty"`
SMTPId int64 `json:"-"`
SMTP SMTP `json:"smtp"`
URL string `json:"url"`
Tags []string `json:"tags" gorm:"-"`
// ScrubOnComplete flags the campaign to have its recipient-identifying
// data scrubbed automatically when it completes (anonymous campaigns).
ScrubOnComplete bool `json:"scrub_on_complete"`
// ScrubbedDate is set when the campaign's results/events have been
// scrubbed. A non-zero value marks the campaign as anonymized and makes
// scrubbing idempotent.
ScrubbedDate time.Time `json:"scrubbed_date"`
// AutoCompleteAfterDays, when > 0, tells the background worker to
// complete this campaign automatically that many days after its send-by
// date (or launch date, when no send-by date is set). 0 means the
// campaign is only completed manually.
AutoCompleteAfterDays int `json:"auto_complete_after_days" gorm:"not null;default:0"`
}
Campaign is a struct representing a created campaign
func GetCampaign ¶
GetCampaign returns the campaign, if it exists, specified by the given id and team_id.
func GetCampaignMailContext ¶
GetCampaignMailContext returns a campaign object with just the relevant data needed to generate and send emails. This includes the top-level metadata, the template, and the sending profile.
This should only ever be used if you specifically want this lightweight context, since it returns a non-standard campaign object. ref: #1726
func GetCampaignPhishContext ¶
GetCampaignPhishContext returns a campaign object with just the relevant data needed to serve a landing page and record an event for a target (open, click, or form submission). This includes the top-level metadata and the sending profile (needed for the "From" address used in template rendering) - notably not the template, nor the potentially large Results/Events history.
This should only ever be used if you specifically want this lightweight context, since it returns a non-standard campaign object. Loading the full Results/Events history here would make every landing page hit scale with the campaign's size. ref: #2527
func GetCampaigns ¶
GetCampaigns returns the campaigns visible to the given team.
func GetCampaignsToAutoComplete ¶ added in v0.18.0
GetCampaignsToAutoComplete returns campaigns that have opted into automatic completion (auto_complete_after_days > 0), are not already complete, and whose grace period has elapsed as of t. The grace period is measured from the send-by date - or the launch date, when no send-by date was set - so that opens, clicks and reports that trickle in after the last email is sent still land in the campaign before it's closed.
func GetQueuedCampaigns ¶
GetQueuedCampaigns returns the campaigns that are queued up for this given minute
func (*Campaign) UpdateStatus ¶
UpdateStatus changes the campaign status appropriately
type CampaignMeta ¶ added in v0.18.0
type CampaignMeta struct {
Name string `json:"name"`
Status string `json:"status"`
CreatedDate time.Time `json:"created_date"`
LaunchDate time.Time `json:"launch_date"`
CompletedDate time.Time `json:"completed_date"`
// ScrubbedDate is the zero value unless the campaign has been anonymized
ScrubbedDate time.Time `json:"scrubbed_date"`
TemplateName string `json:"template_name"`
SMTPName string `json:"smtp_name"`
}
CampaignMeta carries the descriptive, non-metric context a report needs to stand on its own as an evidence artifact: what was tested, when, and whether the data has been anonymized. None of it is recipient PII - the template and sending-profile names describe the pretext, not any target. TemplateName and SMTPName fall back to "[Deleted]" when the referenced object no longer exists, so the report never silently omits the pretext it measured.
type CampaignRates ¶ added in v0.18.0
type CampaignRates struct {
Open float64 `json:"open"`
Click float64 `json:"click"`
Submit float64 `json:"submit"`
Report float64 `json:"report"`
}
CampaignRates holds the funnel rates as fractions in the range [0, 1], relative to the total number of recipients. Consumers format them as percentages. Each rate is cumulative in the same sense as CampaignStats: a recipient counted at a later stage is also counted at every earlier one.
type CampaignReport ¶ added in v0.18.0
type CampaignReport struct {
CampaignId int64 `json:"campaign_id"`
// Anonymized reflects whether the campaign has been scrubbed
Anonymized bool `json:"anonymized"`
Meta CampaignMeta `json:"meta"`
Stats CampaignStats `json:"stats"`
Rates CampaignRates `json:"rates"`
Timing CampaignTiming `json:"timing"`
Timeline []ReportBucket `json:"timeline"`
}
CampaignReport is the aggregated, PII-free view of a campaign's outcome. It is produced identically for normal and anonymized campaigns
func GetCampaignReport ¶ added in v0.18.0
func GetCampaignReport(id int64, teamID int64) (CampaignReport, error)
GetCampaignReport builds the aggregated report for the campaign identified by id and visible to teamID. It reuses getCampaignStats for the funnel counts and derives rates, timing, and the engagement timeline from the campaign's events.
type CampaignResults ¶
type CampaignResults struct {
Id int64 `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
TemplateId int64 `json:"-"`
Template Template `json:"template"`
PageId int64 `json:"-"`
Page Page `json:"page"`
// LaunchDate/SendByDate/AutoCompleteAfterDays let the results page show
// when the campaign will auto-complete (if opted in). They're populated
// from the campaigns row alongside the other columns.
LaunchDate time.Time `json:"launch_date"`
SendByDate time.Time `json:"send_by_date"`
AutoCompleteAfterDays int `json:"auto_complete_after_days"`
// ScrubbedDate is non-zero when the campaign has been anonymized; the UI
// uses it to reflect the scrubbed state.
ScrubbedDate time.Time `json:"scrubbed_date"`
// Results/Events are populated manually via separate queries, not a
// gorm relation - Result/Event's CampaignId satisfies Campaign's FK
// convention, not CampaignResults'.
Results []Result `json:"results,omitempty" gorm:"-"`
Events []Event `json:"timeline,omitempty" gorm:"-"`
}
CampaignResults is a struct representing the results from a campaign
func GetCampaignResults ¶
func GetCampaignResults(id int64, teamID int64) (CampaignResults, error)
GetCampaignResults returns just the campaign results for the given campaign
type CampaignStats ¶
type CampaignStats struct {
Total int64 `json:"total"`
EmailsSent int64 `json:"sent"`
OpenedEmail int64 `json:"opened"`
ClickedLink int64 `json:"clicked"`
SubmittedData int64 `json:"submitted_data"`
EmailReported int64 `json:"email_reported"`
Error int64 `json:"error"`
}
CampaignStats is a struct representing the statistics for a single campaign
type CampaignSummaries ¶
type CampaignSummaries struct {
Total int64 `json:"total"`
// Campaigns is populated manually, not via a gorm relation.
Campaigns []CampaignSummary `json:"campaigns" gorm:"-"`
}
CampaignSummaries is a struct representing the overview of campaigns
func GetCampaignSummaries ¶
func GetCampaignSummaries(teamID int64) (CampaignSummaries, error)
GetCampaignSummaries gets the summary objects for all the campaigns visible to the given team
type CampaignSummary ¶
type CampaignSummary struct {
Id int64 `json:"id"`
CreatedDate time.Time `json:"created_date"`
LaunchDate time.Time `json:"launch_date"`
SendByDate time.Time `json:"send_by_date"`
CompletedDate time.Time `json:"completed_date"`
Status string `json:"status"`
Name string `json:"name"`
// Stats is populated manually after the query, not via a gorm relation.
Stats CampaignStats `json:"stats" gorm:"-"`
Tags []string `json:"tags" gorm:"-"`
}
CampaignSummary is a struct representing the overview of a single camaign
func GetCampaignSummary ¶
func GetCampaignSummary(id int64, teamID int64) (CampaignSummary, error)
GetCampaignSummary gets the summary object for a campaign specified by the campaign ID
type CampaignTiming ¶ added in v0.18.0
type CampaignTiming struct {
Open StageTiming `json:"open"`
Click StageTiming `json:"click"`
Submit StageTiming `json:"submit"`
}
CampaignTiming groups the per-stage timing summaries. Because events do not cascade (a click is not recorded as an implicit open), each stage reflects only recipients with that stage's event actually recorded.
type Dialer ¶
Dialer is a wrapper around a standard gomail.Dialer in order to implement the mailer.Dialer interface. This allows us to better separate the mailer package as opposed to forcing a connection between mailer and gomail.
type EmailRequest ¶
type EmailRequest struct {
Id int64 `json:"-"`
Template Template `json:"template"`
TemplateId int64 `json:"-"`
Page Page `json:"page"`
PageId int64 `json:"-"`
// SMTP has no smtp_id/smtp column in email_requests - it's populated
// transiently (e.g. for test-email requests), never persisted as its
// own relation.
SMTP SMTP `json:"smtp" gorm:"-"`
URL string `json:"url"`
Tracker string `json:"tracker" gorm:"-"`
TrackingURL string `json:"tracking_url" gorm:"-"`
UserId int64 `json:"-"`
TeamId int64 `json:"-" gorm:"column:team_id"`
ErrorChan chan (error) `json:"-" gorm:"-"`
RId string `json:"id"`
FromAddress string `json:"-"`
BaseRecipient
}
EmailRequest is the structure of a request to send a test email to test an SMTP connection. This type implements the mailer.Mail interface.
func GetEmailRequestByResultId ¶
func GetEmailRequestByResultId(id string) (EmailRequest, error)
GetEmailRequestByResultId retrieves the EmailRequest by the underlying rid parameter.
func (*EmailRequest) Backoff ¶
func (s *EmailRequest) Backoff(reason error) error
Backoff treats temporary errors as permanent since this is expected to be a synchronous operation. It returns any errors given back to the ErrorChan
func (*EmailRequest) Error ¶
func (s *EmailRequest) Error(err error) error
Error returns an error on the ErrorChan.
func (*EmailRequest) Generate ¶
func (s *EmailRequest) Generate(msg *gomail.Message) error
Generate fills in the details of a gomail.Message with the contents from the SendTestEmailRequest.
func (*EmailRequest) GetDialer ¶
func (s *EmailRequest) GetDialer() (mailer.Dialer, error)
GetDialer returns the mailer.Dialer for the underlying SMTP object
func (*EmailRequest) GetSendRate ¶
func (s *EmailRequest) GetSendRate() int
GetSendRate returns the send rate configured on the request's SMTP profile. Test emails are single messages, so this has no practical effect, but it satisfies the mailer.Mail interface.
func (*EmailRequest) GetSmtpFrom ¶
func (s *EmailRequest) GetSmtpFrom() (string, error)
func (*EmailRequest) Success ¶
func (s *EmailRequest) Success() error
Success returns nil on the ErrorChan to indicate that the email was sent successfully.
func (*EmailRequest) Validate ¶
func (s *EmailRequest) Validate() error
Validate ensures the SendTestEmailRequest structure is valid.
type Event ¶
type Event struct {
Id int64 `json:"-"`
CampaignId int64 `json:"campaign_id"`
Email string `json:"email"`
Time time.Time `json:"time"`
Message string `json:"message"`
Details string `json:"details"`
}
Event contains the fields for an event that occurs during the campaign
type EventDetails ¶
type EventDetails struct {
Payload url.Values `json:"payload"`
Browser map[string]string `json:"browser"`
}
EventDetails is a struct that wraps common attributes we want to store in an event
type EventError ¶
type EventError struct {
Error string `json:"error"`
}
EventError is a struct that wraps an error that occurs when sending an email to a recipient
type Group ¶
type Group struct {
Id int64 `json:"id"`
UserId int64 `json:"-"`
TeamId int64 `json:"-" gorm:"column:team_id"`
Name string `json:"name"`
ModifiedDate time.Time `json:"modified_date"`
Targets []Target `json:"targets" gorm:"-"`
Tags []string `json:"tags" gorm:"-"`
}
Group contains the fields needed for a user -> group mapping Groups contain 1..* Targets
func GetGroupByName ¶
GetGroupByName returns the group, if it exists, specified by the given name and team_id.
type GroupSummaries ¶
type GroupSummaries struct {
Total int64 `json:"total"`
// Groups is populated manually, not via a gorm relation.
Groups []GroupSummary `json:"groups" gorm:"-"`
}
GroupSummaries is a struct representing the overview of Groups.
func GetGroupSummaries ¶
func GetGroupSummaries(teamID int64) (GroupSummaries, error)
GetGroupSummaries returns the summaries for the groups visible to the given team.
type GroupSummary ¶
type GroupSummary struct {
Id int64 `json:"id"`
Name string `json:"name"`
ModifiedDate time.Time `json:"modified_date"`
NumTargets int64 `json:"num_targets"`
Tags []string `json:"tags" gorm:"-"`
}
GroupSummary represents a summary of the Group model. The only difference is that, instead of listing the Targets (which could be expensive for large groups), it lists the target count.
func GetGroupSummary ¶
func GetGroupSummary(id int64, teamID int64) (GroupSummary, error)
GetGroupSummary returns the summary for the requested group
type GroupTarget ¶
GroupTarget is used for a many-to-many relationship between 1..* Groups and 1..* Targets
type Header ¶
type Header struct {
Id int64 `json:"-"`
SMTPId int64 `json:"-"`
Key string `json:"key"`
Value string `json:"value"`
}
Header contains the fields and methods for a sending profile to have custom headers
type IMAP ¶
type IMAP struct {
// IMAP is intentionally NOT team-scoped like the other owned models -
// it holds one specific person's connected mailbox credentials/OAuth
// grant, not a shared campaign asset. Making it team-visible would let
// teammates see (and potentially reconnect/hijack) each other's
// personal email accounts.
UserId int64 `json:"-" gorm:"column:user_id"`
Enabled bool `json:"enabled"`
Host string `json:"host"`
Port uint16 `json:"port,string,omitempty"`
Username string `json:"username"`
Password string `json:"password"`
TLS bool `json:"tls"`
IgnoreCertErrors bool `json:"ignore_cert_errors"`
Folder string `json:"folder"`
RestrictDomain string `json:"restrict_domain"`
DeleteReportedCampaignEmail bool `json:"delete_reported_campaign_email"`
LastLogin time.Time `json:"last_login,omitempty"`
ModifiedDate time.Time `json:"modified_date"`
IMAPFreq uint32 `json:"imap_freq,string,omitempty"`
// ConsecutiveLoginErrors counts login attempts that have failed since
// the last successful one
ConsecutiveLoginErrors uint32 `json:"consecutive_login_errors,omitempty" gorm:"column:consecutive_login_errors"`
// LastLoginError holds the error message of the most recent failed
// login
LastLoginError string `json:"last_login_error,omitempty" gorm:"column:last_login_error"`
// NonCampaignEmailsCount counts emails reported through this mailbox
// that didnt match a known Gophish campaign
NonCampaignEmailsCount uint32 `json:"non_campaign_emails_count,omitempty" gorm:"column:non_campaign_emails_count"`
// AuthType selects between Basic Auth (the default, existing behavior)
// and OAuth2
AuthType string `json:"auth_type" gorm:"column:auth_type"`
OAuthProvider string `json:"oauth_provider,omitempty" gorm:"column:oauth_provider"`
OAuthTenantID string `json:"oauth_tenant_id,omitempty" gorm:"column:oauth_tenant_id"`
OAuthClientID string `json:"oauth_client_id,omitempty" gorm:"column:oauth_client_id"`
OAuthClientSecret string `json:"oauth_client_secret,omitempty" gorm:"column:oauth_client_secret"`
// OAuthAuthURL/OAuthTokenURL are only used (and shown in the UI) when
// OAuthProvider is "custom" - well-known providers use fixed endpoints
// from oauthEndpoint in oauth_imap.go.
OAuthAuthURL string `json:"oauth_auth_url,omitempty" gorm:"column:oauth_auth_url"`
OAuthTokenURL string `json:"oauth_token_url,omitempty" gorm:"column:oauth_token_url"`
// OAuthScopes is a space-separated OAuth2 scope list. Required for the
// "custom" provider (there's no sane default for an arbitrary IMAP
// OAuth2 server); optional for google/microsoft, where it overrides
// the built-in default scopes from oauthScopes in oauth_imap.go.
OAuthScopes string `json:"oauth_scopes,omitempty" gorm:"column:oauth_scopes"`
// OAuthRefreshTokenEnc/OAuthAccessTokenEnc are AES-256-GCM encrypted
// (see the crypto package) and never exposed over JSON - they're only
// ever written by the OAuth callback handler and read by
// GetValidAccessToken.
OAuthRefreshTokenEnc string `json:"-" gorm:"column:oauth_refresh_token_enc"`
OAuthAccessTokenEnc string `json:"-" gorm:"column:oauth_access_token_enc"`
OAuthTokenExpiry time.Time `json:"-" gorm:"column:oauth_token_expiry"`
}
IMAP contains the attributes needed to handle logging into an IMAP server to check for reported emails
type MailLog ¶
type MailLog struct {
Id int64 `json:"-"`
UserId int64 `json:"-"`
TeamId int64 `json:"-" gorm:"column:team_id"`
CampaignId int64 `json:"campaign_id"`
RId string `json:"id"`
SendDate time.Time `json:"send_date"`
SendAttempt int `json:"send_attempt"`
Processing bool `json:"-"`
// contains filtered or unexported fields
}
MailLog is a struct that holds information about an email that is to be sent out.
func GetMailLogByRId ¶
GetMailLogByRId returns the mail log for the given result ID, if one exists. A permanent send failure (MailLog.Error) deletes the mail log, so this returns gorm.ErrRecordNotFound in that case - callers that need to resend a failed result should treat that as "generate a new one" rather than an error
func GetMailLogsByCampaign ¶
GetMailLogsByCampaign returns all of the mail logs for a given campaign.
func GetQueuedMailLogs ¶
GetQueuedMailLogs returns the mail logs that are queued up for the given minute.
func (*MailLog) Backoff ¶
Backoff sets the MailLog SendDate to be the next entry in an exponential backoff. ErrMaxRetriesExceeded is thrown if this maillog has been retried too many times. Backoff also unlocks the maillog so that it can be processed again in the future.
func (*MailLog) CacheCampaign ¶
CacheCampaign allows bulk-mail workers to cache the otherwise expensive campaign lookup operation by providing a pointer to the campaign here.
func (*MailLog) Error ¶
Error sets the error status on the models.Result that the maillog refers to. Since MailLog errors are permanent, this action also deletes the maillog.
func (*MailLog) Generate ¶
Generate fills in the details of a gomail.Message instance with the correct headers and body from the campaign and recipient listed in the maillog. We accept the gomail.Message as an argument so that the caller can choose to re-use the message across recipients.
func (*MailLog) GetDialer ¶
GetDialer returns a dialer based on the maillog campaign's SMTP configuration
func (*MailLog) GetSendRate ¶
GetSendRate returns the send rate (emails/sec) configured on the maillog's campaign's SMTP profile. Returns 0 (unlimited) if the campaign can't be looked up.
func (*MailLog) GetSmtpFrom ¶
func (*MailLog) Lock ¶
Lock sets the processing flag so that other processes cannot modify the maillog
type Page ¶
type Page struct {
Id int64 `json:"id" gorm:"column:id;primaryKey"`
UserId int64 `json:"-" gorm:"column:user_id"`
TeamId int64 `json:"-" gorm:"column:team_id"`
Name string `json:"name"`
HTML string `json:"html" gorm:"column:html"`
CaptureCredentials bool `json:"capture_credentials" gorm:"column:capture_credentials"`
CapturePasswords bool `json:"capture_passwords" gorm:"column:capture_passwords"`
RedirectURL string `json:"redirect_url" gorm:"column:redirect_url"`
ModifiedDate time.Time `json:"modified_date"`
RedirectMode string `json:"redirect_mode" gorm:"column:redirect_mode"` // "url" or "html"
RedirectHTML string `json:"redirect_html" gorm:"column:redirect_html"`
Tags []string `json:"tags" gorm:"-"`
}
Page contains the fields used for a Page model
func GetPageByName ¶
GetPageByName returns the page, if it exists, specified by the given name and team_id.
type Permission ¶
type Permission struct {
ID int64 `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
Description string `json:"description"`
}
Permission determines what a particular role can do. Each role may have one or more permissions.
type PhishingTemplateContext ¶
type PhishingTemplateContext struct {
From string
URL string
Tracker string
TrackingURL string
RId string
BaseURL string
// Domain is the portion of the recipient's Email after the "@", e.g.
// "example.com" for "foo@example.com". Empty if the email has no "@".
Domain string
BaseRecipient
}
PhishingTemplateContext is the context that is sent to any template, such as the email or landing page content.
func NewPhishingTemplateContext ¶
func NewPhishingTemplateContext(ctx TemplateContext, r BaseRecipient, rid string) (PhishingTemplateContext, error)
NewPhishingTemplateContext returns a populated PhishingTemplateContext, parsing the correct fields from the provided TemplateContext and recipient.
type ReportBucket ¶ added in v0.18.0
type ReportBucket struct {
Time time.Time `json:"time"`
Opened int `json:"opened"`
Clicked int `json:"clicked"`
Submitted int `json:"submitted"`
}
ReportBucket is one time slice of the engagement timeline. Time is the bucket's start; the counts are the engagement events that fell within it. Reporting has no timeline: it is a boolean flag on the result with no timestamp, so it is reflected in Stats/Rates only.
type Response ¶
type Response struct {
Message string `json:"message"`
Success bool `json:"success"`
Data interface{} `json:"data"`
}
Response contains the attributes found in an API response
type Result ¶
type Result struct {
Id int64 `json:"-"`
CampaignId int64 `json:"-"`
UserId int64 `json:"-"`
TeamId int64 `json:"-" gorm:"column:team_id"`
RId string `json:"id"`
Status string `json:"status" gorm:"not null"`
IP string `json:"ip"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
SendDate time.Time `json:"send_date"`
Reported bool `json:"reported" gorm:"not null"`
ModifiedDate time.Time `json:"modified_date"`
BaseRecipient
}
Result contains the fields for a result object, which is a representation of a target in a campaign.
func (*Result) GenerateId ¶
GenerateId generates a unique key to represent the result in the database
func (*Result) HandleClickedLink ¶
func (r *Result) HandleClickedLink(details EventDetails) error
HandleClickedLink updates a Result in the case where the recipient clicked the link in an email.
func (*Result) HandleEmailBackoff ¶
HandleEmailBackoff updates a Result to indicate that the email received a temporary error and needs to be retried
func (*Result) HandleEmailError ¶
HandleEmailError updates a Result to indicate that there was an error when attempting to send the email to the remote SMTP server.
func (*Result) HandleEmailOpened ¶
func (r *Result) HandleEmailOpened(details EventDetails) error
HandleEmailOpened updates a Result in the case where the recipient opened the email.
func (*Result) HandleEmailReport ¶
func (r *Result) HandleEmailReport(details EventDetails) error
HandleEmailReport updates a Result in the case where they report a simulated phishing email using the HTTP handler. The event and result are recorded with the current time.
func (*Result) HandleEmailReportAt ¶
func (r *Result) HandleEmailReportAt(details EventDetails, reportedTime time.Time) error
HandleEmailReportAt behaves like HandleEmailReport, but records the event and result as having happened at reportedTime instead of the current time. This is used when an admin manually marks a result as reported and knows it actually happened earlier (e.g. reported through a channel Gophish doesn't see, like forwarding to IT). A zero reportedTime falls back to the current time.
func (*Result) HandleEmailSent ¶
HandleEmailSent updates a Result to indicate that the email has been successfully sent to the remote SMTP server
func (*Result) HandleFormSubmit ¶
func (r *Result) HandleFormSubmit(details EventDetails) error
HandleFormSubmit updates a Result in the case where the recipient submitted credentials to the form on a Landing Page.
func (*Result) Resend ¶
Resend resets a failed Result so the background worker will attempt to send it again on its next tick. Only valid for results with an Error status - the failure could be transient (rate limiting, a typo in the address since fixed, a temporary mail server issue), and there was previously no way to retry a single recipient without recreating the whole campaign. See gophish/gophish#79.
type Role ¶
type Role struct {
ID int64 `json:"-"`
Slug string `json:"slug"`
Name string `json:"name"`
Description string `json:"description"`
Permissions []Permission `json:"-" gorm:"many2many:role_permissions;"`
}
Role represents a user role within Gophish. Each user has a single role which maps to a set of permissions.
func GetRoleBySlug ¶
GetRoleBySlug returns a role that can be assigned to a user.
type SMTP ¶
type SMTP struct {
Id int64 `json:"id" gorm:"column:id;primaryKey"`
UserId int64 `json:"-" gorm:"column:user_id"`
TeamId int64 `json:"-" gorm:"column:team_id"`
Interface string `json:"interface_type" gorm:"column:interface_type"`
Name string `json:"name"`
Host string `json:"host"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
FromAddress string `json:"from_address"`
IgnoreCertErrors bool `json:"ignore_cert_errors"`
// SendRate is the maximum number of emails to send per second for this
// profile. 0 means unlimited.
SendRate int `json:"send_rate"`
// CC is a comma-separated list of emails. Empty means no CC
CC string `json:"cc,omitempty"`
Headers []Header `json:"headers"`
ModifiedDate time.Time `json:"modified_date"`
Tags []string `json:"tags" gorm:"-"`
}
SMTP contains the attributes needed to handle the sending of campaign emails
func GetSMTPByName ¶
GetSMTPByName returns the SMTP, if it exists, specified by the given name and team_id.
func (*SMTP) CCAddresses ¶
CCAddresses splits the comma-separated CC field into individual, trimmed email addresses, skipping empty entries
type StageTiming ¶ added in v0.18.0
type StageTiming struct {
Count int `json:"count"`
Median time.Duration `json:"median"`
Average time.Duration `json:"average"`
}
StageTiming summarizes how long recipients took to reach a funnel stage, measured from each recipient's "Email Sent" event. Count is the number of recipients with a measurable delta for the stage, which is also the sample size behind Median and Average.
type Tag ¶ added in v0.18.0
type Tag struct {
Id int64 `json:"id" gorm:"column:id;primaryKey"`
TeamId int64 `json:"-" gorm:"column:team_id"`
Name string `json:"name"`
Color string `json:"color,omitempty"`
ModifiedDate time.Time `json:"modified_date"`
}
Tag is a team-scoped label that can be attached to any taggable object (templates, pages, sending profiles, campaigns, groups) via the taggables join table. Tags are shared across object types within a team: a "de" tag is a single row that can label both a template and a page.
type Target ¶
type Target struct {
Id int64 `json:"-"`
BaseRecipient
}
Target contains the fields needed for individual targets specified by the user Groups contain 1..* Targets, but 1 Target may belong to 1..* Groups
func GetTargets ¶
GetTargets performs a many-to-many select to get all the Targets for a Group
func (*Target) FormatAddress ¶
FormatAddress returns the email address to use in the "To" header of the email
type Team ¶
type Team struct {
Id int64 `json:"id"`
Name string `json:"name" gorm:"column:name;not null;unique"`
ModifiedDate time.Time `json:"modified_date"`
}
Team groups users together so that the objects they create (campaigns, templates, pages, groups, sending profiles, IMAP configs) are visible to every member of the team, rather than being strictly siloed to the individual creator. See the design note in rbac.go.
func GetOrCreateTeamByName ¶
GetOrCreateTeamByName returns the team with the given name, creating it if it doesn't already exist. There's no dedicated team management UI - admins assign a team to a user by name directly on that user's account, so a not-yet-seen name is how a new team gets created.
func GetTeam ¶
GetTeam returns the team that the given id corresponds to. If no team is found, an error is thrown.
func GetTeamByName ¶
GetTeamByName returns the team with the given name. If no team is found, an error is thrown.
type Template ¶
type Template struct {
Id int64 `json:"id" gorm:"column:id;primaryKey"`
UserId int64 `json:"-" gorm:"column:user_id"`
TeamId int64 `json:"-" gorm:"column:team_id"`
Name string `json:"name"`
EnvelopeSender string `json:"envelope_sender"`
Subject string `json:"subject"`
Text string `json:"text"`
HTML string `json:"html" gorm:"column:html"`
ModifiedDate time.Time `json:"modified_date"`
Attachments []Attachment `json:"attachments"`
Tags []string `json:"tags" gorm:"-"`
}
Template models hold the attributes for an email template to be sent to targets
func GetTemplate ¶
GetTemplate returns the template, if it exists, specified by the given id and team_id.
func GetTemplateByName ¶
GetTemplateByName returns the template, if it exists, specified by the given name and team_id.
func GetTemplates ¶
GetTemplates returns the templates visible to the given team.
type TemplateContext ¶
type TemplateContext interface {
// contains filtered or unexported methods
}
TemplateContext is an interface that allows both campaigns and email requests to have a PhishingTemplateContext generated for them.
type User ¶
type User struct {
Id int64 `json:"id"`
Username string `json:"username" gorm:"not null;unique"`
Hash string `json:"-"`
ApiKey string `json:"api_key" gorm:"not null;unique"`
// gorm v2 defaults to not auto-saving/creating associations on Save,
// which is the behavior the v1 association_autoupdate/autocreate tags
// used to opt into explicitly.
Role Role `json:"role"`
RoleID int64 `json:"-"`
Team Team `json:"team"`
TeamID int64 `json:"-"`
PasswordChangeRequired bool `json:"password_change_required"`
AccountLocked bool `json:"account_locked"`
LastLogin time.Time `json:"last_login"`
}
User represents the user model for gophish.
func GetUser ¶
GetUser returns the user that the given id corresponds to. If no user is found, an error is thrown.
func GetUserByAPIKey ¶
GetUserByAPIKey returns the user that the given API Key corresponds to. If no user is found, an error is thrown.
func GetUserByUsername ¶
GetUserByUsername returns the user that the given username corresponds to. If no user is found, an error is thrown.
type ValidationContext ¶
ValidationContext is used for validating templates and pages
type Webhook ¶
type Webhook struct {
Id int64 `json:"id" gorm:"column:id;primaryKey"`
Name string `json:"name"`
URL string `json:"url"`
Secret string `json:"secret"`
IsActive bool `json:"is_active"`
}
Webhook represents the webhook model
func GetActiveWebhooks ¶
GetActiveWebhooks returns the active webhooks
func GetWebhook ¶
GetWebhook returns the webhook that the given id corresponds to. If no webhook is found, an error is returned.