main.go 9.8 KB

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