main.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. iaas := &ovirt{}
  128. echoHandler.GET("/ovirtListVMs", iaas.listVM, isLoggedIn)
  129. echoHandler.POST("/ovirtAddVM", iaas.addvm, isLoggedIn)
  130. echoHandler.POST("/ovirtStartVM", iaas.StartVM, isLoggedIn)
  131. echoHandler.POST("/ovirtStopVM", iaas.StopVM, isLoggedIn)
  132. echoHandler.POST("/ovirtRebootVM", iaas.RebootVM, isLoggedIn)
  133. echoHandler.POST("/ovirtPowerOffVM", iaas.PowerOffVM, isLoggedIn)
  134. echoHandler.POST("/ovirtResetVM", iaas.ResetVM, isLoggedIn)
  135. echoHandler.POST("/ovirtAddNIC", iaas.AddNIC, isLoggedIn)
  136. echoHandler.POST("/ovirtAddDisk", iaas.AddDisk, isLoggedIn)
  137. echoHandler.POST("/ovirtEditVM", iaas.EditVM, isLoggedIn)
  138. echoHandler.POST("/ovirtResetPassword", iaas.ResetPassword, isLoggedIn)
  139. echoHandler.POST("/vmDetails", iaas.vmDetails, isLoggedIn)
  140. echoHandler.POST("/ovirtPayment", iaas.ovirtPayment, isLoggedIn )
  141. echoHandler.Logger.Fatal(echoHandler.Start(os.Args[1] + ":" + os.Args[2]))
  142. }
  143. func encrypt(key []byte, text string) string {
  144. // key := []byte(keyText)
  145. //fmt.Println("Encrypt by: ", key)
  146. plaintext := []byte(text)
  147. block, err := aes.NewCipher(key)
  148. if err != nil {
  149. //panic(err)
  150. fmt.Sprintf("encrypt got error")
  151. return ""
  152. }
  153. // The IV needs to be unique, but not secure. Therefore it's common to
  154. // include it at the beginning of the ciphertext.
  155. ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  156. iv := ciphertext[:aes.BlockSize]
  157. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  158. fmt.Sprintf("encrypt got error")
  159. return ""
  160. }
  161. stream := cipher.NewCFBEncrypter(block, iv)
  162. stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
  163. // convert to base64
  164. return base64.URLEncoding.EncodeToString(ciphertext)
  165. }
  166. func decrypt(key []byte, cryptoText string) string {
  167. ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)
  168. //fmt.Println("Decrypt by: ", key)
  169. block, err := aes.NewCipher(key)
  170. if err != nil {
  171. fmt.Sprintf("decrypt got error")
  172. return ""
  173. //panic(err)
  174. }
  175. // The IV needs to be unique, but not secure. Therefore it's common to
  176. // include it at the beginning of the ciphertext.
  177. if len(ciphertext) < aes.BlockSize {
  178. fmt.Sprintf("ciphertext too short")
  179. return ""
  180. //panic("ciphertext too short")
  181. }
  182. iv := ciphertext[:aes.BlockSize]
  183. ciphertext = ciphertext[aes.BlockSize:]
  184. stream := cipher.NewCFBDecrypter(block, iv)
  185. // XORKeyStream can work in-place if the two arguments are the same.
  186. stream.XORKeyStream(ciphertext, ciphertext)
  187. return fmt.Sprintf("%s", ciphertext)
  188. }
  189. func task() {
  190. type Task struct {
  191. UUID string `json:"uuid"`
  192. TaskAPICall string `json:"taskapicall"`
  193. Ruuid string `json:"ruuid"`
  194. CronExpression string `json:"cronexpression"`
  195. Type string `json:"type"` //0: createVM , 1: VMInitialization
  196. }
  197. //fmt.Println("Task is being performed.")
  198. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  199. 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")
  200. for results.Next() {
  201. var res Task
  202. err = results.Scan(&res.UUID, &res.TaskAPICall, &res.CronExpression, &res.Ruuid, &res.Type)
  203. if err != nil {
  204. panic(err.Error()) // proper error handling instead of panic in your app
  205. }
  206. taskType := 0
  207. taskType, _ = strconv.Atoi(res.Type)
  208. if taskType == 0 {
  209. createVM(res.Ruuid, res.TaskAPICall, res.UUID)
  210. } else if taskType == 1 {
  211. VMInitialization(res.Ruuid, res.TaskAPICall, res.UUID)
  212. } else if taskType == 2 {
  213. } else {
  214. }
  215. //fmt.Println("query ruuid: ", res.Ruuid)
  216. }
  217. if err != nil {
  218. panic(err.Error()) // proper error handling instead of panic in your app
  219. }
  220. if err != nil {
  221. panic(err.Error())
  222. }
  223. defer db.Close()
  224. //iaas := &ovirt{}
  225. //fmt.Println("down",iaas.vmStatus("4f0e58ff-fb75-4a3d-9262-bd3714db52a6"))
  226. //fmt.Println("up",iaas.vmStatus("6b84a5dc-1c83-43e0-9ea6-dd86413bccc0"))
  227. }
  228. func addTask(uuid string, taskAPICall string, cronExpression string, origin string, description string, related_uuid string, _type string, active string) string {
  229. {
  230. /*
  231. types:
  232. 0: VM Create
  233. 1: VM Initialize
  234. 2: VM Start
  235. 3: VM Stop
  236. */
  237. //fmt.Println("Add Task:", uuid)
  238. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  239. if err != nil {
  240. }
  241. defer db.Close()
  242. //INSERT INTO `zicloud`.`scheduler`(`uuid`, `taskAPICall`, active`, `cron_expression`, `origin`, NOW()) VALUES ('xx', 'xx', 'xx', 0, 'xx', 'xx');
  243. insert, err := db.Query("INSERT INTO scheduler VALUES (" +
  244. " '" + uuid + "'," +
  245. "'" + taskAPICall + "'," +
  246. "'" + active + "'," +
  247. "'" + cronExpression + "'," +
  248. "'" + origin + "'," +
  249. "'" + description + "'," +
  250. "'" + related_uuid + "'," +
  251. _type + "," +
  252. "NOW()" +
  253. " )")
  254. if err != nil {
  255. }
  256. defer insert.Close()
  257. }
  258. return "OK"
  259. }
  260. func toggleTask(uuid string, active int) {
  261. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  262. if err != nil {
  263. }
  264. update, err := db.Query("update scheduler set active='" + fmt.Sprintf("%s", active) + "' where uuid='" + uuid + "'")
  265. defer db.Close()
  266. if err != nil {
  267. }
  268. defer update.Close()
  269. }
  270. func runAPICall(apiCall addVMTask) []byte {
  271. url := apiCall.URL
  272. method := apiCall.Method
  273. __json := apiCall.JSON
  274. //fmt.Println("runAPICALL: ", __json)
  275. client := &http.Client{}
  276. payload := strings.NewReader(__json)
  277. req, err := http.NewRequest(method, url, payload)
  278. _headers := apiCall.Headers
  279. for _, v := range _headers {
  280. req.Header.Add(v.Name, v.Value)
  281. }
  282. if err != nil {
  283. fmt.Println(err)
  284. }
  285. res, err := client.Do(req)
  286. defer res.Body.Close()
  287. body, _ := ioutil.ReadAll(res.Body)
  288. return body
  289. }
  290. func VMPowerMng(relatedUuid string, apiCall string, uuid string) {
  291. startVM := addVMTask{}
  292. _err := json.Unmarshal([]byte(apiCall), &startVM)
  293. if _err != nil {
  294. fmt.Println("Error in VMPowerMng: ", _err.Error())
  295. }
  296. _sha256 := sha256.Sum256([]byte(relatedUuid))
  297. var hashChannel_ = make(chan []byte, 1)
  298. hashChannel_ <- _sha256[:]
  299. //fmt.Println(" startVM.JSON: ", startVM.JSON)
  300. startVM.JSON = decrypt(<-hashChannel_, startVM.JSON)
  301. //fmt.Println("decrypted json: ",startVM.JSON)
  302. runAPICall(startVM)
  303. toggleTask(uuid, 0)
  304. }