123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305 |
- package main
- import (
- "bufio"
- "bytes"
- "crypto/tls"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "log"
- "net/http"
- "net/url"
- "os"
- "regexp"
- "strings"
- "github.com/dgrijalva/jwt-go"
- "github.com/labstack/echo"
- "golang.org/x/crypto/ssh"
- )
- type handler struct{}
- type userInfo struct {
- Result struct {
- Result struct {
- Sshpubkeyfp []string `json:"sshpubkeyfp"`
- HasKeytab bool `json:"has_keytab"`
- Ipasshpubkey []string `json:"ipasshpubkey"`
- Cn []string `json:"cn"`
- Krbcanonicalname []string `json:"krbcanonicalname"`
- Krbticketflags []string `json:"krbticketflags"`
- MemberofGroup []string `json:"memberof_group"`
- HasPassword bool `json:"has_password"`
- Homedirectory []string `json:"homedirectory"`
- Nsaccountlock bool `json:"nsaccountlock"`
- UID []string `json:"uid"`
- Title []string `json:"title"`
- Loginshell []string `json:"loginshell"`
- Uidnumber []string `json:"uidnumber"`
- Preserved bool `json:"preserved"`
- Krbextradata []struct {
- Base64 string `json:"__base64__"`
- } `json:"krbextradata"`
- Mail []string `json:"mail"`
- MemberofindirectHbacrule []string `json:"memberofindirect_hbacrule"`
- Dn string `json:"dn"`
- Displayname []string `json:"displayname"`
- Mepmanagedentry []string `json:"mepmanagedentry"`
- Ipauniqueid []string `json:"ipauniqueid"`
- Krbloginfailedcount []string `json:"krbloginfailedcount"`
- Krbpwdpolicyreference []string `json:"krbpwdpolicyreference"`
- Krbprincipalname []string `json:"krbprincipalname"`
- Givenname []string `json:"givenname"`
- Krblastadminunlock []struct {
- Datetime string `json:"__datetime__"`
- } `json:"krblastadminunlock"`
- Krbpasswordexpiration []struct {
- Datetime string `json:"__datetime__"`
- } `json:"krbpasswordexpiration"`
- Krblastfailedauth []struct {
- Datetime string `json:"__datetime__"`
- } `json:"krblastfailedauth"`
- Objectclass []string `json:"objectclass"`
- Gidnumber []string `json:"gidnumber"`
- Gecos []string `json:"gecos"`
- Sn []string `json:"sn"`
- MemberofSudorule []string `json:"memberof_sudorule"`
- Krblastpwdchange []struct {
- Datetime string `json:"__datetime__"`
- } `json:"krblastpwdchange"`
- Initials []string `json:"initials"`
- } `json:"result"`
- Value string `json:"value"`
- Summary interface{} `json:"summary"`
- } `json:"result"`
- Version string `json:"version"`
- Error interface{} `json:"error"`
- ID int `json:"id"`
- Principal string `json:"principal"`
- }
- // Most of the code is taken from the echo guide
- // https://echo.labstack.com/cookbook/jwt
- func (h *handler) login(c echo.Context) error {
- username := c.FormValue("username")
- password := c.FormValue("password")
- _url := "https://ipa.sf.faraborddi.dc/ipa/session/login_password"
- method := "POST"
- params := url.Values{}
- params.Add("user", username)
- params.Add("password", password)
- payload := strings.NewReader(params.Encode())
- tr := &http.Transport{
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
- }
- client := &http.Client{Transport: tr}
- req, err := http.NewRequest(method, _url, payload)
- audit("Recieved Login request from: " + RealIP)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Referer", "https://ipa.sf.faraborddi.dc/ipa")
- req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
- req.Header.Add("Accept", "text/plain")
- res, err := client.Do(req)
- cockie := res.Cookies()
- defer res.Body.Close()
- //fmt.Println(res.StatusCode)
- if res.StatusCode == 200 {
- user := getUserInfo(cockie, username)
- //fmt.Println(user.Result.Value)
- tokens, err := generateTokenPair(user)
- if err != nil {
- return err
- }
- return c.JSON(http.StatusOK, tokens)
- }
- return echo.ErrUnauthorized
- }
- func getUserInfo(cockie []*http.Cookie, username string) userInfo {
- url := "https://ipa.sf.faraborddi.dc/ipa/session/json"
- method := "POST"
- _json := fmt.Sprintf(`
- {
- "method": "user_show",
- "params": [
- [
- "%s"
- ],
- {
- "all": true,
- "version": "2.215"
- }
- ],
- "id": 0
- }
- `, username)
- payload := strings.NewReader(_json)
- tr := &http.Transport{
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
- }
- client := &http.Client{Transport: tr}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Referer", "https://ipa.sf.faraborddi.dc/ipa")
- req.Header.Add("Content-Type", "application/json")
- req.Header.Add("Accept", "text/plain")
- req.Header.Add("Cookie", cockie[0].Raw)
- res, err := client.Do(req)
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- user := userInfo{}
- json.Unmarshal(body, &user)
- //fmt.Println(user.Result.Value)
- //fmt.Println(user.Result.Result.MemberofGroup)
- return user
- }
- // This is the api to refresh tokens
- // Most of the code is taken from the jwt-go package's sample codes
- // https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac
- //func (h *handler) token(c echo.Context) error {
- // type tokenReqBody struct {
- // RefreshToken string `json:"refresh_token"`
- // }
- // tokenReq := tokenReqBody{}
- // c.Bind(&tokenReq)
- //
- // // Parse takes the token string and a function for looking up the key.
- // // The latter is especially useful if you use multiple keys for your application.
- // // The standard is to use 'kid' in the head of the token to identify
- // // which key to use, but the parsed token (head and claims) is provided
- // // to the callback, providing flexibility.
- // token, err := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
- // // Don't forget to validate the alg is what you expect:
- // if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
- // return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
- // }
- //
- // // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
- // return []byte("secret"), nil
- // })
- //
- // if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
- // // Get the user record from database or
- // // run through your business logic to verify if the user can log in
- // if int(claims["sub"].(float64)) == 1 {
- //
- // newTokenPair, err := generateTokenPair()
- // if err != nil {
- // return err
- // }
- //
- // return c.JSON(http.StatusOK, newTokenPair)
- // }
- //
- // return echo.ErrUnauthorized
- // }
- //
- // return err
- //}
- // Most of the code is taken from the echo guide
- // https://echo.labstack.com/cookbook/jwt
- func (h *handler) private(c echo.Context) error {
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- name := claims["name"].(string)
- return c.String(http.StatusOK, "Welcome "+name+"!")
- }
- func Connect(user, pass, host string, cmd string) bytes.Buffer {
- cipher := ssh.Config{
- Ciphers: []string{"aes128-cbc", "3des-cbc", "aes192-cbc", "aes256-cbc"},
- }
- config := &ssh.ClientConfig{
- User: user,
- Auth: []ssh.AuthMethod{
- ssh.Password(pass),
- },
- HostKeyCallback: ssh.InsecureIgnoreHostKey(),
- Config: cipher,
- }
- conn, err := ssh.Dial("tcp", host, config)
- // time.Sleep(1)
- if err != nil {
- log.Fatal("Failed to dial: ", err)
- }
- sess, err := conn.NewSession()
- if err != nil {
- log.Fatal("Failed to create session: ", err)
- }
- stdin, err := sess.StdinPipe()
- if err != nil {
- log.Fatal("Failed to create session: ", err)
- }
- var bout bytes.Buffer
- var berr bytes.Buffer
- sess.Stdout = &bout
- sess.Stderr = &berr
- sess.Shell()
- fmt.Fprintf(stdin, "%s\n", "terminal length 0")
- fmt.Fprintf(stdin, "%s\n", cmd)
- fmt.Fprintf(stdin, "\nexit\n")
- fmt.Fprintf(stdin, "exit\n")
- sess.Wait()
- sess.Close()
- // scanner := bufio.NewScanner(&bout)
- // for scanner.Scan() {
- // fmt.Println(scanner.Text())
- // }
- // fmt.Println(bout.String())
- return bout
- }
- func (h *handler) findMAC(c echo.Context) error {
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- name := claims["name"].(string)
- result1 := Connect("rancid", "JDACy6wK*yW%meQ", os.Args[1], os.Args[2])
- intDesc := os.Args[3]
- var IntString string
- scanner := bufio.NewScanner(&result1)
- var IntName string
- var IntMAC string
- // var IntName, IntStatus, IntVLAN, IntDuplex, IntSpeed, IntType string
- for scanner.Scan() {
- // fmt.Println("Text: " + scanner.Text())
- if strings.Contains(scanner.Text(), intDesc) {
- // fmt.Println("Text: " + scanner.Text())
- IntString = scanner.Text()
- IntName = IntStringParser(IntString)[0]
- break
- }
- }
- // fmt.Println(IntName)
- result1 = Connect("rancid", "JDACy6wK*yW%meQ", os.Args[1], "sh mac address-table int "+IntName)
- scanner = bufio.NewScanner(&result1)
- for scanner.Scan() {
- // fmt.Println("Text: " + scanner.Text())
- if strings.Contains(scanner.Text(), IntName) {
- if strings.Contains(scanner.Text(), "mac") {
- continue
- }
- // fmt.Println(scanner.Text())
- IntString = scanner.Text()
- IntMAC = IntStringParser(IntString)[2]
- // fmt.Println(IntMAC)
- // break
- }
- }
- fmt.Println(IntMAC)
- return c.String(http.StatusOK, "Welcome "+IntMAC+"!")
- }
- func IntStringParser(str string) []string {
- re := regexp.MustCompile(`\s{1,}`)
- return strings.Split(re.ReplaceAllString(str, ","), ",")
- }
|