2014-01-09 23:18:49 +00:00
package db
import (
"database/sql"
2014-02-05 16:57:53 +00:00
"errors"
2014-02-07 01:16:29 +00:00
"log"
"net/mail"
2014-01-09 23:18:49 +00:00
"os"
2014-01-31 04:46:25 +00:00
"time"
2014-01-09 23:18:49 +00:00
2014-01-30 21:08:14 +00:00
"github.com/coopernurse/gorp"
2014-01-09 23:18:49 +00:00
"github.com/jordan-wright/gophish/config"
2014-01-30 21:08:14 +00:00
"github.com/jordan-wright/gophish/models"
2014-01-09 23:18:49 +00:00
_ "github.com/mattn/go-sqlite3"
)
2014-01-30 21:08:14 +00:00
var Conn * gorp . DbMap
var DB * sql . DB
var err error
2014-02-05 16:57:53 +00:00
var ErrUsernameTaken = errors . New ( "Username already taken" )
2014-02-07 01:16:29 +00:00
var Logger = log . New ( os . Stdout , "" , log . Ldate | log . Ltime | log . Lshortfile )
2014-01-09 23:18:49 +00:00
// Setup initializes the Conn object
// It also populates the Gophish Config object
2014-01-30 21:08:14 +00:00
func Setup ( ) error {
DB , err := sql . Open ( "sqlite3" , config . Conf . DBPath )
Conn = & gorp . DbMap { Db : DB , Dialect : gorp . SqliteDialect { } }
2014-01-09 23:18:49 +00:00
//If the file already exists, delete it and recreate it
2014-01-30 21:08:14 +00:00
_ , err = os . Stat ( config . Conf . DBPath )
Conn . AddTableWithName ( models . User { } , "users" ) . SetKeys ( true , "Id" )
Conn . AddTableWithName ( models . Campaign { } , "campaigns" ) . SetKeys ( true , "Id" )
2014-02-01 22:35:16 +00:00
Conn . AddTableWithName ( models . Group { } , "groups" ) . SetKeys ( true , "Id" )
2014-01-09 23:18:49 +00:00
if err != nil {
2014-02-07 01:16:29 +00:00
Logger . Println ( "Database not found, recreating..." )
2014-01-13 04:39:40 +00:00
createTablesSQL := [ ] string {
//Create tables
2014-02-05 00:39:01 +00:00
` CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, hash VARCHAR(60) NOT NULL, api_key VARCHAR(32), UNIQUE(username), UNIQUE(api_key)); ` ,
2014-02-01 22:35:16 +00:00
` CREATE TABLE campaigns (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, created_date TIMESTAMP NOT NULL, completed_date TIMESTAMP, template TEXT, status TEXT NOT NULL, uid INTEGER, FOREIGN KEY (uid) REFERENCES users(id)); ` ,
2014-02-05 03:53:11 +00:00
` CREATE TABLE targets (id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL, UNIQUE(email)); ` ,
2014-02-06 17:14:51 +00:00
` CREATE TABLE groups (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, modified_date TIMESTAMP NOT NULL, UNIQUE(name)); ` ,
2014-02-04 21:23:09 +00:00
` CREATE TABLE user_groups (uid INTEGER NOT NULL, gid INTEGER NOT NULL, FOREIGN KEY (uid) REFERENCES users(id), FOREIGN KEY (gid) REFERENCES groups(id), UNIQUE(uid, gid)) ` ,
` CREATE TABLE group_targets (gid INTEGER NOT NULL, tid INTEGER NOT NULL, FOREIGN KEY (gid) REFERENCES groups(id), FOREIGN KEY (tid) REFERENCES targets(id), UNIQUE(gid, tid)); ` ,
2014-01-13 04:39:40 +00:00
}
2014-02-07 01:16:29 +00:00
Logger . Printf ( "Creating db at %s\n" , config . Conf . DBPath )
2014-01-13 04:39:40 +00:00
//Create the tables needed
for _ , stmt := range createTablesSQL {
2014-01-30 21:08:14 +00:00
_ , err = DB . Exec ( stmt )
2014-01-13 04:39:40 +00:00
if err != nil {
return err
}
}
//Create the default user
2014-01-30 21:08:14 +00:00
init_user := models . User {
2014-01-31 05:11:06 +00:00
Username : "admin" ,
2014-02-02 22:37:36 +00:00
Hash : "$2a$10$IYkPp0.QsM81lYYPrQx6W.U6oQGw7wMpozrKhKAHUBVL4mkm/EvAS" ,
2014-01-30 21:08:14 +00:00
APIKey : "12345678901234567890123456789012" ,
2014-01-13 04:39:40 +00:00
}
2014-01-30 21:08:14 +00:00
Conn . Insert ( & init_user )
2014-01-13 03:46:51 +00:00
if err != nil {
2014-02-07 01:16:29 +00:00
Logger . Println ( err )
2014-01-13 03:46:51 +00:00
}
2014-01-31 04:46:25 +00:00
c := models . Campaign {
Name : "Test Campaigns" ,
CreatedDate : time . Now ( ) . UTC ( ) ,
CompletedDate : time . Now ( ) . UTC ( ) ,
Template : "test template" ,
Status : "In progress" ,
Uid : init_user . Id ,
}
Conn . Insert ( & c )
2014-01-09 23:18:49 +00:00
}
return nil
}
2014-02-05 16:57:53 +00:00
// API Functions (GET, POST, PUT, DELETE)
// GetUser returns the user that the given id corresponds to. If no user is found, an
// error is thrown.
func GetUser ( id int64 ) ( models . User , error ) {
u := models . User { }
err := Conn . SelectOne ( & u , "SELECT * FROM Users WHERE id=?" , id )
if err != nil {
return u , err
}
return u , nil
}
// GetUserByAPIKey returns the user that the given API Key corresponds to. If no user is found, an
// error is thrown.
func GetUserByAPIKey ( key [ ] byte ) ( models . User , error ) {
u := models . User { }
err := Conn . SelectOne ( & u , "SELECT id, username, api_key FROM Users WHERE apikey=?" , key )
if err != nil {
return u , err
}
return u , nil
}
2014-02-11 23:32:29 +00:00
// GetUserByUsername returns the user that the given username corresponds to. If no user is found, an
2014-02-05 16:57:53 +00:00
// error is thrown.
func GetUserByUsername ( username string ) ( models . User , error ) {
u := models . User { }
err := Conn . SelectOne ( & u , "SELECT * FROM Users WHERE username=?" , username )
if err != sql . ErrNoRows {
return u , ErrUsernameTaken
} else if err != nil {
return u , err
}
return u , nil
}
2014-02-11 23:32:29 +00:00
// PutUser updates the given user
2014-02-05 16:57:53 +00:00
func PutUser ( u * models . User ) error {
_ , err := Conn . Update ( u )
return err
}
2014-02-11 23:32:29 +00:00
// GetCampaigns returns the campaigns owned by the given user.
2014-02-10 01:34:47 +00:00
func GetCampaigns ( uid int64 ) ( [ ] models . Campaign , error ) {
2014-02-05 16:57:53 +00:00
cs := [ ] models . Campaign { }
2014-02-10 01:34:47 +00:00
_ , err := Conn . Select ( & cs , "SELECT c.id, name, created_date, completed_date, status, template FROM campaigns c, users u WHERE c.uid=u.id AND u.id=?" , uid )
2014-02-05 16:57:53 +00:00
return cs , err
}
2014-02-11 23:32:29 +00:00
// GetCampaign returns the campaign, if it exists, specified by the given id and user_id.
2014-02-10 01:34:47 +00:00
func GetCampaign ( id int64 , uid int64 ) ( models . Campaign , error ) {
2014-02-06 16:49:53 +00:00
c := models . Campaign { }
2014-02-10 01:34:47 +00:00
err := Conn . SelectOne ( & c , "SELECT c.id, name, created_date, completed_date, status, template FROM campaigns c, users u WHERE c.uid=u.id AND c.id =? AND u.id=?" , id , uid )
2014-02-06 16:49:53 +00:00
return c , err
}
2014-02-05 16:57:53 +00:00
2014-02-11 23:32:29 +00:00
// GetGroups returns the groups owned by the given user.
2014-02-10 01:34:47 +00:00
func GetGroups ( uid int64 ) ( [ ] models . Group , error ) {
2014-02-06 19:30:05 +00:00
gs := [ ] models . Group { }
2014-02-10 01:34:47 +00:00
_ , err := Conn . Select ( & gs , "SELECT g.id, g.name, g.modified_date FROM groups g, user_groups ug, users u WHERE ug.uid=u.id AND ug.gid=g.id AND u.id=?" , uid )
2014-02-06 19:30:05 +00:00
if err != nil {
2014-02-07 01:16:29 +00:00
Logger . Println ( err )
2014-02-06 19:30:05 +00:00
return gs , err
}
for i , _ := range gs {
_ , err := Conn . Select ( & gs [ i ] . Targets , "SELECT t.id, t.email FROM targets t, group_targets gt WHERE gt.gid=? AND gt.tid=t.id" , gs [ i ] . Id )
if err != nil {
2014-02-07 01:16:29 +00:00
Logger . Println ( err )
2014-02-06 19:30:05 +00:00
}
}
return gs , nil
}
2014-02-07 01:16:29 +00:00
2014-02-11 23:32:29 +00:00
// GetGroup returns the group, if it exists, specified by the given id and user_id.
2014-02-10 01:34:47 +00:00
func GetGroup ( id int64 , uid int64 ) ( models . Group , error ) {
g := models . Group { }
err := Conn . SelectOne ( & g , "SELECT g.id, g.name, g.modified_date FROM groups g, user_groups ug, users u WHERE ug.uid=u.id AND ug.gid=g.id AND g.id=? AND u.id=?" , id , uid )
if err != nil {
Logger . Println ( err )
return g , err
}
_ , err = Conn . Select ( & g . Targets , "SELECT t.id, t.email FROM targets t, group_targets gt WHERE gt.gid=? AND gt.tid=t.id" , g . Id )
if err != nil {
Logger . Println ( err )
}
return g , nil
}
2014-02-11 23:32:29 +00:00
// PostGroup creates a new group in the database.
2014-02-07 01:16:29 +00:00
func PostGroup ( g * models . Group , uid int64 ) error {
// Insert into the DB
err = Conn . Insert ( g )
if err != nil {
Logger . Println ( err )
return err
}
// Now, let's add the user->user_groups->group mapping
_ , err = Conn . Exec ( "INSERT OR IGNORE INTO user_groups VALUES (?,?)" , uid , g . Id )
if err != nil {
Logger . Printf ( "Error adding many-many mapping for group %s\n" , g . Name )
}
for _ , t := range g . Targets {
2014-02-11 23:32:29 +00:00
insertTargetIntoGroup ( t , g . Id )
}
return nil
}
// PutGroup updates the given group if found in the database.
func PutGroup ( g * models . Group , uid int64 ) error {
// Update all the foreign keys, and many to many relationships
// We will only delete the group->targets entries. We keep the actual targets
// since they are needed by the Results table
// Get all the targets currently in the database for the group
ts := [ ] models . Target { }
_ , err = Conn . Select ( & ts , "SELECT t.id, t.email FROM targets t, group_targets gt WHERE gt.gid=? AND gt.tid=t.id" , g . Id )
if err != nil {
Logger . Printf ( "Error getting targets from group ID: %d" , g . Id )
return err
}
// Enumerate through, removing any entries that are no longer in the group
// For every target in the database
tExists := false
for _ , t := range ts {
tExists = false
// Is the target still in the group?
for _ , nt := range g . Targets {
if t . Email == nt . Email {
tExists = true
break
}
2014-02-07 01:16:29 +00:00
}
2014-02-11 23:32:29 +00:00
// If the target does not exist in the group any longer, we delete it
if ! tExists {
_ , err = Conn . Exec ( "DELETE FROM group_targets WHERE gid=? AND tid=?" , g . Id , t . Id )
if err != nil {
Logger . Printf ( "Error deleting email %s\n" , t . Email )
}
2014-02-07 01:16:29 +00:00
}
2014-02-11 23:32:29 +00:00
}
// Insert any entries that are not in the database
// For every target in the new group
for _ , nt := range g . Targets {
// Check and see if the target already exists in the db
tExists = false
for _ , t := range ts {
if t . Email == nt . Email {
tExists = true
break
}
2014-02-07 01:16:29 +00:00
}
2014-02-11 23:32:29 +00:00
// If the target is not in the db, we add it
if ! tExists {
insertTargetIntoGroup ( nt , g . Id )
2014-02-07 01:16:29 +00:00
}
}
2014-02-11 23:32:29 +00:00
return nil
}
func insertTargetIntoGroup ( t models . Target , gid int64 ) error {
if _ , err = mail . ParseAddress ( t . Email ) ; err != nil {
Logger . Printf ( "Invalid email %s\n" , t . Email )
return err
}
trans , err := Conn . Begin ( )
2014-02-07 01:16:29 +00:00
if err != nil {
Logger . Println ( err )
return err
}
2014-02-11 23:32:29 +00:00
_ , err = trans . Exec ( "INSERT OR IGNORE INTO targets VALUES (null, ?)" , t . Email )
if err != nil {
Logger . Printf ( "Error adding email: %s\n" , t . Email )
return err
}
// Bug: res.LastInsertId() does not work for this, so we need to select it manually (how frustrating.)
t . Id , err = trans . SelectInt ( "SELECT id FROM targets WHERE email=?" , t . Email )
if err != nil {
Logger . Printf ( "Error getting id for email: %s\n" , t . Email )
return err
}
_ , err = trans . Exec ( "INSERT OR IGNORE INTO group_targets VALUES (?,?)" , gid , t . Id )
if err != nil {
Logger . Printf ( "Error adding many-many mapping for %s\n" , t . Email )
return err
}
err = trans . Commit ( )
if err != nil {
Logger . Printf ( "Error committing db changes\n" )
return err
}
2014-02-07 01:16:29 +00:00
return nil
}
2014-02-10 07:15:36 +00:00
func DeleteGroup ( id int64 , uid int64 ) error {
2014-02-07 01:16:29 +00:00
return nil
}