main.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "crypto/sha256"
  7. "database/sql"
  8. "encoding/base64"
  9. "encoding/json"
  10. "fmt"
  11. "github.com/google/uuid"
  12. "github.com/jasonlvhit/gocron"
  13. "github.com/labstack/echo"
  14. "github.com/labstack/echo/middleware"
  15. "io"
  16. "log"
  17. "log/syslog"
  18. "net/http"
  19. "net/smtp"
  20. "os"
  21. "strconv"
  22. "strings"
  23. "time"
  24. )
  25. var _appversion string = "0.1"
  26. var _appname string = "ZiCloud-API"
  27. var URL string = "https://ipa-cl.zi-tel.com"
  28. var OvirtURL string = "https://ovirt-cl.zi-tel.com"
  29. var RealIP string
  30. var secretKey = []byte("P*%!5+u!$y+cgM+P8bybzgnXpsd2Lv2z") // 32 bytes
  31. type _response struct {
  32. Message string `json:"message"`
  33. Origin string `json:"origin"`
  34. Code int `json:"code"`
  35. }
  36. func uuidgen(resource string) (string, int) {
  37. id := uuid.New()
  38. if len(resource) < 3 {
  39. return "resource name should be at least 3 characters!", 1001
  40. }
  41. {
  42. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  43. if err != nil {
  44. return "Error in DB Layer", 1001
  45. }
  46. defer db.Close()
  47. insert, err := db.Query("INSERT INTO uuid VALUES ( '" + fmt.Sprintf("%s", id) + "'," +
  48. "'" + resource + "'," +
  49. "NOW()" +
  50. " )")
  51. if err != nil {
  52. return "Error in DB Layer", 1001
  53. }
  54. defer insert.Close()
  55. }
  56. return fmt.Sprintf("%s", id), 1000
  57. }
  58. func audit(txt string) {
  59. syslogger, err := syslog.New(syslog.LOG_INFO, _appname)
  60. if err != nil {
  61. log.Fatalln(err)
  62. }
  63. log.SetOutput(syslogger)
  64. log.Println(txt)
  65. }
  66. func basicAuth(username, password string) string {
  67. auth := username + "@IPA:" + password
  68. return base64.StdEncoding.EncodeToString([]byte(auth))
  69. }
  70. func sendMail(str string, subject string, recipient string) {
  71. auth := smtp.PlainAuth("", "zicloud@zi-tel.com", "5Sd?^AQx@r2OGRvS?i|DO0", "mail.zi-tel.com")
  72. to := []string{recipient}
  73. buff := make([]byte, 8)
  74. rand.Read(buff)
  75. random_str := base64.StdEncoding.EncodeToString(buff)
  76. msg := []byte("To:" + recipient + "\r\n" +
  77. "Date: " + time.Now().Format(time.RFC1123) + "\r\n" +
  78. "Message-Id: <" + random_str + "@ZiCloud.com>" + "\r\n" +
  79. "subject: " + subject + "\r\n" +
  80. "From: ZiCloud <" + "zicloud@zi-tel.com" + ">\r\n" +
  81. str)
  82. err := smtp.SendMail("mail.zi-tel.com:25", auth, "zicloud@zi-tel.com", to, msg)
  83. if err != nil {
  84. log.Fatal(err)
  85. }
  86. }
  87. func extractIP(next echo.HandlerFunc) echo.HandlerFunc {
  88. return func(c echo.Context) error {
  89. RealIP = c.RealIP()
  90. audit("Recieved request from: " + RealIP)
  91. return next(c)
  92. }
  93. }
  94. func main() {
  95. if len(os.Args) != 3 {
  96. fmt.Println("Wrong Usage:\n\t ./CMD IP Port")
  97. audit("Application in the wrong way")
  98. os.Exit(1)
  99. }
  100. s := gocron.NewScheduler()
  101. s.Every(1).Seconds().Do(task)
  102. go s.Start()
  103. echoHandler := echo.New()
  104. echoHandler.Use(extractIP)
  105. echoHandler.Use(middleware.CORSWithConfig(middleware.CORSConfig{
  106. AllowOrigins: []string{"*", "*"},
  107. AllowMethods: []string{http.MethodGet, http.MethodPost},
  108. }))
  109. audit("Application " + _appname + " (" + _appversion + ") Started by " + os.Getenv("USER"))
  110. echoHandler.GET("/", func(c echo.Context) error {
  111. return c.String(http.StatusOK, "Hello, World!")
  112. })
  113. h := &handler{}
  114. echoHandler.POST("/login", h.login)
  115. echoHandler.GET("/uuidgen", h.uuidgen)
  116. //echoHandler.GET("/admin", h.uuidgen, isLoggedIn, isAdmin)
  117. echoHandler.POST("/addUser", h.addUser, isLoggedIn, isAdmin)
  118. echoHandler.POST("/disableUser", h.disableUser, isLoggedIn, isAdmin)
  119. echoHandler.POST("/resetUser", h.resetUser)
  120. echoHandler.GET("/verifyUser", h.verifyUser)
  121. echoHandler.POST("/dnsrecordadd", h.dnsrecordadd, isLoggedIn, isAdmin)
  122. echoHandler.POST("/forgetpassword", h.forgetpassword, isLoggedIn, isAdmin)
  123. echoHandler.POST("/token", h.token, isLoggedIn)
  124. echoHandler.POST("/ListServices", h.ListServices, isLoggedIn)
  125. iaas := &ovirt{}
  126. echoHandler.GET("/ovirtListVMs", iaas.listVM, isLoggedIn)
  127. echoHandler.POST("/ovirtAddVM", iaas.addvm, isLoggedIn)
  128. echoHandler.POST("/ovirtStartVM", iaas.StartVM, isLoggedIn)
  129. echoHandler.POST("/ovirtStopVM", iaas.StopVM, isLoggedIn)
  130. echoHandler.POST("/ovirtRebootVM", iaas.RebootVM, isLoggedIn)
  131. echoHandler.POST("/ovirtPowerOffVM", iaas.PowerOffVM, isLoggedIn)
  132. echoHandler.POST("/ovirtResetVM", iaas.ResetVM, isLoggedIn)
  133. echoHandler.POST("/ovirtAddNIC", iaas.AddNIC, isLoggedIn)
  134. echoHandler.POST("/ovirtAddDisk", iaas.AddDisk, isLoggedIn)
  135. echoHandler.POST("/ovirtEditVM", iaas.EditVM, isLoggedIn)
  136. echoHandler.POST("/ovirtResetPassword", iaas.ResetPassword, isLoggedIn)
  137. echoHandler.POST("/vmDetails", iaas.vmDetails, isLoggedIn)
  138. echoHandler.Logger.Fatal(echoHandler.Start(os.Args[1] + ":" + os.Args[2]))
  139. }
  140. func encrypt(key []byte, text string) string {
  141. // key := []byte(keyText)
  142. plaintext := []byte(text)
  143. block, err := aes.NewCipher(key)
  144. if err != nil {
  145. //panic(err)
  146. fmt.Sprintf("encrypt got error")
  147. return ""
  148. }
  149. // The IV needs to be unique, but not secure. Therefore it's common to
  150. // include it at the beginning of the ciphertext.
  151. ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  152. iv := ciphertext[:aes.BlockSize]
  153. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  154. fmt.Sprintf("encrypt got error")
  155. return ""
  156. }
  157. stream := cipher.NewCFBEncrypter(block, iv)
  158. stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
  159. // convert to base64
  160. return base64.URLEncoding.EncodeToString(ciphertext)
  161. }
  162. func decrypt(key []byte, cryptoText string) string {
  163. ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)
  164. block, err := aes.NewCipher(key)
  165. if err != nil {
  166. fmt.Sprintf("decrypt got error")
  167. return ""
  168. //panic(err)
  169. }
  170. // The IV needs to be unique, but not secure. Therefore it's common to
  171. // include it at the beginning of the ciphertext.
  172. if len(ciphertext) < aes.BlockSize {
  173. fmt.Sprintf("ciphertext too short")
  174. return ""
  175. //panic("ciphertext too short")
  176. }
  177. iv := ciphertext[:aes.BlockSize]
  178. ciphertext = ciphertext[aes.BlockSize:]
  179. stream := cipher.NewCFBDecrypter(block, iv)
  180. // XORKeyStream can work in-place if the two arguments are the same.
  181. stream.XORKeyStream(ciphertext, ciphertext)
  182. return fmt.Sprintf("%s", ciphertext)
  183. }
  184. func task() {
  185. type Task struct {
  186. UUID string `json:"uuid"`
  187. TaskAPICall string `json:"taskapicall"`
  188. Ruuid string `json:"ruuid"`
  189. CronExpression string `json:"cronexpression"`
  190. Type string `json:"type"`
  191. }
  192. //fmt.Println("Task is being performed.")
  193. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  194. results, err := db.Query("SELECT uuid as UUID ,task_apiCall as TaskAPICall , cron_expression as CronExpression , related_uuid as Ruuid, type FROM scheduler where active=1")
  195. for results.Next() {
  196. var res Task
  197. err = results.Scan(&res.UUID, &res.TaskAPICall, &res.CronExpression, &res.Ruuid, &res.Type)
  198. if err != nil {
  199. panic(err.Error()) // proper error handling instead of panic in your app
  200. }
  201. i := 0
  202. i, _ = strconv.Atoi(res.Type)
  203. if i == 1 {
  204. VMInitialization(res.Ruuid, res.TaskAPICall, res.UUID)
  205. } else if i == 2 {
  206. } else
  207. {
  208. }
  209. //fmt.Println("query ruuid: ", res.Ruuid)
  210. }
  211. if err != nil {
  212. panic(err.Error()) // proper error handling instead of panic in your app
  213. }
  214. if err != nil {
  215. panic(err.Error())
  216. }
  217. defer db.Close()
  218. //iaas := &ovirt{}
  219. //fmt.Println("down",iaas.vmStatus("4f0e58ff-fb75-4a3d-9262-bd3714db52a6"))
  220. //fmt.Println("up",iaas.vmStatus("6b84a5dc-1c83-43e0-9ea6-dd86413bccc0"))
  221. }
  222. func VMInitialization(relatedUuid string, apiCall string, uuid string) {
  223. iaas := &ovirt{}
  224. status := iaas.vmStatus(relatedUuid)
  225. //fmt.Println("VM :", relatedUuid, " is now: ", status)
  226. if status == "down" {
  227. //fmt.Println("APICall: ", apiCall)
  228. startVM := addVMTask{}
  229. //b, _ := json.Marshal(apiCall)
  230. _err := json.Unmarshal([]byte(apiCall), &startVM)
  231. if _err != nil {
  232. fmt.Println("Error in VMInitialization: ", _err.Error())
  233. }
  234. //fmt.Println("calling initialization for VM :", relatedUuid)
  235. _sha256 := sha256.Sum256([]byte(relatedUuid))
  236. var hashChannel_ = make(chan []byte, 1)
  237. hashChannel_ <- _sha256[:]
  238. //fmt.Println(" startVM.JSON: ", startVM.JSON)
  239. startVM.JSON = decrypt(<-hashChannel_, startVM.JSON)
  240. //fmt.Println("decrypted json: ",startVM.JSON)
  241. runAPICall(startVM)
  242. toggleTask(uuid, 0)
  243. }
  244. }
  245. func addTask(uuid string, taskAPICall string, cronExpression string, origin string, description string, related_uuid string, _type string, active string) string {
  246. {
  247. /*
  248. types:
  249. 1: VM Inisialize
  250. 2: VM Start
  251. 3: VM Stop
  252. */
  253. //fmt.Println("Add Task:", taskAPICall)
  254. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  255. if err != nil {
  256. }
  257. defer db.Close()
  258. //INSERT INTO `zicloud`.`scheduler`(`uuid`, `taskAPICall`, active`, `cron_expression`, `origin`, NOW()) VALUES ('xx', 'xx', 'xx', 0, 'xx', 'xx');
  259. insert, err := db.Query("INSERT INTO scheduler VALUES (" +
  260. " '" + uuid + "'," +
  261. "'" + taskAPICall + "'," +
  262. "'" + active + "'," +
  263. "'" + cronExpression + "'," +
  264. "'" + origin + "'," +
  265. "'" + description + "'," +
  266. "'" + related_uuid + "'," +
  267. _type + "," +
  268. "NOW()" +
  269. " )")
  270. if err != nil {
  271. }
  272. defer insert.Close()
  273. }
  274. return "OK"
  275. }
  276. func toggleTask(uuid string, active int) {
  277. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  278. if err != nil {
  279. }
  280. update, err := db.Query("update scheduler set active='" + fmt.Sprintf("%s", active) + "' where uuid='" + uuid + "'")
  281. defer db.Close()
  282. if err != nil {
  283. }
  284. defer update.Close()
  285. }
  286. func runAPICall(apiCall addVMTask) {
  287. url := apiCall.URL
  288. method := apiCall.Method
  289. __json := apiCall.JSON
  290. client := &http.Client{
  291. }
  292. payload := strings.NewReader(__json)
  293. req, err := http.NewRequest(method, url, payload)
  294. _headers := apiCall.Headers
  295. for _, v := range _headers {
  296. req.Header.Add(v.Name, v.Value)
  297. }
  298. if err != nil {
  299. fmt.Println(err)
  300. }
  301. res, err := client.Do(req)
  302. defer res.Body.Close()
  303. }
  304. func VMPowerMng(relatedUuid string, apiCall string, uuid string) {
  305. startVM := addVMTask{}
  306. _err := json.Unmarshal([]byte(apiCall), &startVM)
  307. if _err != nil {
  308. fmt.Println("Error in VMPowerMng: ", _err.Error())
  309. }
  310. _sha256 := sha256.Sum256([]byte(relatedUuid))
  311. var hashChannel_ = make(chan []byte, 1)
  312. hashChannel_ <- _sha256[:]
  313. //fmt.Println(" startVM.JSON: ", startVM.JSON)
  314. startVM.JSON = decrypt(<-hashChannel_, startVM.JSON)
  315. //fmt.Println("decrypted json: ",startVM.JSON)
  316. runAPICall(startVM)
  317. toggleTask(uuid, 0)
  318. }