main.go 9.8 KB

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