Dataset Viewer
Auto-converted to Parquet
cwe_id
stringclasses
158 values
cwe_description
stringclasses
158 values
language
stringclasses
21 values
vulnerable_code
stringlengths
54
508k
fixed_code
stringlengths
54
508k
file_pair_id
stringlengths
3
7
source
stringclasses
1 value
language_dir
stringclasses
29 values
CWE-1021
Improper Restriction of Rendered UI Layers or Frames - A web application is expected to place restrictions on whether it is allowed to be rendered within frames, iframes, objects, embed or applet elements.
go
package controllers import ( "compress/gzip" "context" "crypto/tls" "html/template" "net/http" "net/url" "time" "github.com/NYTimes/gziphandler" "github.com/gophish/gophish/auth" "github.com/gophish/gophish/config" ctx "github.com/gophish/gophish/context" "github.com/gophish/gophish/controllers/api" log "github.com/gophish/gophish/logger" mid "github.com/gophish/gophish/middleware" "github.com/gophish/gophish/middleware/ratelimit" "github.com/gophish/gophish/models" "github.com/gophish/gophish/util" "github.com/gophish/gophish/worker" "github.com/gorilla/csrf" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/gorilla/sessions" "github.com/jordan-wright/unindexed" ) // AdminServerOption is a functional option that is used to configure the // admin server type AdminServerOption func(*AdminServer) // AdminServer is an HTTP server that implements the administrative Gophish // handlers, including the dashboard and REST API. type AdminServer struct { server *http.Server worker worker.Worker config config.AdminServer limiter *ratelimit.PostLimiter } var defaultTLSConfig = &tls.Config{ PreferServerCipherSuites: true, CurvePreferences: []tls.CurveID{ tls.X25519, tls.CurveP256, }, MinVersion: tls.VersionTLS12, CipherSuites: []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, // Kept for backwards compatibility with some clients tls.TLS_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_RSA_WITH_AES_128_GCM_SHA256, }, } // WithWorker is an option that sets the background worker. func WithWorker(w worker.Worker) AdminServerOption { return func(as *AdminServer) { as.worker = w } } // NewAdminServer returns a new instance of the AdminServer with the // provided config and options applied. func NewAdminServer(config config.AdminServer, options ...AdminServerOption) *AdminServer { defaultWorker, _ := worker.New() defaultServer := &http.Server{ ReadTimeout: 10 * time.Second, Addr: config.ListenURL, } defaultLimiter := ratelimit.NewPostLimiter() as := &AdminServer{ worker: defaultWorker, server: defaultServer, limiter: defaultLimiter, config: config, } for _, opt := range options { opt(as) } as.registerRoutes() return as } // Start launches the admin server, listening on the configured address. func (as *AdminServer) Start() { if as.worker != nil { go as.worker.Start() } if as.config.UseTLS { // Only support TLS 1.2 and above - ref #1691, #1689 as.server.TLSConfig = defaultTLSConfig err := util.CheckAndCreateSSL(as.config.CertPath, as.config.KeyPath) if err != nil { log.Fatal(err) } log.Infof("Starting admin server at https://%s", as.config.ListenURL) log.Fatal(as.server.ListenAndServeTLS(as.config.CertPath, as.config.KeyPath)) } // If TLS isn't configured, just listen on HTTP log.Infof("Starting admin server at http://%s", as.config.ListenURL) log.Fatal(as.server.ListenAndServe()) } // Shutdown attempts to gracefully shutdown the server. func (as *AdminServer) Shutdown() error { ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() return as.server.Shutdown(ctx) } // SetupAdminRoutes creates the routes for handling requests to the web interface. // This function returns an http.Handler to be used in http.ListenAndServe(). func (as *AdminServer) registerRoutes() { router := mux.NewRouter() // Base Front-end routes router.HandleFunc("/", mid.Use(as.Base, mid.RequireLogin)) router.HandleFunc("/login", mid.Use(as.Login, as.limiter.Limit)) router.HandleFunc("/logout", mid.Use(as.Logout, mid.RequireLogin)) router.HandleFunc("/reset_password", mid.Use(as.ResetPassword, mid.RequireLogin)) router.HandleFunc("/campaigns", mid.Use(as.Campaigns, mid.RequireLogin)) router.HandleFunc("/campaigns/{id:[0-9]+}", mid.Use(as.CampaignID, mid.RequireLogin)) router.HandleFunc("/templates", mid.Use(as.Templates, mid.RequireLogin)) router.HandleFunc("/groups", mid.Use(as.Groups, mid.RequireLogin)) router.HandleFunc("/landing_pages", mid.Use(as.LandingPages, mid.RequireLogin)) router.HandleFunc("/sending_profiles", mid.Use(as.SendingProfiles, mid.RequireLogin)) router.HandleFunc("/settings", mid.Use(as.Settings, mid.RequireLogin)) router.HandleFunc("/users", mid.Use(as.UserManagement, mid.RequirePermission(models.PermissionModifySystem), mid.RequireLogin)) router.HandleFunc("/webhooks", mid.Use(as.Webhooks, mid.RequirePermission(models.PermissionModifySystem), mid.RequireLogin)) router.HandleFunc("/impersonate", mid.Use(as.Impersonate, mid.RequirePermission(models.PermissionModifySystem), mid.RequireLogin)) // Create the API routes api := api.NewServer( api.WithWorker(as.worker), api.WithLimiter(as.limiter), ) router.PathPrefix("/api/").Handler(api) // Setup static file serving router.PathPrefix("/").Handler(http.FileServer(unindexed.Dir("./static/"))) // Setup CSRF Protection csrfKey := []byte(as.config.CSRFKey) if len(csrfKey) == 0 { csrfKey = []byte(auth.GenerateSecureKey(auth.APIKeyLength)) } csrfHandler := csrf.Protect(csrfKey, csrf.FieldName("csrf_token"), csrf.Secure(as.config.UseTLS)) adminHandler := csrfHandler(router) adminHandler = mid.Use(adminHandler.ServeHTTP, mid.CSRFExceptions, mid.GetContext) // Setup GZIP compression gzipWrapper, _ := gziphandler.NewGzipLevelHandler(gzip.BestCompression) adminHandler = gzipWrapper(adminHandler) // Setup logging adminHandler = handlers.CombinedLoggingHandler(log.Writer(), adminHandler) as.server.Handler = adminHandler } type templateParams struct { Title string Flashes []interface{} User models.User Token string Version string ModifySystem bool } // newTemplateParams returns the default template parameters for a user and // the CSRF token. func newTemplateParams(r *http.Request) templateParams { user := ctx.Get(r, "user").(models.User) session := ctx.Get(r, "session").(*sessions.Session) modifySystem, _ := user.HasPermission(models.PermissionModifySystem) return templateParams{ Token: csrf.Token(r), User: user, ModifySystem: modifySystem, Version: config.Version, Flashes: session.Flashes(), } } // Base handles the default path and template execution func (as *AdminServer) Base(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Dashboard" getTemplate(w, "dashboard").ExecuteTemplate(w, "base", params) } // Campaigns handles the default path and template execution func (as *AdminServer) Campaigns(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Campaigns" getTemplate(w, "campaigns").ExecuteTemplate(w, "base", params) } // CampaignID handles the default path and template execution func (as *AdminServer) CampaignID(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Campaign Results" getTemplate(w, "campaign_results").ExecuteTemplate(w, "base", params) } // Templates handles the default path and template execution func (as *AdminServer) Templates(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Email Templates" getTemplate(w, "templates").ExecuteTemplate(w, "base", params) } // Groups handles the default path and template execution func (as *AdminServer) Groups(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Users & Groups" getTemplate(w, "groups").ExecuteTemplate(w, "base", params) } // LandingPages handles the default path and template execution func (as *AdminServer) LandingPages(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Landing Pages" getTemplate(w, "landing_pages").ExecuteTemplate(w, "base", params) } // SendingProfiles handles the default path and template execution func (as *AdminServer) SendingProfiles(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Sending Profiles" getTemplate(w, "sending_profiles").ExecuteTemplate(w, "base", params) } // Settings handles the changing of settings func (as *AdminServer) Settings(w http.ResponseWriter, r *http.Request) { switch { case r.Method == "GET": params := newTemplateParams(r) params.Title = "Settings" session := ctx.Get(r, "session").(*sessions.Session) session.Save(r, w) getTemplate(w, "settings").ExecuteTemplate(w, "base", params) case r.Method == "POST": u := ctx.Get(r, "user").(models.User) currentPw := r.FormValue("current_password") newPassword := r.FormValue("new_password") confirmPassword := r.FormValue("confirm_new_password") // Check the current password err := auth.ValidatePassword(currentPw, u.Hash) msg := models.Response{Success: true, Message: "Settings Updated Successfully"} if err != nil { msg.Message = err.Error() msg.Success = false api.JSONResponse(w, msg, http.StatusBadRequest) return } newHash, err := auth.ValidatePasswordChange(u.Hash, newPassword, confirmPassword) if err != nil { msg.Message = err.Error() msg.Success = false api.JSONResponse(w, msg, http.StatusBadRequest) return } u.Hash = string(newHash) if err = models.PutUser(&u); err != nil { msg.Message = err.Error() msg.Success = false api.JSONResponse(w, msg, http.StatusInternalServerError) return } api.JSONResponse(w, msg, http.StatusOK) } } // UserManagement is an admin-only handler that allows for the registration // and management of user accounts within Gophish. func (as *AdminServer) UserManagement(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "User Management" getTemplate(w, "users").ExecuteTemplate(w, "base", params) } func (as *AdminServer) nextOrIndex(w http.ResponseWriter, r *http.Request) { next := "/" url, err := url.Parse(r.FormValue("next")) if err == nil { path := url.Path if path != "" { next = path } } http.Redirect(w, r, next, 302) } func (as *AdminServer) handleInvalidLogin(w http.ResponseWriter, r *http.Request) { session := ctx.Get(r, "session").(*sessions.Session) Flash(w, r, "danger", "Invalid Username/Password") params := struct { User models.User Title string Flashes []interface{} Token string }{Title: "Login", Token: csrf.Token(r)} params.Flashes = session.Flashes() session.Save(r, w) templates := template.New("template") _, err := templates.ParseFiles("templates/login.html", "templates/flashes.html") if err != nil { log.Error(err) } // w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusUnauthorized) template.Must(templates, err).ExecuteTemplate(w, "base", params) } // Webhooks is an admin-only handler that handles webhooks func (as *AdminServer) Webhooks(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Webhooks" getTemplate(w, "webhooks").ExecuteTemplate(w, "base", params) } // Impersonate allows an admin to login to a user account without needing the password func (as *AdminServer) Impersonate(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { username := r.FormValue("username") u, err := models.GetUserByUsername(username) if err != nil { log.Error(err) http.Error(w, err.Error(), http.StatusNotFound) return } session := ctx.Get(r, "session").(*sessions.Session) session.Values["id"] = u.Id session.Save(r, w) } http.Redirect(w, r, "/", http.StatusFound) } // Login handles the authentication flow for a user. If credentials are valid, // a session is created func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) { params := struct { User models.User Title string Flashes []interface{} Token string }{Title: "Login", Token: csrf.Token(r)} session := ctx.Get(r, "session").(*sessions.Session) switch { case r.Method == "GET": params.Flashes = session.Flashes() session.Save(r, w) templates := template.New("template") _, err := templates.ParseFiles("templates/login.html", "templates/flashes.html") if err != nil { log.Error(err) } template.Must(templates, err).ExecuteTemplate(w, "base", params) case r.Method == "POST": // Find the user with the provided username username, password := r.FormValue("username"), r.FormValue("password") u, err := models.GetUserByUsername(username) if err != nil { log.Error(err) as.handleInvalidLogin(w, r) return } // Validate the user's password err = auth.ValidatePassword(password, u.Hash) if err != nil { log.Error(err) as.handleInvalidLogin(w, r) return } // If we've logged in, save the session and redirect to the dashboard session.Values["id"] = u.Id session.Save(r, w) as.nextOrIndex(w, r) } } // Logout destroys the current user session func (as *AdminServer) Logout(w http.ResponseWriter, r *http.Request) { session := ctx.Get(r, "session").(*sessions.Session) delete(session.Values, "id") Flash(w, r, "success", "You have successfully logged out") session.Save(r, w) http.Redirect(w, r, "/login", http.StatusFound) } // ResetPassword handles the password reset flow when a password change is // required either by the Gophish system or an administrator. // // This handler is meant to be used when a user is required to reset their // password, not just when they want to. // // This is an important distinction since in this handler we don't require // the user to re-enter their current password, as opposed to the flow // through the settings handler. // // To that end, if the user doesn't require a password change, we will // redirect them to the settings page. func (as *AdminServer) ResetPassword(w http.ResponseWriter, r *http.Request) { u := ctx.Get(r, "user").(models.User) session := ctx.Get(r, "session").(*sessions.Session) if !u.PasswordChangeRequired { Flash(w, r, "info", "Please reset your password through the settings page") session.Save(r, w) http.Redirect(w, r, "/settings", http.StatusTemporaryRedirect) return } params := newTemplateParams(r) params.Title = "Reset Password" switch { case r.Method == http.MethodGet: params.Flashes = session.Flashes() session.Save(r, w) getTemplate(w, "reset_password").ExecuteTemplate(w, "base", params) return case r.Method == http.MethodPost: newPassword := r.FormValue("password") confirmPassword := r.FormValue("confirm_password") newHash, err := auth.ValidatePasswordChange(u.Hash, newPassword, confirmPassword) if err != nil { Flash(w, r, "danger", err.Error()) params.Flashes = session.Flashes() session.Save(r, w) w.WriteHeader(http.StatusBadRequest) getTemplate(w, "reset_password").ExecuteTemplate(w, "base", params) return } u.PasswordChangeRequired = false u.Hash = newHash if err = models.PutUser(&u); err != nil { Flash(w, r, "danger", err.Error()) params.Flashes = session.Flashes() session.Save(r, w) w.WriteHeader(http.StatusInternalServerError) getTemplate(w, "reset_password").ExecuteTemplate(w, "base", params) return } // TODO: We probably want to flash a message here that the password was // changed successfully. The problem is that when the user resets their // password on first use, they will see two flashes on the dashboard- // one for their password reset, and one for the "no campaigns created". // // The solution to this is to revamp the empty page to be more useful, // like a wizard or something. as.nextOrIndex(w, r) } } // TODO: Make this execute the template, too func getTemplate(w http.ResponseWriter, tmpl string) *template.Template { templates := template.New("template") _, err := templates.ParseFiles("templates/base.html", "templates/nav.html", "templates/"+tmpl+".html", "templates/flashes.html") if err != nil { log.Error(err) } return template.Must(templates, err) } // Flash handles the rendering flash messages func Flash(w http.ResponseWriter, r *http.Request, t string, m string) { session := ctx.Get(r, "session").(*sessions.Session) session.AddFlash(models.Flash{ Type: t, Message: m, }) }
package controllers import ( "compress/gzip" "context" "crypto/tls" "html/template" "net/http" "net/url" "time" "github.com/NYTimes/gziphandler" "github.com/gophish/gophish/auth" "github.com/gophish/gophish/config" ctx "github.com/gophish/gophish/context" "github.com/gophish/gophish/controllers/api" log "github.com/gophish/gophish/logger" mid "github.com/gophish/gophish/middleware" "github.com/gophish/gophish/middleware/ratelimit" "github.com/gophish/gophish/models" "github.com/gophish/gophish/util" "github.com/gophish/gophish/worker" "github.com/gorilla/csrf" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/gorilla/sessions" "github.com/jordan-wright/unindexed" ) // AdminServerOption is a functional option that is used to configure the // admin server type AdminServerOption func(*AdminServer) // AdminServer is an HTTP server that implements the administrative Gophish // handlers, including the dashboard and REST API. type AdminServer struct { server *http.Server worker worker.Worker config config.AdminServer limiter *ratelimit.PostLimiter } var defaultTLSConfig = &tls.Config{ PreferServerCipherSuites: true, CurvePreferences: []tls.CurveID{ tls.X25519, tls.CurveP256, }, MinVersion: tls.VersionTLS12, CipherSuites: []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, // Kept for backwards compatibility with some clients tls.TLS_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_RSA_WITH_AES_128_GCM_SHA256, }, } // WithWorker is an option that sets the background worker. func WithWorker(w worker.Worker) AdminServerOption { return func(as *AdminServer) { as.worker = w } } // NewAdminServer returns a new instance of the AdminServer with the // provided config and options applied. func NewAdminServer(config config.AdminServer, options ...AdminServerOption) *AdminServer { defaultWorker, _ := worker.New() defaultServer := &http.Server{ ReadTimeout: 10 * time.Second, Addr: config.ListenURL, } defaultLimiter := ratelimit.NewPostLimiter() as := &AdminServer{ worker: defaultWorker, server: defaultServer, limiter: defaultLimiter, config: config, } for _, opt := range options { opt(as) } as.registerRoutes() return as } // Start launches the admin server, listening on the configured address. func (as *AdminServer) Start() { if as.worker != nil { go as.worker.Start() } if as.config.UseTLS { // Only support TLS 1.2 and above - ref #1691, #1689 as.server.TLSConfig = defaultTLSConfig err := util.CheckAndCreateSSL(as.config.CertPath, as.config.KeyPath) if err != nil { log.Fatal(err) } log.Infof("Starting admin server at https://%s", as.config.ListenURL) log.Fatal(as.server.ListenAndServeTLS(as.config.CertPath, as.config.KeyPath)) } // If TLS isn't configured, just listen on HTTP log.Infof("Starting admin server at http://%s", as.config.ListenURL) log.Fatal(as.server.ListenAndServe()) } // Shutdown attempts to gracefully shutdown the server. func (as *AdminServer) Shutdown() error { ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() return as.server.Shutdown(ctx) } // SetupAdminRoutes creates the routes for handling requests to the web interface. // This function returns an http.Handler to be used in http.ListenAndServe(). func (as *AdminServer) registerRoutes() { router := mux.NewRouter() // Base Front-end routes router.HandleFunc("/", mid.Use(as.Base, mid.RequireLogin)) router.HandleFunc("/login", mid.Use(as.Login, as.limiter.Limit)) router.HandleFunc("/logout", mid.Use(as.Logout, mid.RequireLogin)) router.HandleFunc("/reset_password", mid.Use(as.ResetPassword, mid.RequireLogin)) router.HandleFunc("/campaigns", mid.Use(as.Campaigns, mid.RequireLogin)) router.HandleFunc("/campaigns/{id:[0-9]+}", mid.Use(as.CampaignID, mid.RequireLogin)) router.HandleFunc("/templates", mid.Use(as.Templates, mid.RequireLogin)) router.HandleFunc("/groups", mid.Use(as.Groups, mid.RequireLogin)) router.HandleFunc("/landing_pages", mid.Use(as.LandingPages, mid.RequireLogin)) router.HandleFunc("/sending_profiles", mid.Use(as.SendingProfiles, mid.RequireLogin)) router.HandleFunc("/settings", mid.Use(as.Settings, mid.RequireLogin)) router.HandleFunc("/users", mid.Use(as.UserManagement, mid.RequirePermission(models.PermissionModifySystem), mid.RequireLogin)) router.HandleFunc("/webhooks", mid.Use(as.Webhooks, mid.RequirePermission(models.PermissionModifySystem), mid.RequireLogin)) router.HandleFunc("/impersonate", mid.Use(as.Impersonate, mid.RequirePermission(models.PermissionModifySystem), mid.RequireLogin)) // Create the API routes api := api.NewServer( api.WithWorker(as.worker), api.WithLimiter(as.limiter), ) router.PathPrefix("/api/").Handler(api) // Setup static file serving router.PathPrefix("/").Handler(http.FileServer(unindexed.Dir("./static/"))) // Setup CSRF Protection csrfKey := []byte(as.config.CSRFKey) if len(csrfKey) == 0 { csrfKey = []byte(auth.GenerateSecureKey(auth.APIKeyLength)) } csrfHandler := csrf.Protect(csrfKey, csrf.FieldName("csrf_token"), csrf.Secure(as.config.UseTLS)) adminHandler := csrfHandler(router) adminHandler = mid.Use(adminHandler.ServeHTTP, mid.CSRFExceptions, mid.GetContext, mid.ApplySecurityHeaders) // Setup GZIP compression gzipWrapper, _ := gziphandler.NewGzipLevelHandler(gzip.BestCompression) adminHandler = gzipWrapper(adminHandler) // Setup logging adminHandler = handlers.CombinedLoggingHandler(log.Writer(), adminHandler) as.server.Handler = adminHandler } type templateParams struct { Title string Flashes []interface{} User models.User Token string Version string ModifySystem bool } // newTemplateParams returns the default template parameters for a user and // the CSRF token. func newTemplateParams(r *http.Request) templateParams { user := ctx.Get(r, "user").(models.User) session := ctx.Get(r, "session").(*sessions.Session) modifySystem, _ := user.HasPermission(models.PermissionModifySystem) return templateParams{ Token: csrf.Token(r), User: user, ModifySystem: modifySystem, Version: config.Version, Flashes: session.Flashes(), } } // Base handles the default path and template execution func (as *AdminServer) Base(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Dashboard" getTemplate(w, "dashboard").ExecuteTemplate(w, "base", params) } // Campaigns handles the default path and template execution func (as *AdminServer) Campaigns(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Campaigns" getTemplate(w, "campaigns").ExecuteTemplate(w, "base", params) } // CampaignID handles the default path and template execution func (as *AdminServer) CampaignID(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Campaign Results" getTemplate(w, "campaign_results").ExecuteTemplate(w, "base", params) } // Templates handles the default path and template execution func (as *AdminServer) Templates(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Email Templates" getTemplate(w, "templates").ExecuteTemplate(w, "base", params) } // Groups handles the default path and template execution func (as *AdminServer) Groups(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Users & Groups" getTemplate(w, "groups").ExecuteTemplate(w, "base", params) } // LandingPages handles the default path and template execution func (as *AdminServer) LandingPages(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Landing Pages" getTemplate(w, "landing_pages").ExecuteTemplate(w, "base", params) } // SendingProfiles handles the default path and template execution func (as *AdminServer) SendingProfiles(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Sending Profiles" getTemplate(w, "sending_profiles").ExecuteTemplate(w, "base", params) } // Settings handles the changing of settings func (as *AdminServer) Settings(w http.ResponseWriter, r *http.Request) { switch { case r.Method == "GET": params := newTemplateParams(r) params.Title = "Settings" session := ctx.Get(r, "session").(*sessions.Session) session.Save(r, w) getTemplate(w, "settings").ExecuteTemplate(w, "base", params) case r.Method == "POST": u := ctx.Get(r, "user").(models.User) currentPw := r.FormValue("current_password") newPassword := r.FormValue("new_password") confirmPassword := r.FormValue("confirm_new_password") // Check the current password err := auth.ValidatePassword(currentPw, u.Hash) msg := models.Response{Success: true, Message: "Settings Updated Successfully"} if err != nil { msg.Message = err.Error() msg.Success = false api.JSONResponse(w, msg, http.StatusBadRequest) return } newHash, err := auth.ValidatePasswordChange(u.Hash, newPassword, confirmPassword) if err != nil { msg.Message = err.Error() msg.Success = false api.JSONResponse(w, msg, http.StatusBadRequest) return } u.Hash = string(newHash) if err = models.PutUser(&u); err != nil { msg.Message = err.Error() msg.Success = false api.JSONResponse(w, msg, http.StatusInternalServerError) return } api.JSONResponse(w, msg, http.StatusOK) } } // UserManagement is an admin-only handler that allows for the registration // and management of user accounts within Gophish. func (as *AdminServer) UserManagement(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "User Management" getTemplate(w, "users").ExecuteTemplate(w, "base", params) } func (as *AdminServer) nextOrIndex(w http.ResponseWriter, r *http.Request) { next := "/" url, err := url.Parse(r.FormValue("next")) if err == nil { path := url.Path if path != "" { next = path } } http.Redirect(w, r, next, 302) } func (as *AdminServer) handleInvalidLogin(w http.ResponseWriter, r *http.Request) { session := ctx.Get(r, "session").(*sessions.Session) Flash(w, r, "danger", "Invalid Username/Password") params := struct { User models.User Title string Flashes []interface{} Token string }{Title: "Login", Token: csrf.Token(r)} params.Flashes = session.Flashes() session.Save(r, w) templates := template.New("template") _, err := templates.ParseFiles("templates/login.html", "templates/flashes.html") if err != nil { log.Error(err) } // w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusUnauthorized) template.Must(templates, err).ExecuteTemplate(w, "base", params) } // Webhooks is an admin-only handler that handles webhooks func (as *AdminServer) Webhooks(w http.ResponseWriter, r *http.Request) { params := newTemplateParams(r) params.Title = "Webhooks" getTemplate(w, "webhooks").ExecuteTemplate(w, "base", params) } // Impersonate allows an admin to login to a user account without needing the password func (as *AdminServer) Impersonate(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { username := r.FormValue("username") u, err := models.GetUserByUsername(username) if err != nil { log.Error(err) http.Error(w, err.Error(), http.StatusNotFound) return } session := ctx.Get(r, "session").(*sessions.Session) session.Values["id"] = u.Id session.Save(r, w) } http.Redirect(w, r, "/", http.StatusFound) } // Login handles the authentication flow for a user. If credentials are valid, // a session is created func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) { params := struct { User models.User Title string Flashes []interface{} Token string }{Title: "Login", Token: csrf.Token(r)} session := ctx.Get(r, "session").(*sessions.Session) switch { case r.Method == "GET": params.Flashes = session.Flashes() session.Save(r, w) templates := template.New("template") _, err := templates.ParseFiles("templates/login.html", "templates/flashes.html") if err != nil { log.Error(err) } template.Must(templates, err).ExecuteTemplate(w, "base", params) case r.Method == "POST": // Find the user with the provided username username, password := r.FormValue("username"), r.FormValue("password") u, err := models.GetUserByUsername(username) if err != nil { log.Error(err) as.handleInvalidLogin(w, r) return } // Validate the user's password err = auth.ValidatePassword(password, u.Hash) if err != nil { log.Error(err) as.handleInvalidLogin(w, r) return } // If we've logged in, save the session and redirect to the dashboard session.Values["id"] = u.Id session.Save(r, w) as.nextOrIndex(w, r) } } // Logout destroys the current user session func (as *AdminServer) Logout(w http.ResponseWriter, r *http.Request) { session := ctx.Get(r, "session").(*sessions.Session) delete(session.Values, "id") Flash(w, r, "success", "You have successfully logged out") session.Save(r, w) http.Redirect(w, r, "/login", http.StatusFound) } // ResetPassword handles the password reset flow when a password change is // required either by the Gophish system or an administrator. // // This handler is meant to be used when a user is required to reset their // password, not just when they want to. // // This is an important distinction since in this handler we don't require // the user to re-enter their current password, as opposed to the flow // through the settings handler. // // To that end, if the user doesn't require a password change, we will // redirect them to the settings page. func (as *AdminServer) ResetPassword(w http.ResponseWriter, r *http.Request) { u := ctx.Get(r, "user").(models.User) session := ctx.Get(r, "session").(*sessions.Session) if !u.PasswordChangeRequired { Flash(w, r, "info", "Please reset your password through the settings page") session.Save(r, w) http.Redirect(w, r, "/settings", http.StatusTemporaryRedirect) return } params := newTemplateParams(r) params.Title = "Reset Password" switch { case r.Method == http.MethodGet: params.Flashes = session.Flashes() session.Save(r, w) getTemplate(w, "reset_password").ExecuteTemplate(w, "base", params) return case r.Method == http.MethodPost: newPassword := r.FormValue("password") confirmPassword := r.FormValue("confirm_password") newHash, err := auth.ValidatePasswordChange(u.Hash, newPassword, confirmPassword) if err != nil { Flash(w, r, "danger", err.Error()) params.Flashes = session.Flashes() session.Save(r, w) w.WriteHeader(http.StatusBadRequest) getTemplate(w, "reset_password").ExecuteTemplate(w, "base", params) return } u.PasswordChangeRequired = false u.Hash = newHash if err = models.PutUser(&u); err != nil { Flash(w, r, "danger", err.Error()) params.Flashes = session.Flashes() session.Save(r, w) w.WriteHeader(http.StatusInternalServerError) getTemplate(w, "reset_password").ExecuteTemplate(w, "base", params) return } // TODO: We probably want to flash a message here that the password was // changed successfully. The problem is that when the user resets their // password on first use, they will see two flashes on the dashboard- // one for their password reset, and one for the "no campaigns created". // // The solution to this is to revamp the empty page to be more useful, // like a wizard or something. as.nextOrIndex(w, r) } } // TODO: Make this execute the template, too func getTemplate(w http.ResponseWriter, tmpl string) *template.Template { templates := template.New("template") _, err := templates.ParseFiles("templates/base.html", "templates/nav.html", "templates/"+tmpl+".html", "templates/flashes.html") if err != nil { log.Error(err) } return template.Must(templates, err) } // Flash handles the rendering flash messages func Flash(w http.ResponseWriter, r *http.Request, t string, m string) { session := ctx.Get(r, "session").(*sessions.Session) session.AddFlash(models.Flash{ Type: t, Message: m, }) }
4282_0
crossvul
go
CWE-1021
Improper Restriction of Rendered UI Layers or Frames - A web application is expected to place restrictions on whether it is allowed to be rendered within frames, iframes, objects, embed or applet elements.
go
package middleware import ( "encoding/json" "fmt" "net/http" "strings" ctx "github.com/gophish/gophish/context" "github.com/gophish/gophish/models" "github.com/gorilla/csrf" ) // CSRFExemptPrefixes are a list of routes that are exempt from CSRF protection var CSRFExemptPrefixes = []string{ "/api", } // CSRFExceptions is a middleware that prevents CSRF checks on routes listed in // CSRFExemptPrefixes. func CSRFExceptions(handler http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { for _, prefix := range CSRFExemptPrefixes { if strings.HasPrefix(r.URL.Path, prefix) { r = csrf.UnsafeSkipCheck(r) break } } handler.ServeHTTP(w, r) } } // Use allows us to stack middleware to process the request // Example taken from https://github.com/gorilla/mux/pull/36#issuecomment-25849172 func Use(handler http.HandlerFunc, mid ...func(http.Handler) http.HandlerFunc) http.HandlerFunc { for _, m := range mid { handler = m(handler) } return handler } // GetContext wraps each request in a function which fills in the context for a given request. // This includes setting the User and Session keys and values as necessary for use in later functions. func GetContext(handler http.Handler) http.HandlerFunc { // Set the context here return func(w http.ResponseWriter, r *http.Request) { // Parse the request form err := r.ParseForm() if err != nil { http.Error(w, "Error parsing request", http.StatusInternalServerError) } // Set the context appropriately here. // Set the session session, _ := Store.Get(r, "gophish") // Put the session in the context so that we can // reuse the values in different handlers r = ctx.Set(r, "session", session) if id, ok := session.Values["id"]; ok { u, err := models.GetUser(id.(int64)) if err != nil { r = ctx.Set(r, "user", nil) } else { r = ctx.Set(r, "user", u) } } else { r = ctx.Set(r, "user", nil) } handler.ServeHTTP(w, r) // Remove context contents ctx.Clear(r) } } // RequireAPIKey ensures that a valid API key is set as either the api_key GET // parameter, or a Bearer token. func RequireAPIKey(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") if r.Method == "OPTIONS" { w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS") w.Header().Set("Access-Control-Max-Age", "1000") w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") return } r.ParseForm() ak := r.Form.Get("api_key") // If we can't get the API key, we'll also check for the // Authorization Bearer token if ak == "" { tokens, ok := r.Header["Authorization"] if ok && len(tokens) >= 1 { ak = tokens[0] ak = strings.TrimPrefix(ak, "Bearer ") } } if ak == "" { JSONError(w, http.StatusUnauthorized, "API Key not set") return } u, err := models.GetUserByAPIKey(ak) if err != nil { JSONError(w, http.StatusUnauthorized, "Invalid API Key") return } r = ctx.Set(r, "user", u) r = ctx.Set(r, "user_id", u.Id) r = ctx.Set(r, "api_key", ak) handler.ServeHTTP(w, r) }) } // RequireLogin checks to see if the user is currently logged in. // If not, the function returns a 302 redirect to the login page. func RequireLogin(handler http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if u := ctx.Get(r, "user"); u != nil { // If a password change is required for the user, then redirect them // to the login page currentUser := u.(models.User) if currentUser.PasswordChangeRequired && r.URL.Path != "/reset_password" { q := r.URL.Query() q.Set("next", r.URL.Path) http.Redirect(w, r, fmt.Sprintf("/reset_password?%s", q.Encode()), http.StatusTemporaryRedirect) return } handler.ServeHTTP(w, r) return } q := r.URL.Query() q.Set("next", r.URL.Path) http.Redirect(w, r, fmt.Sprintf("/login?%s", q.Encode()), http.StatusTemporaryRedirect) } } // EnforceViewOnly is a global middleware that limits the ability to edit // objects to accounts with the PermissionModifyObjects permission. func EnforceViewOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // If the request is for any non-GET HTTP method, e.g. POST, PUT, // or DELETE, we need to ensure the user has the appropriate // permission. if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodOptions { user := ctx.Get(r, "user").(models.User) access, err := user.HasPermission(models.PermissionModifyObjects) if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } if !access { http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } } next.ServeHTTP(w, r) }) } // RequirePermission checks to see if the user has the requested permission // before executing the handler. If the request is unauthorized, a JSONError // is returned. func RequirePermission(perm string) func(http.Handler) http.HandlerFunc { return func(next http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { user := ctx.Get(r, "user").(models.User) access, err := user.HasPermission(perm) if err != nil { JSONError(w, http.StatusInternalServerError, err.Error()) return } if !access { JSONError(w, http.StatusForbidden, http.StatusText(http.StatusForbidden)) return } next.ServeHTTP(w, r) } } } // JSONError returns an error in JSON format with the given // status code and message func JSONError(w http.ResponseWriter, c int, m string) { cj, _ := json.MarshalIndent(models.Response{Success: false, Message: m}, "", " ") w.Header().Set("Content-Type", "application/json") w.WriteHeader(c) fmt.Fprintf(w, "%s", cj) }
package middleware import ( "encoding/json" "fmt" "net/http" "strings" ctx "github.com/gophish/gophish/context" "github.com/gophish/gophish/models" "github.com/gorilla/csrf" ) // CSRFExemptPrefixes are a list of routes that are exempt from CSRF protection var CSRFExemptPrefixes = []string{ "/api", } // CSRFExceptions is a middleware that prevents CSRF checks on routes listed in // CSRFExemptPrefixes. func CSRFExceptions(handler http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { for _, prefix := range CSRFExemptPrefixes { if strings.HasPrefix(r.URL.Path, prefix) { r = csrf.UnsafeSkipCheck(r) break } } handler.ServeHTTP(w, r) } } // Use allows us to stack middleware to process the request // Example taken from https://github.com/gorilla/mux/pull/36#issuecomment-25849172 func Use(handler http.HandlerFunc, mid ...func(http.Handler) http.HandlerFunc) http.HandlerFunc { for _, m := range mid { handler = m(handler) } return handler } // GetContext wraps each request in a function which fills in the context for a given request. // This includes setting the User and Session keys and values as necessary for use in later functions. func GetContext(handler http.Handler) http.HandlerFunc { // Set the context here return func(w http.ResponseWriter, r *http.Request) { // Parse the request form err := r.ParseForm() if err != nil { http.Error(w, "Error parsing request", http.StatusInternalServerError) } // Set the context appropriately here. // Set the session session, _ := Store.Get(r, "gophish") // Put the session in the context so that we can // reuse the values in different handlers r = ctx.Set(r, "session", session) if id, ok := session.Values["id"]; ok { u, err := models.GetUser(id.(int64)) if err != nil { r = ctx.Set(r, "user", nil) } else { r = ctx.Set(r, "user", u) } } else { r = ctx.Set(r, "user", nil) } handler.ServeHTTP(w, r) // Remove context contents ctx.Clear(r) } } // RequireAPIKey ensures that a valid API key is set as either the api_key GET // parameter, or a Bearer token. func RequireAPIKey(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") if r.Method == "OPTIONS" { w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS") w.Header().Set("Access-Control-Max-Age", "1000") w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") return } r.ParseForm() ak := r.Form.Get("api_key") // If we can't get the API key, we'll also check for the // Authorization Bearer token if ak == "" { tokens, ok := r.Header["Authorization"] if ok && len(tokens) >= 1 { ak = tokens[0] ak = strings.TrimPrefix(ak, "Bearer ") } } if ak == "" { JSONError(w, http.StatusUnauthorized, "API Key not set") return } u, err := models.GetUserByAPIKey(ak) if err != nil { JSONError(w, http.StatusUnauthorized, "Invalid API Key") return } r = ctx.Set(r, "user", u) r = ctx.Set(r, "user_id", u.Id) r = ctx.Set(r, "api_key", ak) handler.ServeHTTP(w, r) }) } // RequireLogin checks to see if the user is currently logged in. // If not, the function returns a 302 redirect to the login page. func RequireLogin(handler http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if u := ctx.Get(r, "user"); u != nil { // If a password change is required for the user, then redirect them // to the login page currentUser := u.(models.User) if currentUser.PasswordChangeRequired && r.URL.Path != "/reset_password" { q := r.URL.Query() q.Set("next", r.URL.Path) http.Redirect(w, r, fmt.Sprintf("/reset_password?%s", q.Encode()), http.StatusTemporaryRedirect) return } handler.ServeHTTP(w, r) return } q := r.URL.Query() q.Set("next", r.URL.Path) http.Redirect(w, r, fmt.Sprintf("/login?%s", q.Encode()), http.StatusTemporaryRedirect) } } // EnforceViewOnly is a global middleware that limits the ability to edit // objects to accounts with the PermissionModifyObjects permission. func EnforceViewOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // If the request is for any non-GET HTTP method, e.g. POST, PUT, // or DELETE, we need to ensure the user has the appropriate // permission. if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodOptions { user := ctx.Get(r, "user").(models.User) access, err := user.HasPermission(models.PermissionModifyObjects) if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } if !access { http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } } next.ServeHTTP(w, r) }) } // RequirePermission checks to see if the user has the requested permission // before executing the handler. If the request is unauthorized, a JSONError // is returned. func RequirePermission(perm string) func(http.Handler) http.HandlerFunc { return func(next http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { user := ctx.Get(r, "user").(models.User) access, err := user.HasPermission(perm) if err != nil { JSONError(w, http.StatusInternalServerError, err.Error()) return } if !access { JSONError(w, http.StatusForbidden, http.StatusText(http.StatusForbidden)) return } next.ServeHTTP(w, r) } } } // ApplySecurityHeaders applies various security headers according to best- // practices. func ApplySecurityHeaders(next http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { csp := "frame-ancestors 'none';" w.Header().Set("Content-Security-Policy", csp) w.Header().Set("X-Frame-Options", "DENY") next.ServeHTTP(w, r) } } // JSONError returns an error in JSON format with the given // status code and message func JSONError(w http.ResponseWriter, c int, m string) { cj, _ := json.MarshalIndent(models.Response{Success: false, Message: m}, "", " ") w.Header().Set("Content-Type", "application/json") w.WriteHeader(c) fmt.Fprintf(w, "%s", cj) }
4282_1
crossvul
go
CWE-1021
Improper Restriction of Rendered UI Layers or Frames - A web application is expected to place restrictions on whether it is allowed to be rendered within frames, iframes, objects, embed or applet elements.
php
<?php /* * LimeSurvey * Copyright (C) 2007-2016 The LimeSurvey Project Team / Carsten Schmitz * All rights reserved. * License: GNU/GPL License v3 or later, see LICENSE.php * LimeSurvey is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ $config['versionnumber'] = '3.17.13'; $config['dbversionnumber'] = 359; $config['buildnumber'] = ''; $config['updatable'] = true; $config['assetsversionnumber'] = '30095'; return $config;
<?php /* * LimeSurvey * Copyright (C) 2007-2016 The LimeSurvey Project Team / Carsten Schmitz * All rights reserved. * License: GNU/GPL License v3 or later, see LICENSE.php * LimeSurvey is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ $config['versionnumber'] = '3.17.14'; $config['dbversionnumber'] = 359; $config['buildnumber'] = ''; $config['updatable'] = true; $config['assetsversionnumber'] = '30096'; return $config;
1075_0
crossvul
php
CWE-113
Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Request/Response Splitting') - HTTP agents or components may include a web server, load balancer, reverse proxy, web caching proxy, application firewall, web browser, etc.
javascript
'use strict'; const util = require('util'); const net = require('net'); const HTTPParser = process.binding('http_parser').HTTPParser; const assert = require('assert').ok; const common = require('_http_common'); const parsers = common.parsers; const freeParser = common.freeParser; const debug = common.debug; const CRLF = common.CRLF; const continueExpression = common.continueExpression; const chunkExpression = common.chunkExpression; const httpSocketSetup = common.httpSocketSetup; const OutgoingMessage = require('_http_outgoing').OutgoingMessage; const STATUS_CODES = exports.STATUS_CODES = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', // RFC 2518, obsoleted by RFC 4918 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', // RFC 4918 208: 'Already Reported', 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 307: 'Temporary Redirect', 308: 'Permanent Redirect', // RFC 7238 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Payload Too Large', 414: 'URI Too Long', 415: 'Unsupported Media Type', 416: 'Range Not Satisfiable', 417: 'Expectation Failed', 418: 'I\'m a teapot', // RFC 2324 421: 'Misdirected Request', 422: 'Unprocessable Entity', // RFC 4918 423: 'Locked', // RFC 4918 424: 'Failed Dependency', // RFC 4918 425: 'Unordered Collection', // RFC 4918 426: 'Upgrade Required', // RFC 2817 428: 'Precondition Required', // RFC 6585 429: 'Too Many Requests', // RFC 6585 431: 'Request Header Fields Too Large', // RFC 6585 451: 'Unavailable For Legal Reasons', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', // RFC 2295 507: 'Insufficient Storage', // RFC 4918 508: 'Loop Detected', 509: 'Bandwidth Limit Exceeded', 510: 'Not Extended', // RFC 2774 511: 'Network Authentication Required' // RFC 6585 }; const kOnExecute = HTTPParser.kOnExecute | 0; function ServerResponse(req) { OutgoingMessage.call(this); if (req.method === 'HEAD') this._hasBody = false; this.sendDate = true; if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) { this.useChunkedEncodingByDefault = chunkExpression.test(req.headers.te); this.shouldKeepAlive = false; } } util.inherits(ServerResponse, OutgoingMessage); ServerResponse.prototype._finish = function() { DTRACE_HTTP_SERVER_RESPONSE(this.connection); LTTNG_HTTP_SERVER_RESPONSE(this.connection); COUNTER_HTTP_SERVER_RESPONSE(); OutgoingMessage.prototype._finish.call(this); }; exports.ServerResponse = ServerResponse; ServerResponse.prototype.statusCode = 200; ServerResponse.prototype.statusMessage = undefined; function onServerResponseClose() { // EventEmitter.emit makes a copy of the 'close' listeners array before // calling the listeners. detachSocket() unregisters onServerResponseClose // but if detachSocket() is called, directly or indirectly, by a 'close' // listener, onServerResponseClose is still in that copy of the listeners // array. That is, in the example below, b still gets called even though // it's been removed by a: // // var EventEmitter = require('events'); // var obj = new EventEmitter(); // obj.on('event', a); // obj.on('event', b); // function a() { obj.removeListener('event', b) } // function b() { throw "BAM!" } // obj.emit('event'); // throws // // Ergo, we need to deal with stale 'close' events and handle the case // where the ServerResponse object has already been deconstructed. // Fortunately, that requires only a single if check. :-) if (this._httpMessage) this._httpMessage.emit('close'); } ServerResponse.prototype.assignSocket = function(socket) { assert(!socket._httpMessage); socket._httpMessage = this; socket.on('close', onServerResponseClose); this.socket = socket; this.connection = socket; this.emit('socket', socket); this._flush(); }; ServerResponse.prototype.detachSocket = function(socket) { assert(socket._httpMessage === this); socket.removeListener('close', onServerResponseClose); socket._httpMessage = null; this.socket = this.connection = null; }; ServerResponse.prototype.writeContinue = function(cb) { this._writeRaw('HTTP/1.1 100 Continue' + CRLF + CRLF, 'ascii', cb); this._sent100 = true; }; ServerResponse.prototype._implicitHeader = function() { this.writeHead(this.statusCode); }; ServerResponse.prototype.writeHead = function(statusCode, reason, obj) { var headers; if (typeof reason === 'string') { // writeHead(statusCode, reasonPhrase[, headers]) this.statusMessage = reason; } else { // writeHead(statusCode[, headers]) this.statusMessage = this.statusMessage || STATUS_CODES[statusCode] || 'unknown'; obj = reason; } this.statusCode = statusCode; if (this._headers) { // Slow-case: when progressive API and header fields are passed. if (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (k) this.setHeader(k, obj[k]); } } // only progressive api is used headers = this._renderHeaders(); } else { // only writeHead() called headers = obj; } statusCode |= 0; if (statusCode < 100 || statusCode > 999) throw new RangeError(`Invalid status code: ${statusCode}`); var statusLine = 'HTTP/1.1 ' + statusCode.toString() + ' ' + this.statusMessage + CRLF; if (statusCode === 204 || statusCode === 304 || (100 <= statusCode && statusCode <= 199)) { // RFC 2616, 10.2.5: // The 204 response MUST NOT include a message-body, and thus is always // terminated by the first empty line after the header fields. // RFC 2616, 10.3.5: // The 304 response MUST NOT contain a message-body, and thus is always // terminated by the first empty line after the header fields. // RFC 2616, 10.1 Informational 1xx: // This class of status code indicates a provisional response, // consisting only of the Status-Line and optional headers, and is // terminated by an empty line. this._hasBody = false; } // don't keep alive connections where the client expects 100 Continue // but we sent a final status; they may put extra bytes on the wire. if (this._expect_continue && !this._sent100) { this.shouldKeepAlive = false; } this._storeHeader(statusLine, headers); }; ServerResponse.prototype.writeHeader = function() { this.writeHead.apply(this, arguments); }; function Server(requestListener) { if (!(this instanceof Server)) return new Server(requestListener); net.Server.call(this, { allowHalfOpen: true }); if (requestListener) { this.addListener('request', requestListener); } /* eslint-disable max-len */ // Similar option to this. Too lazy to write my own docs. // http://www.squid-cache.org/Doc/config/half_closed_clients/ // http://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F /* eslint-enable max-len */ this.httpAllowHalfOpen = false; this.addListener('connection', connectionListener); this.timeout = 2 * 60 * 1000; this._pendingResponseData = 0; } util.inherits(Server, net.Server); Server.prototype.setTimeout = function(msecs, callback) { this.timeout = msecs; if (callback) this.on('timeout', callback); return this; }; exports.Server = Server; function connectionListener(socket) { var self = this; var outgoing = []; var incoming = []; var outgoingData = 0; function updateOutgoingData(delta) { // `outgoingData` is an approximate amount of bytes queued through all // inactive responses. If more data than the high watermark is queued - we // need to pause TCP socket/HTTP parser, and wait until the data will be // sent to the client. outgoingData += delta; if (socket._paused && outgoingData < socket._writableState.highWaterMark) return socketOnDrain(); } function abortIncoming() { while (incoming.length) { var req = incoming.shift(); req.emit('aborted'); req.emit('close'); } // abort socket._httpMessage ? } function serverSocketCloseListener() { debug('server socket close'); // mark this parser as reusable if (this.parser) { freeParser(this.parser, null, this); } abortIncoming(); } debug('SERVER new http connection'); httpSocketSetup(socket); // If the user has added a listener to the server, // request, or response, then it's their responsibility. // otherwise, destroy on timeout by default if (self.timeout) socket.setTimeout(self.timeout); socket.on('timeout', function() { var req = socket.parser && socket.parser.incoming; var reqTimeout = req && !req.complete && req.emit('timeout', socket); var res = socket._httpMessage; var resTimeout = res && res.emit('timeout', socket); var serverTimeout = self.emit('timeout', socket); if (!reqTimeout && !resTimeout && !serverTimeout) socket.destroy(); }); var parser = parsers.alloc(); parser.reinitialize(HTTPParser.REQUEST); parser.socket = socket; socket.parser = parser; parser.incoming = null; // Propagate headers limit from server instance to parser if (typeof this.maxHeadersCount === 'number') { parser.maxHeaderPairs = this.maxHeadersCount << 1; } else { // Set default value because parser may be reused from FreeList parser.maxHeaderPairs = 2000; } socket.addListener('error', socketOnError); socket.addListener('close', serverSocketCloseListener); parser.onIncoming = parserOnIncoming; socket.on('end', socketOnEnd); socket.on('data', socketOnData); // We are consuming socket, so it won't get any actual data socket.on('resume', onSocketResume); socket.on('pause', onSocketPause); socket.on('drain', socketOnDrain); // Override on to unconsume on `data`, `readable` listeners socket.on = socketOnWrap; var external = socket._handle._externalStream; if (external) { parser._consumed = true; parser.consume(external); } external = null; parser[kOnExecute] = onParserExecute; // TODO(isaacs): Move all these functions out of here function socketOnError(e) { // Ignore further errors this.removeListener('error', socketOnError); this.on('error', () => {}); if (!self.emit('clientError', e, this)) this.destroy(e); } function socketOnData(d) { assert(!socket._paused); debug('SERVER socketOnData %d', d.length); var ret = parser.execute(d); onParserExecuteCommon(ret, d); } function onParserExecute(ret, d) { socket._unrefTimer(); debug('SERVER socketOnParserExecute %d', ret); onParserExecuteCommon(ret, undefined); } function onParserExecuteCommon(ret, d) { if (ret instanceof Error) { debug('parse error'); socketOnError.call(socket, ret); } else if (parser.incoming && parser.incoming.upgrade) { // Upgrade or CONNECT var bytesParsed = ret; var req = parser.incoming; debug('SERVER upgrade or connect', req.method); if (!d) d = parser.getCurrentBuffer(); socket.removeListener('data', socketOnData); socket.removeListener('end', socketOnEnd); socket.removeListener('close', serverSocketCloseListener); unconsume(parser, socket); parser.finish(); freeParser(parser, req, null); parser = null; var eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade'; if (self.listenerCount(eventName) > 0) { debug('SERVER have listener for %s', eventName); var bodyHead = d.slice(bytesParsed, d.length); // TODO(isaacs): Need a way to reset a stream to fresh state // IE, not flowing, and not explicitly paused. socket._readableState.flowing = null; self.emit(eventName, req, socket, bodyHead); } else { // Got upgrade header or CONNECT method, but have no handler. socket.destroy(); } } if (socket._paused && socket.parser) { // onIncoming paused the socket, we should pause the parser as well debug('pause parser'); socket.parser.pause(); } } function socketOnEnd() { var socket = this; var ret = parser.finish(); if (ret instanceof Error) { debug('parse error'); socketOnError.call(socket, ret); return; } if (!self.httpAllowHalfOpen) { abortIncoming(); if (socket.writable) socket.end(); } else if (outgoing.length) { outgoing[outgoing.length - 1]._last = true; } else if (socket._httpMessage) { socket._httpMessage._last = true; } else { if (socket.writable) socket.end(); } } // The following callback is issued after the headers have been read on a // new message. In this callback we setup the response object and pass it // to the user. socket._paused = false; function socketOnDrain() { var needPause = outgoingData > socket._writableState.highWaterMark; // If we previously paused, then start reading again. if (socket._paused && !needPause) { socket._paused = false; if (socket.parser) socket.parser.resume(); socket.resume(); } } function parserOnIncoming(req, shouldKeepAlive) { incoming.push(req); // If the writable end isn't consuming, then stop reading // so that we don't become overwhelmed by a flood of // pipelined requests that may never be resolved. if (!socket._paused) { var needPause = socket._writableState.needDrain || outgoingData >= socket._writableState.highWaterMark; if (needPause) { socket._paused = true; // We also need to pause the parser, but don't do that until after // the call to execute, because we may still be processing the last // chunk. socket.pause(); } } var res = new ServerResponse(req); res._onPendingData = updateOutgoingData; res.shouldKeepAlive = shouldKeepAlive; DTRACE_HTTP_SERVER_REQUEST(req, socket); LTTNG_HTTP_SERVER_REQUEST(req, socket); COUNTER_HTTP_SERVER_REQUEST(); if (socket._httpMessage) { // There are already pending outgoing res, append. outgoing.push(res); } else { res.assignSocket(socket); } // When we're finished writing the response, check if this is the last // response, if so destroy the socket. res.on('finish', resOnFinish); function resOnFinish() { // Usually the first incoming element should be our request. it may // be that in the case abortIncoming() was called that the incoming // array will be empty. assert(incoming.length === 0 || incoming[0] === req); incoming.shift(); // if the user never called req.read(), and didn't pipe() or // .resume() or .on('data'), then we call req._dump() so that the // bytes will be pulled off the wire. if (!req._consuming && !req._readableState.resumeScheduled) req._dump(); res.detachSocket(socket); if (res._last) { socket.destroySoon(); } else { // start sending the next message var m = outgoing.shift(); if (m) { m.assignSocket(socket); } } } if (req.headers.expect !== undefined && (req.httpVersionMajor == 1 && req.httpVersionMinor == 1)) { if (continueExpression.test(req.headers.expect)) { res._expect_continue = true; if (self.listenerCount('checkContinue') > 0) { self.emit('checkContinue', req, res); } else { res.writeContinue(); self.emit('request', req, res); } } else { if (self.listenerCount('checkExpectation') > 0) { self.emit('checkExpectation', req, res); } else { res.writeHead(417); res.end(); } } } else { self.emit('request', req, res); } return false; // Not a HEAD response. (Not even a response!) } } exports._connectionListener = connectionListener; function onSocketResume() { // It may seem that the socket is resumed, but this is an enemy's trick to // deceive us! `resume` is emitted asynchronously, and may be called from // `incoming.readStart()`. Stop the socket again here, just to preserve the // state. // // We don't care about stream semantics for the consumed socket anyway. if (this._paused) { this.pause(); return; } if (this._handle && !this._handle.reading) { this._handle.reading = true; this._handle.readStart(); } } function onSocketPause() { if (this._handle && this._handle.reading) { this._handle.reading = false; this._handle.readStop(); } } function unconsume(parser, socket) { if (socket._handle) { if (parser._consumed) parser.unconsume(socket._handle._externalStream); parser._consumed = false; socket.removeListener('pause', onSocketPause); socket.removeListener('resume', onSocketResume); } } function socketOnWrap(ev, fn) { var res = net.Socket.prototype.on.call(this, ev, fn); if (!this.parser) { this.on = net.Socket.prototype.on; return res; } if (ev === 'data' || ev === 'readable') unconsume(this.parser, this); return res; }
'use strict'; const util = require('util'); const net = require('net'); const HTTPParser = process.binding('http_parser').HTTPParser; const assert = require('assert').ok; const common = require('_http_common'); const parsers = common.parsers; const freeParser = common.freeParser; const debug = common.debug; const CRLF = common.CRLF; const continueExpression = common.continueExpression; const chunkExpression = common.chunkExpression; const httpSocketSetup = common.httpSocketSetup; const OutgoingMessage = require('_http_outgoing').OutgoingMessage; const STATUS_CODES = exports.STATUS_CODES = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', // RFC 2518, obsoleted by RFC 4918 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', // RFC 4918 208: 'Already Reported', 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 307: 'Temporary Redirect', 308: 'Permanent Redirect', // RFC 7238 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Payload Too Large', 414: 'URI Too Long', 415: 'Unsupported Media Type', 416: 'Range Not Satisfiable', 417: 'Expectation Failed', 418: 'I\'m a teapot', // RFC 2324 421: 'Misdirected Request', 422: 'Unprocessable Entity', // RFC 4918 423: 'Locked', // RFC 4918 424: 'Failed Dependency', // RFC 4918 425: 'Unordered Collection', // RFC 4918 426: 'Upgrade Required', // RFC 2817 428: 'Precondition Required', // RFC 6585 429: 'Too Many Requests', // RFC 6585 431: 'Request Header Fields Too Large', // RFC 6585 451: 'Unavailable For Legal Reasons', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', // RFC 2295 507: 'Insufficient Storage', // RFC 4918 508: 'Loop Detected', 509: 'Bandwidth Limit Exceeded', 510: 'Not Extended', // RFC 2774 511: 'Network Authentication Required' // RFC 6585 }; const kOnExecute = HTTPParser.kOnExecute | 0; function ServerResponse(req) { OutgoingMessage.call(this); if (req.method === 'HEAD') this._hasBody = false; this.sendDate = true; if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) { this.useChunkedEncodingByDefault = chunkExpression.test(req.headers.te); this.shouldKeepAlive = false; } } util.inherits(ServerResponse, OutgoingMessage); ServerResponse.prototype._finish = function() { DTRACE_HTTP_SERVER_RESPONSE(this.connection); LTTNG_HTTP_SERVER_RESPONSE(this.connection); COUNTER_HTTP_SERVER_RESPONSE(); OutgoingMessage.prototype._finish.call(this); }; exports.ServerResponse = ServerResponse; ServerResponse.prototype.statusCode = 200; ServerResponse.prototype.statusMessage = undefined; function onServerResponseClose() { // EventEmitter.emit makes a copy of the 'close' listeners array before // calling the listeners. detachSocket() unregisters onServerResponseClose // but if detachSocket() is called, directly or indirectly, by a 'close' // listener, onServerResponseClose is still in that copy of the listeners // array. That is, in the example below, b still gets called even though // it's been removed by a: // // var EventEmitter = require('events'); // var obj = new EventEmitter(); // obj.on('event', a); // obj.on('event', b); // function a() { obj.removeListener('event', b) } // function b() { throw "BAM!" } // obj.emit('event'); // throws // // Ergo, we need to deal with stale 'close' events and handle the case // where the ServerResponse object has already been deconstructed. // Fortunately, that requires only a single if check. :-) if (this._httpMessage) this._httpMessage.emit('close'); } ServerResponse.prototype.assignSocket = function(socket) { assert(!socket._httpMessage); socket._httpMessage = this; socket.on('close', onServerResponseClose); this.socket = socket; this.connection = socket; this.emit('socket', socket); this._flush(); }; ServerResponse.prototype.detachSocket = function(socket) { assert(socket._httpMessage === this); socket.removeListener('close', onServerResponseClose); socket._httpMessage = null; this.socket = this.connection = null; }; ServerResponse.prototype.writeContinue = function(cb) { this._writeRaw('HTTP/1.1 100 Continue' + CRLF + CRLF, 'ascii', cb); this._sent100 = true; }; ServerResponse.prototype._implicitHeader = function() { this.writeHead(this.statusCode); }; ServerResponse.prototype.writeHead = function(statusCode, reason, obj) { var headers; if (typeof reason === 'string') { // writeHead(statusCode, reasonPhrase[, headers]) this.statusMessage = reason; } else { // writeHead(statusCode[, headers]) this.statusMessage = this.statusMessage || STATUS_CODES[statusCode] || 'unknown'; obj = reason; } this.statusCode = statusCode; if (this._headers) { // Slow-case: when progressive API and header fields are passed. if (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (k) this.setHeader(k, obj[k]); } } // only progressive api is used headers = this._renderHeaders(); } else { // only writeHead() called headers = obj; } statusCode |= 0; if (statusCode < 100 || statusCode > 999) throw new RangeError(`Invalid status code: ${statusCode}`); if (common._checkInvalidHeaderChar(this.statusMessage)) throw new Error('Invalid character in statusMessage.'); var statusLine = 'HTTP/1.1 ' + statusCode.toString() + ' ' + this.statusMessage + CRLF; if (statusCode === 204 || statusCode === 304 || (100 <= statusCode && statusCode <= 199)) { // RFC 2616, 10.2.5: // The 204 response MUST NOT include a message-body, and thus is always // terminated by the first empty line after the header fields. // RFC 2616, 10.3.5: // The 304 response MUST NOT contain a message-body, and thus is always // terminated by the first empty line after the header fields. // RFC 2616, 10.1 Informational 1xx: // This class of status code indicates a provisional response, // consisting only of the Status-Line and optional headers, and is // terminated by an empty line. this._hasBody = false; } // don't keep alive connections where the client expects 100 Continue // but we sent a final status; they may put extra bytes on the wire. if (this._expect_continue && !this._sent100) { this.shouldKeepAlive = false; } this._storeHeader(statusLine, headers); }; ServerResponse.prototype.writeHeader = function() { this.writeHead.apply(this, arguments); }; function Server(requestListener) { if (!(this instanceof Server)) return new Server(requestListener); net.Server.call(this, { allowHalfOpen: true }); if (requestListener) { this.addListener('request', requestListener); } /* eslint-disable max-len */ // Similar option to this. Too lazy to write my own docs. // http://www.squid-cache.org/Doc/config/half_closed_clients/ // http://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F /* eslint-enable max-len */ this.httpAllowHalfOpen = false; this.addListener('connection', connectionListener); this.timeout = 2 * 60 * 1000; this._pendingResponseData = 0; } util.inherits(Server, net.Server); Server.prototype.setTimeout = function(msecs, callback) { this.timeout = msecs; if (callback) this.on('timeout', callback); return this; }; exports.Server = Server; function connectionListener(socket) { var self = this; var outgoing = []; var incoming = []; var outgoingData = 0; function updateOutgoingData(delta) { // `outgoingData` is an approximate amount of bytes queued through all // inactive responses. If more data than the high watermark is queued - we // need to pause TCP socket/HTTP parser, and wait until the data will be // sent to the client. outgoingData += delta; if (socket._paused && outgoingData < socket._writableState.highWaterMark) return socketOnDrain(); } function abortIncoming() { while (incoming.length) { var req = incoming.shift(); req.emit('aborted'); req.emit('close'); } // abort socket._httpMessage ? } function serverSocketCloseListener() { debug('server socket close'); // mark this parser as reusable if (this.parser) { freeParser(this.parser, null, this); } abortIncoming(); } debug('SERVER new http connection'); httpSocketSetup(socket); // If the user has added a listener to the server, // request, or response, then it's their responsibility. // otherwise, destroy on timeout by default if (self.timeout) socket.setTimeout(self.timeout); socket.on('timeout', function() { var req = socket.parser && socket.parser.incoming; var reqTimeout = req && !req.complete && req.emit('timeout', socket); var res = socket._httpMessage; var resTimeout = res && res.emit('timeout', socket); var serverTimeout = self.emit('timeout', socket); if (!reqTimeout && !resTimeout && !serverTimeout) socket.destroy(); }); var parser = parsers.alloc(); parser.reinitialize(HTTPParser.REQUEST); parser.socket = socket; socket.parser = parser; parser.incoming = null; // Propagate headers limit from server instance to parser if (typeof this.maxHeadersCount === 'number') { parser.maxHeaderPairs = this.maxHeadersCount << 1; } else { // Set default value because parser may be reused from FreeList parser.maxHeaderPairs = 2000; } socket.addListener('error', socketOnError); socket.addListener('close', serverSocketCloseListener); parser.onIncoming = parserOnIncoming; socket.on('end', socketOnEnd); socket.on('data', socketOnData); // We are consuming socket, so it won't get any actual data socket.on('resume', onSocketResume); socket.on('pause', onSocketPause); socket.on('drain', socketOnDrain); // Override on to unconsume on `data`, `readable` listeners socket.on = socketOnWrap; var external = socket._handle._externalStream; if (external) { parser._consumed = true; parser.consume(external); } external = null; parser[kOnExecute] = onParserExecute; // TODO(isaacs): Move all these functions out of here function socketOnError(e) { // Ignore further errors this.removeListener('error', socketOnError); this.on('error', () => {}); if (!self.emit('clientError', e, this)) this.destroy(e); } function socketOnData(d) { assert(!socket._paused); debug('SERVER socketOnData %d', d.length); var ret = parser.execute(d); onParserExecuteCommon(ret, d); } function onParserExecute(ret, d) { socket._unrefTimer(); debug('SERVER socketOnParserExecute %d', ret); onParserExecuteCommon(ret, undefined); } function onParserExecuteCommon(ret, d) { if (ret instanceof Error) { debug('parse error'); socketOnError.call(socket, ret); } else if (parser.incoming && parser.incoming.upgrade) { // Upgrade or CONNECT var bytesParsed = ret; var req = parser.incoming; debug('SERVER upgrade or connect', req.method); if (!d) d = parser.getCurrentBuffer(); socket.removeListener('data', socketOnData); socket.removeListener('end', socketOnEnd); socket.removeListener('close', serverSocketCloseListener); unconsume(parser, socket); parser.finish(); freeParser(parser, req, null); parser = null; var eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade'; if (self.listenerCount(eventName) > 0) { debug('SERVER have listener for %s', eventName); var bodyHead = d.slice(bytesParsed, d.length); // TODO(isaacs): Need a way to reset a stream to fresh state // IE, not flowing, and not explicitly paused. socket._readableState.flowing = null; self.emit(eventName, req, socket, bodyHead); } else { // Got upgrade header or CONNECT method, but have no handler. socket.destroy(); } } if (socket._paused && socket.parser) { // onIncoming paused the socket, we should pause the parser as well debug('pause parser'); socket.parser.pause(); } } function socketOnEnd() { var socket = this; var ret = parser.finish(); if (ret instanceof Error) { debug('parse error'); socketOnError.call(socket, ret); return; } if (!self.httpAllowHalfOpen) { abortIncoming(); if (socket.writable) socket.end(); } else if (outgoing.length) { outgoing[outgoing.length - 1]._last = true; } else if (socket._httpMessage) { socket._httpMessage._last = true; } else { if (socket.writable) socket.end(); } } // The following callback is issued after the headers have been read on a // new message. In this callback we setup the response object and pass it // to the user. socket._paused = false; function socketOnDrain() { var needPause = outgoingData > socket._writableState.highWaterMark; // If we previously paused, then start reading again. if (socket._paused && !needPause) { socket._paused = false; if (socket.parser) socket.parser.resume(); socket.resume(); } } function parserOnIncoming(req, shouldKeepAlive) { incoming.push(req); // If the writable end isn't consuming, then stop reading // so that we don't become overwhelmed by a flood of // pipelined requests that may never be resolved. if (!socket._paused) { var needPause = socket._writableState.needDrain || outgoingData >= socket._writableState.highWaterMark; if (needPause) { socket._paused = true; // We also need to pause the parser, but don't do that until after // the call to execute, because we may still be processing the last // chunk. socket.pause(); } } var res = new ServerResponse(req); res._onPendingData = updateOutgoingData; res.shouldKeepAlive = shouldKeepAlive; DTRACE_HTTP_SERVER_REQUEST(req, socket); LTTNG_HTTP_SERVER_REQUEST(req, socket); COUNTER_HTTP_SERVER_REQUEST(); if (socket._httpMessage) { // There are already pending outgoing res, append. outgoing.push(res); } else { res.assignSocket(socket); } // When we're finished writing the response, check if this is the last // response, if so destroy the socket. res.on('finish', resOnFinish); function resOnFinish() { // Usually the first incoming element should be our request. it may // be that in the case abortIncoming() was called that the incoming // array will be empty. assert(incoming.length === 0 || incoming[0] === req); incoming.shift(); // if the user never called req.read(), and didn't pipe() or // .resume() or .on('data'), then we call req._dump() so that the // bytes will be pulled off the wire. if (!req._consuming && !req._readableState.resumeScheduled) req._dump(); res.detachSocket(socket); if (res._last) { socket.destroySoon(); } else { // start sending the next message var m = outgoing.shift(); if (m) { m.assignSocket(socket); } } } if (req.headers.expect !== undefined && (req.httpVersionMajor == 1 && req.httpVersionMinor == 1)) { if (continueExpression.test(req.headers.expect)) { res._expect_continue = true; if (self.listenerCount('checkContinue') > 0) { self.emit('checkContinue', req, res); } else { res.writeContinue(); self.emit('request', req, res); } } else { if (self.listenerCount('checkExpectation') > 0) { self.emit('checkExpectation', req, res); } else { res.writeHead(417); res.end(); } } } else { self.emit('request', req, res); } return false; // Not a HEAD response. (Not even a response!) } } exports._connectionListener = connectionListener; function onSocketResume() { // It may seem that the socket is resumed, but this is an enemy's trick to // deceive us! `resume` is emitted asynchronously, and may be called from // `incoming.readStart()`. Stop the socket again here, just to preserve the // state. // // We don't care about stream semantics for the consumed socket anyway. if (this._paused) { this.pause(); return; } if (this._handle && !this._handle.reading) { this._handle.reading = true; this._handle.readStart(); } } function onSocketPause() { if (this._handle && this._handle.reading) { this._handle.reading = false; this._handle.readStop(); } } function unconsume(parser, socket) { if (socket._handle) { if (parser._consumed) parser.unconsume(socket._handle._externalStream); parser._consumed = false; socket.removeListener('pause', onSocketPause); socket.removeListener('resume', onSocketResume); } } function socketOnWrap(ev, fn) { var res = net.Socket.prototype.on.call(this, ev, fn); if (!this.parser) { this.on = net.Socket.prototype.on; return res; } if (ev === 'data' || ev === 'readable') unconsume(this.parser, this); return res; }
5103_0
crossvul
js
CWE-116
"Improper Encoding or Escaping of Output - Improper encoding or escaping can allow attackers to chan(...TRUNCATED)
python
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyrigt: (c) 2017, Yanis Guenane <yanis+ansible@gu(...TRUNCATED)
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyrigt: (c) 2017, Yanis Guenane <yanis+ansible@gu(...TRUNCATED)
4295_1
crossvul
py
CWE-116
"Improper Encoding or Escaping of Output - Improper encoding or escaping can allow attackers to chan(...TRUNCATED)
python
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2016, Yanis Guenane <yanis+ansible@g(...TRUNCATED)
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2016, Yanis Guenane <yanis+ansible@g(...TRUNCATED)
4295_2
crossvul
py
CWE-116
"Improper Encoding or Escaping of Output - Improper encoding or escaping can allow attackers to chan(...TRUNCATED)
python
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2016-2017, Yanis Guenane <yanis+ansi(...TRUNCATED)
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2016-2017, Yanis Guenane <yanis+ansi(...TRUNCATED)
4295_3
crossvul
py
CWE-116
"Improper Encoding or Escaping of Output - Improper encoding or escaping can allow attackers to chan(...TRUNCATED)
python
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2016, Yanis Guenane <yanis+ansible@g(...TRUNCATED)
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2016, Yanis Guenane <yanis+ansible@g(...TRUNCATED)
4295_4
crossvul
py
CWE-116
"Improper Encoding or Escaping of Output - Improper encoding or escaping can allow attackers to chan(...TRUNCATED)
python
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2019, Patrick Pichler <ppichler+ansi(...TRUNCATED)
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2019, Patrick Pichler <ppichler+ansi(...TRUNCATED)
4295_5
crossvul
py
CWE-116
"Improper Encoding or Escaping of Output - Improper encoding or escaping can allow attackers to chan(...TRUNCATED)
python
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2016-2017, Yanis Guenane <yanis+ansi(...TRUNCATED)
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2016-2017, Yanis Guenane <yanis+ansi(...TRUNCATED)
4295_6
crossvul
py
End of preview. Expand in Data Studio

CrossVul Multi-Language Security Vulnerability Dataset

Security vulnerability dataset from CrossVul with 9,313 before/after code pairs across 158 CWE categories and 21 programming languages.

Contains vulnerable code examples paired with their secure fixes, ideal for training AI models on security code remediation.

Dataset Statistics

  • Total Examples: 9,313
  • CWE Categories: 158
  • Languages: 21
  • Format: Raw vulnerability records (JSON Lines)

Top Languages

Language Examples
c 3,972
php 2,139
javascript 660
python 492
java 489
ruby 422
cpp 399
go 172
xml 106
json 97

Top CWE Categories

CWE ID Description Examples
CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') - Cross-site scripting (XSS) vulnerabilities occur when: Untrusted data enters a web application, typically from a web request. 1,426
CWE-119 Improper Restriction of Operations within the Bounds of a Memory Buffer - Certain languages allow direct addressing of memory locations and do not automatically ensure that these locations are valid for the memory buffer that is being referenced. 724
CWE-20 Improper Input Validation - Input validation is a frequently-used technique for checking potentially dangerous inputs in order to ensure that the inputs are safe for processing within the code, or when communicating with othe... 710
CWE-125 Out-of-bounds Read - Typically, this can allow attackers to read sensitive information from other memory locations or cause a crash. 531
CWE-200 Exposure of Sensitive Information to an Unauthorized Actor - There are many different kinds of mistakes that introduce information exposures. 448
CWE-264 Permissions, Privileges, and Access Controls 419
CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data. 393
CWE-352 Cross-Site Request Forgery (CSRF) - When a web server is designed to receive a request from a client without any mechanism for verifying that it was intentionally sent, then it might be possible for an attacker to trick a client into... 298
CWE-476 NULL Pointer Dereference - NULL pointer dereference issues can occur through a number of flaws, including race conditions, and simple programming omissions. 244
CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') - Many file operations are intended to take place within a restricted directory. 231

Usage

from datasets import load_dataset

# Load raw vulnerability dataset
dataset = load_dataset("hitoshura25/crossvul")

# Example raw record format
record = dataset['train'][0]
print(record)
# {
#   'cwe_id': 'CWE-79',
#   'cwe_description': 'Cross-site Scripting (XSS)',
#   'language': 'java',
#   'vulnerable_code': '...',
#   'fixed_code': '...',
#   'file_pair_id': '1163_0',
#   'source': 'crossvul',
#   'language_dir': 'java'
# }

Processing for Training

This dataset contains raw vulnerability data. To use for training:

Step 1: Transform into Chat Format (process_artifacts.py)

# Transform raw records into chat-formatted training pairs
def transform_to_chat(record):
    return {
        'messages': [
            {'role': 'system', 'content': 'Security expert...'},
            {'role': 'user', 'content': f"Fix {record['cwe_id']} in {record['language']}:\n{record['vulnerable_code']}"},
            {'role': 'assistant', 'content': f"Fixed code:\n{record['fixed_code']}"}
        ]
    }

Step 2: Sequential Fine-Tuning

# Stage 1: General security training (this dataset)
model = train_on_crossvul(
    model_path="base-model",
    dataset="hitoshura25/crossvul",
    transform_fn=transform_to_chat
)

# Stage 2: Project-specific adaptation
model = specialized_training(
    base_model=model,
    project_data="your-vulnerability-dataset",
    memory_replay=0.15  # 15% CrossVul to prevent forgetting
)

Citation

If you use this dataset, please cite the original CrossVul paper:

@inproceedings{wartschinski2022vulnrepair,
  title={VulnRepair: Learning to Repair Vulnerable Code with Graph Neural Networks},
  author={Wartschinski, Laura and Noller, Yannic and Vogel, Thomas and Kehrer, Timo and Grunske, Lars},
  booktitle={Proceedings of the 44th International Conference on Software Engineering},
  year={2022}
}

License

Apache License 2.0 - Derived from CrossVul Dataset

Dataset Preprocessing

This dataset was processed from the original CrossVul dataset using automated scripts to:

  • Match vulnerable/fixed code pairs (bad_*/good_* files)
  • Detect programming language from directory structure
  • Filter by file size and quality (<500KB, >50 chars)
  • Extract CWE metadata and descriptions
  • Output raw JSON Lines format (no chat formatting)

Note: This is a raw dataset. Use process_artifacts.py to transform into chat-formatted training data.

Preprocessing script: crossvul_dataset_loader.py

Downloads last month
51