main.go 11 KB

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