htbapi

package module
v0.0.0-...-87a7f31 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2021 License: MIT Imports: 18 Imported by: 0

README

go-htbapi

Documentation

Overview

Package htbapi provides a library to interact with the api/v4/ endpoint of hackthebox.com. It will let you do a lot of different things

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInterrupted       = errors.New("interrupted")
	ErrMaxLengthExceeded = fmt.Errorf("maximum byte limit (%v) exceeded", maxLength)
)
View Source
var (
	// EnumVPNEndpoints hold the possible vpn endpoints to fetch data
	EnumVPNEndpoints = []string{"lab", "starting_point", "endgames", "fortresses", "pro_labs", "release_arena"}
)

Functions

func GetPasswdMasked

func GetPasswdMasked() ([]byte, error)

GetPasswdMasked returns the password read from the terminal, echoing asterisks. The returned byte array does not include end-of-line characters.

func JWTExpired

func JWTExpired(accessToken string) (bool, error)

JWTExpired is a helper function. It will take the access_token and parse the payload part of it. It will judge expiration based upon the 'exp' field in the payload. It will compare it to time.Now().Unix()

Types

type API

type API struct {
	BaseURL      string
	Is2FAEnabled bool
	Password     string
	RefreshToken string
	Remember     bool
	Session      *http.Client
	Token        string
	TokenHas2FA  bool
	Username     string
}

API represents the connection details with hackthebox It will be provided with credentials and is the main interface to communicate with the api at /api/v4

func New

func New(u, p string, r bool) (*API, error)

New will return an instantiated pointer to API. BaseURL is set statically to "https://www.hackthebox.com/api/v4". If DEBUG=TRUE is present in env http.Proxy will be set to http://127.0.0.1:8080. Also the connection will then ignore self signed certificates.

func (*API) DoLogin

func (a *API) DoLogin() error

DoLogin actually does the login request. If Email and Password are not set, it will prompt for it. It sets the Session details within the API struct after successful login.

func (*API) DoOTPLogin

func (a *API) DoOTPLogin() error

DoOTPLogin will handle the 2FA OTP login. It will prompt for the login code.

func (*API) DoRefreshToken

func (a *API) DoRefreshToken() error

DoRefreshToken will handle the renewal of the access_token. If it is expired it will pull a new one using the refresh_token

func (*API) DoRequest

func (a *API) DoRequest(endpoint string, jsonData []byte, authorized bool, post bool) (io.ReadCloser, int, error)

DoRequest will send a request to the API endpoint. You provide the endpoint, jsonData or nil, if it will be authorized by using the Bearer Token and if it is supposed to be a POST request (otherwise it will be GET). It will return to you the io.ReadCloser of the responses body and the HTTP Status code.

func (*API) DumpSessionToCache

func (a *API) DumpSessionToCache(path string) error

DumpSessionToCache will write the access_token and the refresh_token to disk to be read by LoadSessionFromCache. It will take a path where the file will be written to.

func (*API) GetAllChallenges

func (a *API) GetAllChallenges(retired bool) ([]Challenge, error)

GetAllChallenges will return you all challenges either retired=true or retired=false (the active ones)

func (*API) GetAllMachines

func (a *API) GetAllMachines(retired bool) ([]Machine, error)

GetAllMachines will get you a list of machines either active ones when choosing retired=false or retired ones if choosing retired=true

func (*API) GetChallenge

func (a *API) GetChallenge(id int) (Challenge, error)

GetChallenge will return you a certain challenge by id

func (*API) GetCurrentVPNServer

func (a *API) GetCurrentVPNServer(search string) (VPNServer, error)

GetCurrentVPNServer will give you VPNServer information by giving it one of the possible endpoints (also see EnumVPNEndpoints)

func (*API) GetMachine

func (a *API) GetMachine(id int) (Machine, error)

GetMachine will get you a machine by id

func (*API) GetReleaseArenaMachine

func (a *API) GetReleaseArenaMachine() (Machine, error)

GetReleaseArenaMachine will get you the machine currently in release arena

func (*API) GetSpawnedMachineInstance

func (a *API) GetSpawnedMachineInstance(releaseArena bool) (MachineInstance, error)

GetSpawnedMachineInstance will return the Machine Instance of the spawned machine either in release arena or in the lab.

func (*API) LoadSessionFromCache

func (a *API) LoadSessionFromCache(path string) (bool, error)

LoadSessionFromCache will load a session cache file containing the access_token and the refresh_token. It takes a path where the file is stored.

func (*API) Login

func (a *API) Login() error

Login will handle the login to /login. It will also trigger 2FA login if needed. It is a wrapper function around DoLogin() and DoOTPLogin().

type AssignedServer

type AssignedServer struct {
	ID             int    `json:"id"`
	FriendlyName   string `json:"friendly_name"`
	CurrentClients int    `json:"current_clients"`
	Location       string `json:"location"`
}

AssignedServer has further information about a VPNServer

type BloodInfo

type BloodInfo struct {
	BloodDifference string `json:"blood_difference"`
	CreatedAt       string `json:"created_at"`
	User            Player `json:"user"`
}

BloodInfo will hold information about machines first blood

type Challenge

type Challenge struct {
	AuthUserSolve        bool            `json:"authUserSolve"`
	AuthUserSolveTime    string          `json:"authUserSolveTime"`
	AVGDifficulty        int             `json:"avg_difficulty"`
	CategoryName         string          `json:"category_name"`
	ChallengeCategoryID  int             `json:"challenge_category_id"`
	Creator2Avatar       string          `json:"creator2_avatar"`
	Creator2ID           int             `json:"creator2_id"`
	Creator2Name         string          `json:"creator2_name"`
	CreatorAvatar        string          `json:"creator_avatar"`
	CreatorID            int             `json:"creator_id"`
	CreatorName          string          `json:"creator_name"`
	Description          string          `json:"description"`
	Difficulty           string          `json:"difficulty"`
	DifficultyChart      DifficultyChart `json:"difficulty_chart"`
	DifficultyChartArray []int           `json:"difficulty_chart_arr"`
	DislikeByAuthUser    bool            `json:"dislikeByAuthUser"`
	Dislikes             int             `json:"dislikes"`
	Docker               bool            `json:"docker"`
	DockerIP             string          `json:"docker_ip"`
	DockerPort           int             `json:"docker_port"`
	Download             bool            `json:"download"`
	FirstBloodTime       string          `json:"first_blood_time"`
	FirstBloodUser       string          `json:"first_blood_user"`
	FirstBloodUserAvatar string          `json:"first_blood_user_avatar"`
	FirstBloodUserID     int             `json:"first_blood_user_id"`
	ID                   int             `json:"id"`
	IsActive             bool            `json:"isActive"`
	IsCompleted          bool            `json:"isCompleted"`
	IsRespected          bool            `json:"isRespected"`
	IsRespected2         bool            `json:"isRespected2"`
	IsTodo               bool            `json:"isTodo"`
	LikeByAuthUser       bool            `json:"likeByAuthUser"`
	Likes                int             `json:"likes"`
	Name                 string          `json:"name"`
	Points               string          `json:"points"`
	Recommended          int             `json:"recommended"`
	ReleaseDate          string          `json:"release_date"`
	Retired              int             `json:"retired"`
	SHA256               string          `json:"sha256"`
	Solves               int             `json:"solves"`
	StaticPoints         string          `json:"static_points"`
	URLName              string          `json:"url_name"`
}

Challenge represents information about a Challenge

type Connections

type Connections struct {
	Status bool                 `json:"status"`
	Data   map[string]VPNServer `json:"data"`
}

Connections represents the connection details of all vpn endpoints within the HTB VPN environment

type DifficultyChart

type DifficultyChart struct {
	CounterCake      int `json:"counterCake"`
	CounterVeryEasy  int `json:"counterVeryEasy"`
	CounterEasy      int `json:"counterEasy"`
	CounterTooEasy   int `json:"counterTooEasy"`
	CounterMedium    int `json:"counterMedium"`
	CounterBitHard   int `json:"counterBitHard"`
	CounterHard      int `json:"counterHard"`
	CounterTooHard   int `json:"counterTooHard"`
	CounterExHard    int `json:"counterExHard"`
	CounterBrainFuck int `json:"counterBrainFuck"`
}

DifficultyChart is the rating system

type FdReader

type FdReader interface {
	io.Reader
	Fd() uintptr
}

type GetChallengeRepsonse

type GetChallengeRepsonse struct {
	Challenge Challenge `json:"challenge"`
}

GetChallengeResponse is used to construct the response to /challenge/info/<id>

type GetChallengesResponse

type GetChallengesResponse struct {
	Challenges []Challenge `json:"challenges"`
}

GetChallengesResponse is used to construct the response to /challenge/list

type GetMachineRepsonse

type GetMachineRepsonse struct {
	Machine Machine `json:"info"`
}

GetMachineResponse will be used to construct the response to /machine/profile/<id> endpoint

type GetMachinesResponse

type GetMachinesResponse struct {
	Machines []Machine `json:"info"`
}

GetMachinesResponse will be used to construct the response to /machine/list endpoint

type JWTPayload

type JWTPayload struct {
	AUD string `json:"aud"`
	JTI string `json:"jti"`
	IAT int    `json:"iat"`
	NBF int    `json:"nbf"`
	EXP int64  `json:"exp"`
	SUB string `json:"sub"`
}

JWTPayload is used to construct the JWTToken data while parsed

type LoginBody

type LoginBody struct {
	Email    string `json:"email"`
	Password string `json:"password"`
	Remember bool   `json:"remember"`
}

LoginBody is used to construct the json payload for /login

type LoginResponse

type LoginResponse struct {
	Message LoginResponseMessage `json:"message"`
}

LoginResponse is used to construct the response for /login

type LoginResponseMessage

type LoginResponseMessage struct {
	AccessToken  string `json:"access_token"`
	Is2FAEnabled bool   `json:"is2FAEnabled"`
	RefreshToken string `json:"refresh_token"`
	TokenHas2FA  bool   `json:"tokenHas2FA"`
}

LoginResponseMessage holds the login response data for /login

type Machine

type Machine struct {
	Active                int             `json:"active"`
	AuthUserFirstRootTime string          `json:"authUserFirstRootTime"`
	AuthUserFirstUserTime string          `json:"authUserFirstUserTime"`
	AuthUserHasReviewed   bool            `json:"auth_user_has_reviewed"`
	AuthUserInRootOwns    bool            `json:"auth_user_in_root_owns"`
	AuthUserInUserOwns    bool            `json:"auth_user_in_user_owns"`
	Avatar                string          `json:"avatar"`
	AvatarThumbUrl        string          `json:"avatar_thumb_url"`
	Difficulty            int             `json:"difficulty"`
	DifficultyText        string          `json:"difficultyText"`
	EasyMonth             int             `json:"easy_month"`
	ExpiresAt             string          `json:"expires_at"`
	FeedbackForChart      DifficultyChart `json:"feedbackForChart"`
	FirstRootBloodTime    string          `json:"firstRootBloodTime"`
	FirstUserBloodTime    string          `json:"firstUserBloodTime"`
	Free                  bool            `json:"free"`
	ID                    int             `json:"id"`
	IP                    string          `json:"ip"`
	IsCompleted           bool            `json:"isCompleted"`
	IsSpawning            bool            `json:"isSpawning"`
	IsTodo                bool            `json:"isTodo"`
	LabServer             string          `json:"lab_server"`
	Lifespan              int             `json:"lifespan"`
	Maker                 Maker           `json:"maker"`
	Maker2                Maker           `json:"maker2"`
	Name                  string          `json:"name"`
	OS                    string          `json:"os"`
	PlayInfo              PlayInfo        `json:"playInfo"`
	Points                int             `json:"points"`
	Recommended           int             `json:"recommended"`
	Release               time.Time       `json:"release"`
	Retired               int             `json:"retired"`
	RootBlood             BloodInfo       `json:"rootBlood"`
	RootBloodAvatar       string          `json:"rootBloodAvatar"`
	RootOwnsCount         int             `json:"root_owns_count"`
	SpFlag                int             `json:"sp_flag"`
	Stars                 string          `json:"stars"`
	StaticPoints          int             `json:"static_points"`
	Type                  string          `json:"type"`
	UserBlood             BloodInfo       `json:"userBlood"`
	UserBloodAvatar       string          `json:"userBloodAvatar"`
	UserOwnsCount         int             `json:"user_owns_count"`
	Voted                 bool            `json:"voted"`
	Voting                bool            `json:"voting"`
}

Machine will represent the data of a machine either in lab or release arena

func (*Machine) SpawnMachine

func (m *Machine) SpawnMachine(a *API, releaseArena bool) (MachineInstance, error)

Spawn machine will spawn a machine and give you the machine instance. You can choose if you want to spawn a release arena machine or a lab machine.

type MachineInstance

type MachineInstance struct {
	IP      string
	Machine Machine
	Server  string
}

MachineInstance is a wrapper around machine and vpn server info

func (*MachineInstance) Stop

func (mi *MachineInstance) Stop(a *API, releaseArena bool) (bool, error)

Stop will stop the currently running machine instance

func (*MachineInstance) Submit

func (mi *MachineInstance) Submit(a *API, flag string, difficulty int, releaseArena bool) (bool, SubmissionResponse, error)

Submit will submit a flag to the currently running machine instance. We will have to provide diffuculty from 1 to 10 and the flag and we need to either choose releaseArena true or false accordingly

type Maker

type Maker struct {
	Avatar      string `json:"avatar"`
	ID          int    `json:"id"`
	IsRespected bool   `json:"isRespected"`
	Name        string `json:"name"`
}

Maker will hold data about a box creator

type OTPBody

type OTPBody struct {
	OneTimePassword string `json:"one_time_password"`
}

OTPBody is used to construct the json payload for /2fa/login

type OTPLoginResponse

type OTPLoginResponse struct {
	Message string `json:"message"`
}

OTPLoginResponse is used to construct the login response data for /2fa/login

type PlayInfo

type PlayInfo struct {
	ActivePlayerCount int    `json:"active_player_count"`
	ExpiresAt         string `json:"expires_at"`
	IsActive          bool   `json:"isActive"`
	IsSpawend         bool   `json:"isSpawned"`
	IsSpawning        bool   `json:"isSpawning"`
}

PlayInfo will represent data of an active machine

type Player

type Player struct {
	Avatar string `json:"avatar"`
	ID     int    `json:"id"`
	Name   string `json:"name"`
}

Player will hold data of a htb player

type SpawnMachineResponse

type SpawnMachineResponse struct {
	Message string `json:"message"`
	Success int    `json:"success"`
}

SpawnMachineResponse will be used to construct the response to /vm/spawn or /release_arena/spawn

type SpawnedMachineInfoResponse

type SpawnedMachineInfoResponse struct {
	Info Machine `json:"info"`
}

SpawnedMachineInfoResponse will be used to construct the response to /machine/active or /release_arena/active

type Submission

type Submission struct {
	Difficulty int    `json:"difficulty"`
	Flag       string `json:"flag"`
	ID         int    `json:"id"`
}

Submission will represent submission details for submitting flags to /machine/own

type SubmissionResponse

type SubmissionResponse struct {
	Message string `json:"message"`
	Status  int    `json:"status"`
	Success string `json:"success"`
}

SubmissionResponse will be used to construct the response to /machine/own

type VPNServer

type VPNServer struct {
	CanAccess                bool           `json:"can_access"`
	LocationTypeFriendlyName string         `json:"location_type_friendly"`
	AssignedServer           AssignedServer `json:"assigned_server"`
	Available                bool           `json:"available"`
	Machine                  Machine        `json:"machine"`
}

VPNServer represents a single vpn endpoint within the HTB VPN environment

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL