1
0

http.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. package repo
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "gopkg.in/macaron.v1"
  15. log "unknwon.dev/clog/v2"
  16. "gogs.io/gogs/internal/auth"
  17. "gogs.io/gogs/internal/conf"
  18. "gogs.io/gogs/internal/context"
  19. "gogs.io/gogs/internal/database"
  20. "gogs.io/gogs/internal/lazyregexp"
  21. "gogs.io/gogs/internal/pathutil"
  22. "gogs.io/gogs/internal/tool"
  23. )
  24. type HTTPContext struct {
  25. *macaron.Context
  26. OwnerName string
  27. OwnerSalt string
  28. RepoID int64
  29. RepoName string
  30. AuthUser *database.User
  31. }
  32. // askCredentials responses HTTP header and status which informs client to provide credentials.
  33. func askCredentials(c *macaron.Context, status int, text string) {
  34. c.Header().Set("WWW-Authenticate", "Basic realm=\".\"")
  35. c.Error(status, text)
  36. }
  37. func HTTPContexter(store Store) macaron.Handler {
  38. return func(c *macaron.Context) {
  39. if len(conf.HTTP.AccessControlAllowOrigin) > 0 {
  40. // Set CORS headers for browser-based git clients
  41. c.Header().Set("Access-Control-Allow-Origin", conf.HTTP.AccessControlAllowOrigin)
  42. c.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, User-Agent")
  43. // Handle preflight OPTIONS request
  44. if c.Req.Method == "OPTIONS" {
  45. c.Status(http.StatusOK)
  46. return
  47. }
  48. }
  49. ownerName := c.Params(":username")
  50. repoName := strings.TrimSuffix(c.Params(":reponame"), ".git")
  51. repoName = strings.TrimSuffix(repoName, ".wiki")
  52. isPull := c.Query("service") == "git-upload-pack" ||
  53. strings.HasSuffix(c.Req.URL.Path, "git-upload-pack") ||
  54. c.Req.Method == "GET"
  55. owner, err := store.GetUserByUsername(c.Req.Context(), ownerName)
  56. if err != nil {
  57. if database.IsErrUserNotExist(err) {
  58. c.Status(http.StatusNotFound)
  59. } else {
  60. c.Status(http.StatusInternalServerError)
  61. log.Error("Failed to get user [name: %s]: %v", ownerName, err)
  62. }
  63. return
  64. }
  65. repo, err := store.GetRepositoryByName(c.Req.Context(), owner.ID, repoName)
  66. if err != nil {
  67. if database.IsErrRepoNotExist(err) {
  68. c.Status(http.StatusNotFound)
  69. } else {
  70. c.Status(http.StatusInternalServerError)
  71. log.Error("Failed to get repository [owner_id: %d, name: %s]: %v", owner.ID, repoName, err)
  72. }
  73. return
  74. }
  75. // Authentication is not required for pulling from public repositories.
  76. if isPull && !repo.IsPrivate && !conf.Auth.RequireSigninView {
  77. c.Map(&HTTPContext{
  78. Context: c,
  79. })
  80. return
  81. }
  82. // In case user requested a wrong URL and not intended to access Git objects.
  83. action := c.Params("*")
  84. if !strings.Contains(action, "git-") &&
  85. !strings.Contains(action, "info/") &&
  86. !strings.Contains(action, "HEAD") &&
  87. !strings.Contains(action, "objects/") {
  88. c.Error(http.StatusBadRequest, fmt.Sprintf("Unrecognized action %q", action))
  89. return
  90. }
  91. // Handle HTTP Basic Authentication
  92. authHead := c.Req.Header.Get("Authorization")
  93. if authHead == "" {
  94. askCredentials(c, http.StatusUnauthorized, "")
  95. return
  96. }
  97. auths := strings.Fields(authHead)
  98. if len(auths) != 2 || auths[0] != "Basic" {
  99. askCredentials(c, http.StatusUnauthorized, "")
  100. return
  101. }
  102. authUsername, authPassword, err := tool.BasicAuthDecode(auths[1])
  103. if err != nil {
  104. askCredentials(c, http.StatusUnauthorized, "")
  105. return
  106. }
  107. authUser, err := store.AuthenticateUser(c.Req.Context(), authUsername, authPassword, -1)
  108. if err != nil && !auth.IsErrBadCredentials(err) {
  109. c.Status(http.StatusInternalServerError)
  110. log.Error("Failed to authenticate user [name: %s]: %v", authUsername, err)
  111. return
  112. }
  113. // If username and password combination failed, try again using either username
  114. // or password as the token.
  115. if authUser == nil {
  116. authUser, err = context.AuthenticateByToken(store, c.Req.Context(), authUsername)
  117. if err != nil && !database.IsErrAccessTokenNotExist(err) {
  118. c.Status(http.StatusInternalServerError)
  119. log.Error("Failed to authenticate by access token via username: %v", err)
  120. return
  121. } else if database.IsErrAccessTokenNotExist(err) {
  122. // Try again using the password field as the token.
  123. authUser, err = context.AuthenticateByToken(store, c.Req.Context(), authPassword)
  124. if err != nil {
  125. if database.IsErrAccessTokenNotExist(err) {
  126. askCredentials(c, http.StatusUnauthorized, "")
  127. } else {
  128. c.Status(http.StatusInternalServerError)
  129. log.Error("Failed to authenticate by access token via password: %v", err)
  130. }
  131. return
  132. }
  133. }
  134. } else if store.IsTwoFactorEnabled(c.Req.Context(), authUser.ID) {
  135. askCredentials(c, http.StatusUnauthorized, `User with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password
  136. Please create and use personal access token on user settings page`)
  137. return
  138. }
  139. log.Trace("[Git] Authenticated user: %s", authUser.Name)
  140. mode := database.AccessModeWrite
  141. if isPull {
  142. mode = database.AccessModeRead
  143. }
  144. if !database.Handle.Permissions().Authorize(c.Req.Context(), authUser.ID, repo.ID, mode,
  145. database.AccessModeOptions{
  146. OwnerID: repo.OwnerID,
  147. Private: repo.IsPrivate,
  148. },
  149. ) {
  150. askCredentials(c, http.StatusForbidden, "User permission denied")
  151. return
  152. }
  153. if !isPull && repo.IsMirror {
  154. c.Error(http.StatusForbidden, "Mirror repository is read-only")
  155. return
  156. }
  157. c.Map(&HTTPContext{
  158. Context: c,
  159. OwnerName: ownerName,
  160. OwnerSalt: owner.Salt,
  161. RepoID: repo.ID,
  162. RepoName: repoName,
  163. AuthUser: authUser,
  164. })
  165. }
  166. }
  167. type serviceHandler struct {
  168. w http.ResponseWriter
  169. r *http.Request
  170. dir string
  171. file string
  172. authUser *database.User
  173. ownerName string
  174. ownerSalt string
  175. repoID int64
  176. repoName string
  177. }
  178. func (h *serviceHandler) setHeaderNoCache() {
  179. h.w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  180. h.w.Header().Set("Pragma", "no-cache")
  181. h.w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  182. }
  183. func (h *serviceHandler) setHeaderCacheForever() {
  184. now := time.Now().Unix()
  185. expires := now + 31536000
  186. h.w.Header().Set("Date", fmt.Sprintf("%d", now))
  187. h.w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  188. h.w.Header().Set("Cache-Control", "public, max-age=31536000")
  189. }
  190. func (h *serviceHandler) sendFile(contentType string) {
  191. reqFile := path.Join(h.dir, h.file)
  192. fi, err := os.Stat(reqFile)
  193. if os.IsNotExist(err) {
  194. h.w.WriteHeader(http.StatusNotFound)
  195. return
  196. }
  197. h.w.Header().Set("Content-Type", contentType)
  198. h.w.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size()))
  199. h.w.Header().Set("Last-Modified", fi.ModTime().Format(http.TimeFormat))
  200. http.ServeFile(h.w, h.r, reqFile)
  201. }
  202. func serviceRPC(h serviceHandler, service string) {
  203. defer h.r.Body.Close()
  204. if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) {
  205. h.w.WriteHeader(http.StatusUnauthorized)
  206. return
  207. }
  208. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service))
  209. var (
  210. reqBody = h.r.Body
  211. err error
  212. )
  213. // Handle GZIP
  214. if h.r.Header.Get("Content-Encoding") == "gzip" {
  215. reqBody, err = gzip.NewReader(reqBody)
  216. if err != nil {
  217. log.Error("HTTP.Get: fail to create gzip reader: %v", err)
  218. h.w.WriteHeader(http.StatusInternalServerError)
  219. return
  220. }
  221. }
  222. var stderr bytes.Buffer
  223. cmd := exec.Command("git", service, "--stateless-rpc", h.dir)
  224. if service == "receive-pack" {
  225. cmd.Env = append(os.Environ(), database.ComposeHookEnvs(database.ComposeHookEnvsOptions{
  226. AuthUser: h.authUser,
  227. OwnerName: h.ownerName,
  228. OwnerSalt: h.ownerSalt,
  229. RepoID: h.repoID,
  230. RepoName: h.repoName,
  231. RepoPath: h.dir,
  232. })...)
  233. }
  234. cmd.Dir = h.dir
  235. cmd.Stdout = h.w
  236. cmd.Stderr = &stderr
  237. cmd.Stdin = reqBody
  238. if err = cmd.Run(); err != nil {
  239. log.Error("HTTP.serviceRPC: fail to serve RPC '%s': %v - %s", service, err, stderr.String())
  240. h.w.WriteHeader(http.StatusInternalServerError)
  241. return
  242. }
  243. }
  244. func serviceUploadPack(h serviceHandler) {
  245. serviceRPC(h, "upload-pack")
  246. }
  247. func serviceReceivePack(h serviceHandler) {
  248. serviceRPC(h, "receive-pack")
  249. }
  250. func getServiceType(r *http.Request) string {
  251. serviceType := r.FormValue("service")
  252. if !strings.HasPrefix(serviceType, "git-") {
  253. return ""
  254. }
  255. return strings.TrimPrefix(serviceType, "git-")
  256. }
  257. // FIXME: use process module
  258. func gitCommand(dir string, args ...string) []byte {
  259. cmd := exec.Command("git", args...)
  260. cmd.Dir = dir
  261. out, err := cmd.Output()
  262. if err != nil {
  263. log.Error("Git: %v - %s", err, out)
  264. }
  265. return out
  266. }
  267. func updateServerInfo(dir string) []byte {
  268. return gitCommand(dir, "update-server-info")
  269. }
  270. func packetWrite(str string) []byte {
  271. s := strconv.FormatInt(int64(len(str)+4), 16)
  272. if len(s)%4 != 0 {
  273. s = strings.Repeat("0", 4-len(s)%4) + s
  274. }
  275. return []byte(s + str)
  276. }
  277. func getInfoRefs(h serviceHandler) {
  278. h.setHeaderNoCache()
  279. service := getServiceType(h.r)
  280. if service != "upload-pack" && service != "receive-pack" {
  281. updateServerInfo(h.dir)
  282. h.sendFile("text/plain; charset=utf-8")
  283. return
  284. }
  285. refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".")
  286. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
  287. h.w.WriteHeader(http.StatusOK)
  288. _, _ = h.w.Write(packetWrite("# service=git-" + service + "\n"))
  289. _, _ = h.w.Write([]byte("0000"))
  290. _, _ = h.w.Write(refs)
  291. }
  292. func getTextFile(h serviceHandler) {
  293. h.setHeaderNoCache()
  294. h.sendFile("text/plain")
  295. }
  296. func getInfoPacks(h serviceHandler) {
  297. h.setHeaderCacheForever()
  298. h.sendFile("text/plain; charset=utf-8")
  299. }
  300. func getLooseObject(h serviceHandler) {
  301. h.setHeaderCacheForever()
  302. h.sendFile("application/x-git-loose-object")
  303. }
  304. func getPackFile(h serviceHandler) {
  305. h.setHeaderCacheForever()
  306. h.sendFile("application/x-git-packed-objects")
  307. }
  308. func getIdxFile(h serviceHandler) {
  309. h.setHeaderCacheForever()
  310. h.sendFile("application/x-git-packed-objects-toc")
  311. }
  312. var routes = []struct {
  313. re *lazyregexp.Regexp
  314. method string
  315. handler func(serviceHandler)
  316. }{
  317. {lazyregexp.New("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  318. {lazyregexp.New("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  319. {lazyregexp.New("(.*?)/info/refs$"), "GET", getInfoRefs},
  320. {lazyregexp.New("(.*?)/HEAD$"), "GET", getTextFile},
  321. {lazyregexp.New("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  322. {lazyregexp.New("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  323. {lazyregexp.New("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  324. {lazyregexp.New("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  325. {lazyregexp.New("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  326. {lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  327. {lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
  328. }
  329. func getGitRepoPath(dir string) (string, error) {
  330. if !strings.HasSuffix(dir, ".git") {
  331. dir += ".git"
  332. }
  333. filename := filepath.Join(conf.Repository.Root, dir)
  334. if _, err := os.Stat(filename); os.IsNotExist(err) {
  335. return "", err
  336. }
  337. return filename, nil
  338. }
  339. func HTTP(c *HTTPContext) {
  340. for _, route := range routes {
  341. reqPath := strings.ToLower(c.Req.URL.Path)
  342. m := route.re.FindStringSubmatch(reqPath)
  343. if m == nil {
  344. continue
  345. }
  346. // We perform check here because route matched in cmd/web.go is wider than needed,
  347. // but we only want to output this message only if user is really trying to access
  348. // Git HTTP endpoints.
  349. if conf.Repository.DisableHTTPGit {
  350. c.Error(http.StatusForbidden, "Interacting with repositories by HTTP protocol is disabled")
  351. return
  352. }
  353. if route.method != c.Req.Method {
  354. c.Error(http.StatusNotFound)
  355. return
  356. }
  357. // 🚨 SECURITY: Prevent path traversal.
  358. cleaned := pathutil.Clean(m[1])
  359. if m[1] != "/"+cleaned {
  360. c.Error(http.StatusBadRequest, "Request path contains suspicious characters")
  361. return
  362. }
  363. file := strings.TrimPrefix(reqPath, cleaned)
  364. dir, err := getGitRepoPath(cleaned)
  365. if err != nil {
  366. log.Warn("HTTP.getGitRepoPath: %v", err)
  367. c.Error(http.StatusNotFound)
  368. return
  369. }
  370. route.handler(serviceHandler{
  371. w: c.Resp,
  372. r: c.Req.Request,
  373. dir: dir,
  374. file: file,
  375. authUser: c.AuthUser,
  376. ownerName: c.OwnerName,
  377. ownerSalt: c.OwnerSalt,
  378. repoID: c.RepoID,
  379. repoName: c.RepoName,
  380. })
  381. return
  382. }
  383. c.Error(http.StatusNotFound)
  384. }