id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
161,500 | cloudflare/cfssl | api/client/client.go | Sign | func (ar *AuthRemote) Sign(req []byte) ([]byte, error) {
return ar.AuthSign(req, nil, ar.provider)
} | go | func (ar *AuthRemote) Sign(req []byte) ([]byte, error) {
return ar.AuthSign(req, nil, ar.provider)
} | [
"func",
"(",
"ar",
"*",
"AuthRemote",
")",
"Sign",
"(",
"req",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"ar",
".",
"AuthSign",
"(",
"req",
",",
"nil",
",",
"ar",
".",
"provider",
")",
"\n",
"}"
] | // Sign is overloaded to perform an AuthSign request using the default auth provider. | [
"Sign",
"is",
"overloaded",
"to",
"perform",
"an",
"AuthSign",
"request",
"using",
"the",
"default",
"auth",
"provider",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/client/client.go#L327-L329 |
161,501 | cloudflare/cfssl | cmd/multirootca/api.go | incRequests | func incRequests() {
stats.TotalRequestRate.Mark(1)
eCtr := float64(stats.ErrorRate.Count())
rCtr := float64(stats.TotalRequestRate.Count())
stats.ErrorPercent.Update(eCtr / rCtr * 100)
} | go | func incRequests() {
stats.TotalRequestRate.Mark(1)
eCtr := float64(stats.ErrorRate.Count())
rCtr := float64(stats.TotalRequestRate.Count())
stats.ErrorPercent.Update(eCtr / rCtr * 100)
} | [
"func",
"incRequests",
"(",
")",
"{",
"stats",
".",
"TotalRequestRate",
".",
"Mark",
"(",
"1",
")",
"\n",
"eCtr",
":=",
"float64",
"(",
"stats",
".",
"ErrorRate",
".",
"Count",
"(",
")",
")",
"\n",
"rCtr",
":=",
"float64",
"(",
"stats",
".",
"TotalRe... | // incRequests increments the request count and updates the error percentage. | [
"incRequests",
"increments",
"the",
"request",
"count",
"and",
"updates",
"the",
"error",
"percentage",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cmd/multirootca/api.go#L69-L74 |
161,502 | cloudflare/cfssl | log/log.go | Fatalf | func Fatalf(format string, v ...interface{}) {
outputf(LevelFatal, format, v)
os.Exit(1)
} | go | func Fatalf(format string, v ...interface{}) {
outputf(LevelFatal, format, v)
os.Exit(1)
} | [
"func",
"Fatalf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"outputf",
"(",
"LevelFatal",
",",
"format",
",",
"v",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // Fatalf logs a formatted message at the "fatal" level and then exits. The
// arguments are handled in the same manner as fmt.Printf. | [
"Fatalf",
"logs",
"a",
"formatted",
"message",
"at",
"the",
"fatal",
"level",
"and",
"then",
"exits",
".",
"The",
"arguments",
"are",
"handled",
"in",
"the",
"same",
"manner",
"as",
"fmt",
".",
"Printf",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/log/log.go#L98-L101 |
161,503 | cloudflare/cfssl | scan/crypto/tls/tls.go | Dial | func Dial(network, addr string, config *Config) (*Conn, error) {
return DialWithDialer(new(net.Dialer), network, addr, config)
} | go | func Dial(network, addr string, config *Config) (*Conn, error) {
return DialWithDialer(new(net.Dialer), network, addr, config)
} | [
"func",
"Dial",
"(",
"network",
",",
"addr",
"string",
",",
"config",
"*",
"Config",
")",
"(",
"*",
"Conn",
",",
"error",
")",
"{",
"return",
"DialWithDialer",
"(",
"new",
"(",
"net",
".",
"Dialer",
")",
",",
"network",
",",
"addr",
",",
"config",
... | // Dial connects to the given network address using net.Dial
// and then initiates a TLS handshake, returning the resulting
// TLS connection.
// Dial interprets a nil configuration as equivalent to
// the zero configuration; see the documentation of Config
// for the defaults. | [
"Dial",
"connects",
"to",
"the",
"given",
"network",
"address",
"using",
"net",
".",
"Dial",
"and",
"then",
"initiates",
"a",
"TLS",
"handshake",
"returning",
"the",
"resulting",
"TLS",
"connection",
".",
"Dial",
"interprets",
"a",
"nil",
"configuration",
"as"... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/tls.go#L170-L172 |
161,504 | cloudflare/cfssl | transport/roots/provider.go | Pool | func (ts *TrustStore) Pool() *x509.CertPool {
var pool = x509.NewCertPool()
for _, cert := range ts.roots {
pool.AddCert(cert)
}
return pool
} | go | func (ts *TrustStore) Pool() *x509.CertPool {
var pool = x509.NewCertPool()
for _, cert := range ts.roots {
pool.AddCert(cert)
}
return pool
} | [
"func",
"(",
"ts",
"*",
"TrustStore",
")",
"Pool",
"(",
")",
"*",
"x509",
".",
"CertPool",
"{",
"var",
"pool",
"=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"for",
"_",
",",
"cert",
":=",
"range",
"ts",
".",
"roots",
"{",
"pool",
".",
"AddCert... | // Pool returns a certificate pool containing the certificates
// loaded into the provider. | [
"Pool",
"returns",
"a",
"certificate",
"pool",
"containing",
"the",
"certificates",
"loaded",
"into",
"the",
"provider",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/roots/provider.go#L30-L36 |
161,505 | cloudflare/cfssl | transport/roots/provider.go | Certificates | func (ts *TrustStore) Certificates() []*x509.Certificate {
var roots = make([]*x509.Certificate, 0, len(ts.roots))
for _, cert := range ts.roots {
roots = append(roots, cert)
}
return roots
} | go | func (ts *TrustStore) Certificates() []*x509.Certificate {
var roots = make([]*x509.Certificate, 0, len(ts.roots))
for _, cert := range ts.roots {
roots = append(roots, cert)
}
return roots
} | [
"func",
"(",
"ts",
"*",
"TrustStore",
")",
"Certificates",
"(",
")",
"[",
"]",
"*",
"x509",
".",
"Certificate",
"{",
"var",
"roots",
"=",
"make",
"(",
"[",
"]",
"*",
"x509",
".",
"Certificate",
",",
"0",
",",
"len",
"(",
"ts",
".",
"roots",
")",
... | // Certificates returns a slice of the loaded certificates. | [
"Certificates",
"returns",
"a",
"slice",
"of",
"the",
"loaded",
"certificates",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/roots/provider.go#L39-L45 |
161,506 | cloudflare/cfssl | transport/roots/provider.go | New | func New(rootDefs []*core.Root) (*TrustStore, error) {
var err error
var store = &TrustStore{}
var roots []*x509.Certificate
if len(rootDefs) == 0 {
roots, err = system.New(nil)
if err != nil {
return nil, err
}
store.addCerts(roots)
return store, nil
}
err = errors.New("transport: no supported root providers found")
for _, root := range rootDefs {
pfn, ok := Providers[root.Type]
if ok {
roots, err = pfn(root.Metadata)
if err != nil {
break
}
store.addCerts(roots)
}
}
if err != nil {
store = nil
}
return store, err
} | go | func New(rootDefs []*core.Root) (*TrustStore, error) {
var err error
var store = &TrustStore{}
var roots []*x509.Certificate
if len(rootDefs) == 0 {
roots, err = system.New(nil)
if err != nil {
return nil, err
}
store.addCerts(roots)
return store, nil
}
err = errors.New("transport: no supported root providers found")
for _, root := range rootDefs {
pfn, ok := Providers[root.Type]
if ok {
roots, err = pfn(root.Metadata)
if err != nil {
break
}
store.addCerts(roots)
}
}
if err != nil {
store = nil
}
return store, err
} | [
"func",
"New",
"(",
"rootDefs",
"[",
"]",
"*",
"core",
".",
"Root",
")",
"(",
"*",
"TrustStore",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n\n",
"var",
"store",
"=",
"&",
"TrustStore",
"{",
"}",
"\n",
"var",
"roots",
"[",
"]",
"*",
"x509",... | // New produces a new trusted root provider from a collection of
// roots. If there are no roots, the system roots will be used. | [
"New",
"produces",
"a",
"new",
"trusted",
"root",
"provider",
"from",
"a",
"collection",
"of",
"roots",
".",
"If",
"there",
"are",
"no",
"roots",
"the",
"system",
"roots",
"will",
"be",
"used",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/roots/provider.go#L74-L107 |
161,507 | cloudflare/cfssl | transport/roots/provider.go | TrustPEM | func TrustPEM(metadata map[string]string) ([]*x509.Certificate, error) {
sourceFile, ok := metadata["source"]
if !ok {
return nil, errors.New("transport: PEM source requires a source file")
}
in, err := ioutil.ReadFile(sourceFile)
if err != nil {
return nil, err
}
return helpers.ParseCertificatesPEM(in)
} | go | func TrustPEM(metadata map[string]string) ([]*x509.Certificate, error) {
sourceFile, ok := metadata["source"]
if !ok {
return nil, errors.New("transport: PEM source requires a source file")
}
in, err := ioutil.ReadFile(sourceFile)
if err != nil {
return nil, err
}
return helpers.ParseCertificatesPEM(in)
} | [
"func",
"TrustPEM",
"(",
"metadata",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"[",
"]",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"sourceFile",
",",
"ok",
":=",
"metadata",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"r... | // TrustPEM takes a source file containing one or more certificates
// and adds them to the trust store. | [
"TrustPEM",
"takes",
"a",
"source",
"file",
"containing",
"one",
"or",
"more",
"certificates",
"and",
"adds",
"them",
"to",
"the",
"trust",
"store",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/roots/provider.go#L111-L123 |
161,508 | cloudflare/cfssl | helpers/helpers.go | InclusiveDate | func InclusiveDate(year int, month time.Month, day int) time.Time {
return time.Date(year, month, day, 0, 0, 0, 0, time.UTC).Add(-1 * time.Nanosecond)
} | go | func InclusiveDate(year int, month time.Month, day int) time.Time {
return time.Date(year, month, day, 0, 0, 0, 0, time.UTC).Add(-1 * time.Nanosecond)
} | [
"func",
"InclusiveDate",
"(",
"year",
"int",
",",
"month",
"time",
".",
"Month",
",",
"day",
"int",
")",
"time",
".",
"Time",
"{",
"return",
"time",
".",
"Date",
"(",
"year",
",",
"month",
",",
"day",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
","... | // InclusiveDate returns the time.Time representation of a date - 1
// nanosecond. This allows time.After to be used inclusively. | [
"InclusiveDate",
"returns",
"the",
"time",
".",
"Time",
"representation",
"of",
"a",
"date",
"-",
"1",
"nanosecond",
".",
"This",
"allows",
"time",
".",
"After",
"to",
"be",
"used",
"inclusively",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L44-L46 |
161,509 | cloudflare/cfssl | helpers/helpers.go | KeyLength | func KeyLength(key interface{}) int {
if key == nil {
return 0
}
if ecdsaKey, ok := key.(*ecdsa.PublicKey); ok {
return ecdsaKey.Curve.Params().BitSize
} else if rsaKey, ok := key.(*rsa.PublicKey); ok {
return rsaKey.N.BitLen()
}
return 0
} | go | func KeyLength(key interface{}) int {
if key == nil {
return 0
}
if ecdsaKey, ok := key.(*ecdsa.PublicKey); ok {
return ecdsaKey.Curve.Params().BitSize
} else if rsaKey, ok := key.(*rsa.PublicKey); ok {
return rsaKey.N.BitLen()
}
return 0
} | [
"func",
"KeyLength",
"(",
"key",
"interface",
"{",
"}",
")",
"int",
"{",
"if",
"key",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"if",
"ecdsaKey",
",",
"ok",
":=",
"key",
".",
"(",
"*",
"ecdsa",
".",
"PublicKey",
")",
";",
"ok",
"{",
"re... | // KeyLength returns the bit size of ECDSA or RSA PublicKey | [
"KeyLength",
"returns",
"the",
"bit",
"size",
"of",
"ECDSA",
"or",
"RSA",
"PublicKey"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L57-L68 |
161,510 | cloudflare/cfssl | helpers/helpers.go | ExpiryTime | func ExpiryTime(chain []*x509.Certificate) (notAfter time.Time) {
if len(chain) == 0 {
return
}
notAfter = chain[0].NotAfter
for _, cert := range chain {
if notAfter.After(cert.NotAfter) {
notAfter = cert.NotAfter
}
}
return
} | go | func ExpiryTime(chain []*x509.Certificate) (notAfter time.Time) {
if len(chain) == 0 {
return
}
notAfter = chain[0].NotAfter
for _, cert := range chain {
if notAfter.After(cert.NotAfter) {
notAfter = cert.NotAfter
}
}
return
} | [
"func",
"ExpiryTime",
"(",
"chain",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"(",
"notAfter",
"time",
".",
"Time",
")",
"{",
"if",
"len",
"(",
"chain",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"notAfter",
"=",
"chain",
"[",
"0",
"... | // ExpiryTime returns the time when the certificate chain is expired. | [
"ExpiryTime",
"returns",
"the",
"time",
"when",
"the",
"certificate",
"chain",
"is",
"expired",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L71-L83 |
161,511 | cloudflare/cfssl | helpers/helpers.go | MonthsValid | func MonthsValid(c *x509.Certificate) int {
issued := c.NotBefore
expiry := c.NotAfter
years := (expiry.Year() - issued.Year())
months := years*12 + int(expiry.Month()) - int(issued.Month())
// Round up if valid for less than a full month
if expiry.Day() > issued.Day() {
months++
}
return months
} | go | func MonthsValid(c *x509.Certificate) int {
issued := c.NotBefore
expiry := c.NotAfter
years := (expiry.Year() - issued.Year())
months := years*12 + int(expiry.Month()) - int(issued.Month())
// Round up if valid for less than a full month
if expiry.Day() > issued.Day() {
months++
}
return months
} | [
"func",
"MonthsValid",
"(",
"c",
"*",
"x509",
".",
"Certificate",
")",
"int",
"{",
"issued",
":=",
"c",
".",
"NotBefore",
"\n",
"expiry",
":=",
"c",
".",
"NotAfter",
"\n",
"years",
":=",
"(",
"expiry",
".",
"Year",
"(",
")",
"-",
"issued",
".",
"Ye... | // MonthsValid returns the number of months for which a certificate is valid. | [
"MonthsValid",
"returns",
"the",
"number",
"of",
"months",
"for",
"which",
"a",
"certificate",
"is",
"valid",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L86-L97 |
161,512 | cloudflare/cfssl | helpers/helpers.go | SignatureString | func SignatureString(alg x509.SignatureAlgorithm) string {
switch alg {
case x509.MD2WithRSA:
return "MD2WithRSA"
case x509.MD5WithRSA:
return "MD5WithRSA"
case x509.SHA1WithRSA:
return "SHA1WithRSA"
case x509.SHA256WithRSA:
return "SHA256WithRSA"
case x509.SHA384WithRSA:
return "SHA384WithRSA"
case x509.SHA512WithRSA:
return "SHA512WithRSA"
case x509.DSAWithSHA1:
return "DSAWithSHA1"
case x509.DSAWithSHA256:
return "DSAWithSHA256"
case x509.ECDSAWithSHA1:
return "ECDSAWithSHA1"
case x509.ECDSAWithSHA256:
return "ECDSAWithSHA256"
case x509.ECDSAWithSHA384:
return "ECDSAWithSHA384"
case x509.ECDSAWithSHA512:
return "ECDSAWithSHA512"
default:
return "Unknown Signature"
}
} | go | func SignatureString(alg x509.SignatureAlgorithm) string {
switch alg {
case x509.MD2WithRSA:
return "MD2WithRSA"
case x509.MD5WithRSA:
return "MD5WithRSA"
case x509.SHA1WithRSA:
return "SHA1WithRSA"
case x509.SHA256WithRSA:
return "SHA256WithRSA"
case x509.SHA384WithRSA:
return "SHA384WithRSA"
case x509.SHA512WithRSA:
return "SHA512WithRSA"
case x509.DSAWithSHA1:
return "DSAWithSHA1"
case x509.DSAWithSHA256:
return "DSAWithSHA256"
case x509.ECDSAWithSHA1:
return "ECDSAWithSHA1"
case x509.ECDSAWithSHA256:
return "ECDSAWithSHA256"
case x509.ECDSAWithSHA384:
return "ECDSAWithSHA384"
case x509.ECDSAWithSHA512:
return "ECDSAWithSHA512"
default:
return "Unknown Signature"
}
} | [
"func",
"SignatureString",
"(",
"alg",
"x509",
".",
"SignatureAlgorithm",
")",
"string",
"{",
"switch",
"alg",
"{",
"case",
"x509",
".",
"MD2WithRSA",
":",
"return",
"\"",
"\"",
"\n",
"case",
"x509",
".",
"MD5WithRSA",
":",
"return",
"\"",
"\"",
"\n",
"c... | // SignatureString returns the TLS signature string corresponding to
// an X509 signature algorithm. | [
"SignatureString",
"returns",
"the",
"TLS",
"signature",
"string",
"corresponding",
"to",
"an",
"X509",
"signature",
"algorithm",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L123-L152 |
161,513 | cloudflare/cfssl | helpers/helpers.go | StringTLSVersion | func StringTLSVersion(version string) uint16 {
switch version {
case "1.2":
return tls.VersionTLS12
case "1.1":
return tls.VersionTLS11
default:
return tls.VersionTLS10
}
} | go | func StringTLSVersion(version string) uint16 {
switch version {
case "1.2":
return tls.VersionTLS12
case "1.1":
return tls.VersionTLS11
default:
return tls.VersionTLS10
}
} | [
"func",
"StringTLSVersion",
"(",
"version",
"string",
")",
"uint16",
"{",
"switch",
"version",
"{",
"case",
"\"",
"\"",
":",
"return",
"tls",
".",
"VersionTLS12",
"\n",
"case",
"\"",
"\"",
":",
"return",
"tls",
".",
"VersionTLS11",
"\n",
"default",
":",
... | // StringTLSVersion returns underlying enum values from human names for TLS
// versions, defaults to current golang default of TLS 1.0 | [
"StringTLSVersion",
"returns",
"underlying",
"enum",
"values",
"from",
"human",
"names",
"for",
"TLS",
"versions",
"defaults",
"to",
"current",
"golang",
"default",
"of",
"TLS",
"1",
".",
"0"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L189-L198 |
161,514 | cloudflare/cfssl | helpers/helpers.go | EncodeCertificatesPEM | func EncodeCertificatesPEM(certs []*x509.Certificate) []byte {
var buffer bytes.Buffer
for _, cert := range certs {
pem.Encode(&buffer, &pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Raw,
})
}
return buffer.Bytes()
} | go | func EncodeCertificatesPEM(certs []*x509.Certificate) []byte {
var buffer bytes.Buffer
for _, cert := range certs {
pem.Encode(&buffer, &pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Raw,
})
}
return buffer.Bytes()
} | [
"func",
"EncodeCertificatesPEM",
"(",
"certs",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"[",
"]",
"byte",
"{",
"var",
"buffer",
"bytes",
".",
"Buffer",
"\n",
"for",
"_",
",",
"cert",
":=",
"range",
"certs",
"{",
"pem",
".",
"Encode",
"(",
"&",... | // EncodeCertificatesPEM encodes a number of x509 certificates to PEM | [
"EncodeCertificatesPEM",
"encodes",
"a",
"number",
"of",
"x509",
"certificates",
"to",
"PEM"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L201-L211 |
161,515 | cloudflare/cfssl | helpers/helpers.go | ParseSelfSignedCertificatePEM | func ParseSelfSignedCertificatePEM(certPEM []byte) (*x509.Certificate, error) {
cert, err := ParseCertificatePEM(certPEM)
if err != nil {
return nil, err
}
if err := cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature); err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.VerifyFailed, err)
}
return cert, nil
} | go | func ParseSelfSignedCertificatePEM(certPEM []byte) (*x509.Certificate, error) {
cert, err := ParseCertificatePEM(certPEM)
if err != nil {
return nil, err
}
if err := cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature); err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.VerifyFailed, err)
}
return cert, nil
} | [
"func",
"ParseSelfSignedCertificatePEM",
"(",
"certPEM",
"[",
"]",
"byte",
")",
"(",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"cert",
",",
"err",
":=",
"ParseCertificatePEM",
"(",
"certPEM",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"retu... | // ParseSelfSignedCertificatePEM parses a PEM-encoded certificate and check if it is self-signed. | [
"ParseSelfSignedCertificatePEM",
"parses",
"a",
"PEM",
"-",
"encoded",
"certificate",
"and",
"check",
"if",
"it",
"is",
"self",
"-",
"signed",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L272-L282 |
161,516 | cloudflare/cfssl | helpers/helpers.go | LoadPEMCertPool | func LoadPEMCertPool(certsFile string) (*x509.CertPool, error) {
if certsFile == "" {
return nil, nil
}
pemCerts, err := ioutil.ReadFile(certsFile)
if err != nil {
return nil, err
}
return PEMToCertPool(pemCerts)
} | go | func LoadPEMCertPool(certsFile string) (*x509.CertPool, error) {
if certsFile == "" {
return nil, nil
}
pemCerts, err := ioutil.ReadFile(certsFile)
if err != nil {
return nil, err
}
return PEMToCertPool(pemCerts)
} | [
"func",
"LoadPEMCertPool",
"(",
"certsFile",
"string",
")",
"(",
"*",
"x509",
".",
"CertPool",
",",
"error",
")",
"{",
"if",
"certsFile",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"pemCerts",
",",
"err",
":=",
"ioutil",
"."... | // LoadPEMCertPool loads a pool of PEM certificates from file. | [
"LoadPEMCertPool",
"loads",
"a",
"pool",
"of",
"PEM",
"certificates",
"from",
"file",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L334-L344 |
161,517 | cloudflare/cfssl | helpers/helpers.go | PEMToCertPool | func PEMToCertPool(pemCerts []byte) (*x509.CertPool, error) {
if len(pemCerts) == 0 {
return nil, nil
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(pemCerts) {
return nil, errors.New("failed to load cert pool")
}
return certPool, nil
} | go | func PEMToCertPool(pemCerts []byte) (*x509.CertPool, error) {
if len(pemCerts) == 0 {
return nil, nil
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(pemCerts) {
return nil, errors.New("failed to load cert pool")
}
return certPool, nil
} | [
"func",
"PEMToCertPool",
"(",
"pemCerts",
"[",
"]",
"byte",
")",
"(",
"*",
"x509",
".",
"CertPool",
",",
"error",
")",
"{",
"if",
"len",
"(",
"pemCerts",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"certPool",
":=",
"x509",... | // PEMToCertPool concerts PEM certificates to a CertPool. | [
"PEMToCertPool",
"concerts",
"PEM",
"certificates",
"to",
"a",
"CertPool",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L347-L358 |
161,518 | cloudflare/cfssl | helpers/helpers.go | GetKeyDERFromPEM | func GetKeyDERFromPEM(in []byte, password []byte) ([]byte, error) {
keyDER, _ := pem.Decode(in)
if keyDER != nil {
if procType, ok := keyDER.Headers["Proc-Type"]; ok {
if strings.Contains(procType, "ENCRYPTED") {
if password != nil {
return x509.DecryptPEMBlock(keyDER, password)
}
return nil, cferr.New(cferr.PrivateKeyError, cferr.Encrypted)
}
}
return keyDER.Bytes, nil
}
return nil, cferr.New(cferr.PrivateKeyError, cferr.DecodeFailed)
} | go | func GetKeyDERFromPEM(in []byte, password []byte) ([]byte, error) {
keyDER, _ := pem.Decode(in)
if keyDER != nil {
if procType, ok := keyDER.Headers["Proc-Type"]; ok {
if strings.Contains(procType, "ENCRYPTED") {
if password != nil {
return x509.DecryptPEMBlock(keyDER, password)
}
return nil, cferr.New(cferr.PrivateKeyError, cferr.Encrypted)
}
}
return keyDER.Bytes, nil
}
return nil, cferr.New(cferr.PrivateKeyError, cferr.DecodeFailed)
} | [
"func",
"GetKeyDERFromPEM",
"(",
"in",
"[",
"]",
"byte",
",",
"password",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"keyDER",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"in",
")",
"\n",
"if",
"keyDER",
"!=",
"nil",
"... | // GetKeyDERFromPEM parses a PEM-encoded private key and returns DER-format key bytes. | [
"GetKeyDERFromPEM",
"parses",
"a",
"PEM",
"-",
"encoded",
"private",
"key",
"and",
"returns",
"DER",
"-",
"format",
"key",
"bytes",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L380-L395 |
161,519 | cloudflare/cfssl | helpers/helpers.go | ParseCSRPEM | func ParseCSRPEM(csrPEM []byte) (*x509.CertificateRequest, error) {
block, _ := pem.Decode([]byte(csrPEM))
if block == nil {
return nil, cferr.New(cferr.CSRError, cferr.DecodeFailed)
}
csrObject, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return nil, err
}
return csrObject, nil
} | go | func ParseCSRPEM(csrPEM []byte) (*x509.CertificateRequest, error) {
block, _ := pem.Decode([]byte(csrPEM))
if block == nil {
return nil, cferr.New(cferr.CSRError, cferr.DecodeFailed)
}
csrObject, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return nil, err
}
return csrObject, nil
} | [
"func",
"ParseCSRPEM",
"(",
"csrPEM",
"[",
"]",
"byte",
")",
"(",
"*",
"x509",
".",
"CertificateRequest",
",",
"error",
")",
"{",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"[",
"]",
"byte",
"(",
"csrPEM",
")",
")",
"\n",
"if",
"block",
... | // ParseCSRPEM parses a PEM-encoded certificate signing request.
// It does not check the signature. This is useful for dumping data from a CSR
// locally. | [
"ParseCSRPEM",
"parses",
"a",
"PEM",
"-",
"encoded",
"certificate",
"signing",
"request",
".",
"It",
"does",
"not",
"check",
"the",
"signature",
".",
"This",
"is",
"useful",
"for",
"dumping",
"data",
"from",
"a",
"CSR",
"locally",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L426-L438 |
161,520 | cloudflare/cfssl | helpers/helpers.go | CreateTLSConfig | func CreateTLSConfig(remoteCAs *x509.CertPool, cert *tls.Certificate) *tls.Config {
var certs []tls.Certificate
if cert != nil {
certs = []tls.Certificate{*cert}
}
return &tls.Config{
Certificates: certs,
RootCAs: remoteCAs,
}
} | go | func CreateTLSConfig(remoteCAs *x509.CertPool, cert *tls.Certificate) *tls.Config {
var certs []tls.Certificate
if cert != nil {
certs = []tls.Certificate{*cert}
}
return &tls.Config{
Certificates: certs,
RootCAs: remoteCAs,
}
} | [
"func",
"CreateTLSConfig",
"(",
"remoteCAs",
"*",
"x509",
".",
"CertPool",
",",
"cert",
"*",
"tls",
".",
"Certificate",
")",
"*",
"tls",
".",
"Config",
"{",
"var",
"certs",
"[",
"]",
"tls",
".",
"Certificate",
"\n",
"if",
"cert",
"!=",
"nil",
"{",
"c... | // CreateTLSConfig creates a tls.Config object from certs and roots | [
"CreateTLSConfig",
"creates",
"a",
"tls",
".",
"Config",
"object",
"from",
"certs",
"and",
"roots"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L486-L495 |
161,521 | cloudflare/cfssl | helpers/helpers.go | SerializeSCTList | func SerializeSCTList(sctList []ct.SignedCertificateTimestamp) ([]byte, error) {
list := ctx509.SignedCertificateTimestampList{}
for _, sct := range sctList {
sctBytes, err := cttls.Marshal(sct)
if err != nil {
return nil, err
}
list.SCTList = append(list.SCTList, ctx509.SerializedSCT{Val: sctBytes})
}
return cttls.Marshal(list)
} | go | func SerializeSCTList(sctList []ct.SignedCertificateTimestamp) ([]byte, error) {
list := ctx509.SignedCertificateTimestampList{}
for _, sct := range sctList {
sctBytes, err := cttls.Marshal(sct)
if err != nil {
return nil, err
}
list.SCTList = append(list.SCTList, ctx509.SerializedSCT{Val: sctBytes})
}
return cttls.Marshal(list)
} | [
"func",
"SerializeSCTList",
"(",
"sctList",
"[",
"]",
"ct",
".",
"SignedCertificateTimestamp",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"list",
":=",
"ctx509",
".",
"SignedCertificateTimestampList",
"{",
"}",
"\n",
"for",
"_",
",",
"sct",
":=",
... | // SerializeSCTList serializes a list of SCTs. | [
"SerializeSCTList",
"serializes",
"a",
"list",
"of",
"SCTs",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L498-L508 |
161,522 | cloudflare/cfssl | helpers/helpers.go | DeserializeSCTList | func DeserializeSCTList(serializedSCTList []byte) ([]ct.SignedCertificateTimestamp, error) {
var sctList ctx509.SignedCertificateTimestampList
rest, err := cttls.Unmarshal(serializedSCTList, &sctList)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, errors.New("serialized SCT list contained trailing garbage"))
}
list := make([]ct.SignedCertificateTimestamp, len(sctList.SCTList))
for i, serializedSCT := range sctList.SCTList {
var sct ct.SignedCertificateTimestamp
rest, err := cttls.Unmarshal(serializedSCT.Val, &sct)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, errors.New("serialized SCT contained trailing garbage"))
}
list[i] = sct
}
return list, nil
} | go | func DeserializeSCTList(serializedSCTList []byte) ([]ct.SignedCertificateTimestamp, error) {
var sctList ctx509.SignedCertificateTimestampList
rest, err := cttls.Unmarshal(serializedSCTList, &sctList)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, errors.New("serialized SCT list contained trailing garbage"))
}
list := make([]ct.SignedCertificateTimestamp, len(sctList.SCTList))
for i, serializedSCT := range sctList.SCTList {
var sct ct.SignedCertificateTimestamp
rest, err := cttls.Unmarshal(serializedSCT.Val, &sct)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, errors.New("serialized SCT contained trailing garbage"))
}
list[i] = sct
}
return list, nil
} | [
"func",
"DeserializeSCTList",
"(",
"serializedSCTList",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"ct",
".",
"SignedCertificateTimestamp",
",",
"error",
")",
"{",
"var",
"sctList",
"ctx509",
".",
"SignedCertificateTimestampList",
"\n",
"rest",
",",
"err",
":=",
"c... | // DeserializeSCTList deserializes a list of SCTs. | [
"DeserializeSCTList",
"deserializes",
"a",
"list",
"of",
"SCTs",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L511-L533 |
161,523 | cloudflare/cfssl | helpers/helpers.go | SCTListFromOCSPResponse | func SCTListFromOCSPResponse(response *ocsp.Response) ([]ct.SignedCertificateTimestamp, error) {
// This loop finds the SCTListExtension in the OCSP response.
var SCTListExtension, ext pkix.Extension
for _, ext = range response.Extensions {
// sctExtOid is the ObjectIdentifier of a Signed Certificate Timestamp.
sctExtOid := asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 5}
if ext.Id.Equal(sctExtOid) {
SCTListExtension = ext
break
}
}
// This code block extracts the sctList from the SCT extension.
var sctList []ct.SignedCertificateTimestamp
var err error
if numBytes := len(SCTListExtension.Value); numBytes != 0 {
var serializedSCTList []byte
rest := make([]byte, numBytes)
copy(rest, SCTListExtension.Value)
for len(rest) != 0 {
rest, err = asn1.Unmarshal(rest, &serializedSCTList)
if err != nil {
return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err)
}
}
sctList, err = DeserializeSCTList(serializedSCTList)
}
return sctList, err
} | go | func SCTListFromOCSPResponse(response *ocsp.Response) ([]ct.SignedCertificateTimestamp, error) {
// This loop finds the SCTListExtension in the OCSP response.
var SCTListExtension, ext pkix.Extension
for _, ext = range response.Extensions {
// sctExtOid is the ObjectIdentifier of a Signed Certificate Timestamp.
sctExtOid := asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 5}
if ext.Id.Equal(sctExtOid) {
SCTListExtension = ext
break
}
}
// This code block extracts the sctList from the SCT extension.
var sctList []ct.SignedCertificateTimestamp
var err error
if numBytes := len(SCTListExtension.Value); numBytes != 0 {
var serializedSCTList []byte
rest := make([]byte, numBytes)
copy(rest, SCTListExtension.Value)
for len(rest) != 0 {
rest, err = asn1.Unmarshal(rest, &serializedSCTList)
if err != nil {
return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err)
}
}
sctList, err = DeserializeSCTList(serializedSCTList)
}
return sctList, err
} | [
"func",
"SCTListFromOCSPResponse",
"(",
"response",
"*",
"ocsp",
".",
"Response",
")",
"(",
"[",
"]",
"ct",
".",
"SignedCertificateTimestamp",
",",
"error",
")",
"{",
"// This loop finds the SCTListExtension in the OCSP response.",
"var",
"SCTListExtension",
",",
"ext",... | // SCTListFromOCSPResponse extracts the SCTList from an ocsp.Response,
// returning an empty list if the SCT extension was not found or could not be
// unmarshalled. | [
"SCTListFromOCSPResponse",
"extracts",
"the",
"SCTList",
"from",
"an",
"ocsp",
".",
"Response",
"returning",
"an",
"empty",
"list",
"if",
"the",
"SCT",
"extension",
"was",
"not",
"found",
"or",
"could",
"not",
"be",
"unmarshalled",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/helpers/helpers.go#L538-L566 |
161,524 | cloudflare/cfssl | cmd/cfssl/cfssl.go | main | func main() {
// Add command names to cfssl usage
flag.Usage = nil // this is set to nil for testabilty
// Register commands.
cmds := map[string]*cli.Command{
"bundle": bundle.Command,
"certinfo": certinfo.Command,
"crl": crl.Command,
"sign": sign.Command,
"serve": serve.Command,
"version": version.Command,
"genkey": genkey.Command,
"gencert": gencert.Command,
"gencsr": gencsr.Command,
"gencrl": gencrl.Command,
"ocspdump": ocspdump.Command,
"ocsprefresh": ocsprefresh.Command,
"ocspsign": ocspsign.Command,
"ocspserve": ocspserve.Command,
"selfsign": selfsign.Command,
"scan": scan.Command,
"info": info.Command,
"print-defaults": printdefaults.Command,
"revoke": revoke.Command,
}
// If the CLI returns an error, exit with an appropriate status
// code.
err := cli.Start(cmds)
if err != nil {
os.Exit(1)
}
} | go | func main() {
// Add command names to cfssl usage
flag.Usage = nil // this is set to nil for testabilty
// Register commands.
cmds := map[string]*cli.Command{
"bundle": bundle.Command,
"certinfo": certinfo.Command,
"crl": crl.Command,
"sign": sign.Command,
"serve": serve.Command,
"version": version.Command,
"genkey": genkey.Command,
"gencert": gencert.Command,
"gencsr": gencsr.Command,
"gencrl": gencrl.Command,
"ocspdump": ocspdump.Command,
"ocsprefresh": ocsprefresh.Command,
"ocspsign": ocspsign.Command,
"ocspserve": ocspserve.Command,
"selfsign": selfsign.Command,
"scan": scan.Command,
"info": info.Command,
"print-defaults": printdefaults.Command,
"revoke": revoke.Command,
}
// If the CLI returns an error, exit with an appropriate status
// code.
err := cli.Start(cmds)
if err != nil {
os.Exit(1)
}
} | [
"func",
"main",
"(",
")",
"{",
"// Add command names to cfssl usage",
"flag",
".",
"Usage",
"=",
"nil",
"// this is set to nil for testabilty",
"\n",
"// Register commands.",
"cmds",
":=",
"map",
"[",
"string",
"]",
"*",
"cli",
".",
"Command",
"{",
"\"",
"\"",
"... | // main defines the cfssl usage and registers all defined commands and flags. | [
"main",
"defines",
"the",
"cfssl",
"usage",
"and",
"registers",
"all",
"defined",
"commands",
"and",
"flags",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cmd/cfssl/cfssl.go#L55-L87 |
161,525 | cloudflare/cfssl | api/gencrl/gencrl.go | gencrlHandler | func gencrlHandler(w http.ResponseWriter, r *http.Request) error {
var revokedCerts []pkix.RevokedCertificate
var oneWeek = time.Duration(604800) * time.Second
var newExpiryTime = time.Now()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
r.Body.Close()
req := &jsonCRLRequest{}
err = json.Unmarshal(body, req)
if err != nil {
log.Error(err)
}
if req.ExpiryTime != "" {
expiryTime := strings.TrimSpace(req.ExpiryTime)
expiryInt, err := strconv.ParseInt(expiryTime, 0, 32)
if err != nil {
return err
}
newExpiryTime = time.Now().Add((time.Duration(expiryInt) * time.Second))
}
if req.ExpiryTime == "" {
newExpiryTime = time.Now().Add(oneWeek)
}
if err != nil {
return err
}
cert, err := helpers.ParseCertificatePEM([]byte(req.Certificate))
if err != nil {
log.Error("error from ParseCertificatePEM", err)
return errors.NewBadRequestString("malformed certificate")
}
for _, value := range req.SerialNumber {
tempBigInt := new(big.Int)
tempBigInt.SetString(value, 10)
tempCert := pkix.RevokedCertificate{
SerialNumber: tempBigInt,
RevocationTime: time.Now(),
}
revokedCerts = append(revokedCerts, tempCert)
}
key, err := helpers.ParsePrivateKeyPEM([]byte(req.PrivateKey))
if err != nil {
log.Debug("malformed private key %v", err)
return errors.NewBadRequestString("malformed Private Key")
}
result, err := cert.CreateCRL(rand.Reader, key, revokedCerts, time.Now(), newExpiryTime)
if err != nil {
log.Debug("unable to create CRL: %v", err)
return err
}
return api.SendResponse(w, result)
} | go | func gencrlHandler(w http.ResponseWriter, r *http.Request) error {
var revokedCerts []pkix.RevokedCertificate
var oneWeek = time.Duration(604800) * time.Second
var newExpiryTime = time.Now()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
r.Body.Close()
req := &jsonCRLRequest{}
err = json.Unmarshal(body, req)
if err != nil {
log.Error(err)
}
if req.ExpiryTime != "" {
expiryTime := strings.TrimSpace(req.ExpiryTime)
expiryInt, err := strconv.ParseInt(expiryTime, 0, 32)
if err != nil {
return err
}
newExpiryTime = time.Now().Add((time.Duration(expiryInt) * time.Second))
}
if req.ExpiryTime == "" {
newExpiryTime = time.Now().Add(oneWeek)
}
if err != nil {
return err
}
cert, err := helpers.ParseCertificatePEM([]byte(req.Certificate))
if err != nil {
log.Error("error from ParseCertificatePEM", err)
return errors.NewBadRequestString("malformed certificate")
}
for _, value := range req.SerialNumber {
tempBigInt := new(big.Int)
tempBigInt.SetString(value, 10)
tempCert := pkix.RevokedCertificate{
SerialNumber: tempBigInt,
RevocationTime: time.Now(),
}
revokedCerts = append(revokedCerts, tempCert)
}
key, err := helpers.ParsePrivateKeyPEM([]byte(req.PrivateKey))
if err != nil {
log.Debug("malformed private key %v", err)
return errors.NewBadRequestString("malformed Private Key")
}
result, err := cert.CreateCRL(rand.Reader, key, revokedCerts, time.Now(), newExpiryTime)
if err != nil {
log.Debug("unable to create CRL: %v", err)
return err
}
return api.SendResponse(w, result)
} | [
"func",
"gencrlHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"var",
"revokedCerts",
"[",
"]",
"pkix",
".",
"RevokedCertificate",
"\n",
"var",
"oneWeek",
"=",
"time",
".",
"Duration",
"(",
"60... | // Handle responds to requests for crl generation. It creates this crl
// based off of the given certificate, serial numbers, and private key | [
"Handle",
"responds",
"to",
"requests",
"for",
"crl",
"generation",
".",
"It",
"creates",
"this",
"crl",
"based",
"off",
"of",
"the",
"given",
"certificate",
"serial",
"numbers",
"and",
"private",
"key"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/gencrl/gencrl.go#L30-L94 |
161,526 | cloudflare/cfssl | api/gencrl/gencrl.go | NewHandler | func NewHandler() http.Handler {
return api.HTTPHandler{
Handler: api.HandlerFunc(gencrlHandler),
Methods: []string{"POST"},
}
} | go | func NewHandler() http.Handler {
return api.HTTPHandler{
Handler: api.HandlerFunc(gencrlHandler),
Methods: []string{"POST"},
}
} | [
"func",
"NewHandler",
"(",
")",
"http",
".",
"Handler",
"{",
"return",
"api",
".",
"HTTPHandler",
"{",
"Handler",
":",
"api",
".",
"HandlerFunc",
"(",
"gencrlHandler",
")",
",",
"Methods",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"}",
"\n"... | // NewHandler returns a new http.Handler that handles a crl generation request. | [
"NewHandler",
"returns",
"a",
"new",
"http",
".",
"Handler",
"that",
"handles",
"a",
"crl",
"generation",
"request",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/gencrl/gencrl.go#L97-L102 |
161,527 | cloudflare/cfssl | api/client/group.go | StrategyFromString | func StrategyFromString(s string) Strategy {
s = strings.TrimSpace(strings.ToLower(s))
strategy, ok := strategyStrings[s]
if !ok {
return StrategyInvalid
}
return strategy
} | go | func StrategyFromString(s string) Strategy {
s = strings.TrimSpace(strings.ToLower(s))
strategy, ok := strategyStrings[s]
if !ok {
return StrategyInvalid
}
return strategy
} | [
"func",
"StrategyFromString",
"(",
"s",
"string",
")",
"Strategy",
"{",
"s",
"=",
"strings",
".",
"TrimSpace",
"(",
"strings",
".",
"ToLower",
"(",
"s",
")",
")",
"\n",
"strategy",
",",
"ok",
":=",
"strategyStrings",
"[",
"s",
"]",
"\n",
"if",
"!",
"... | // StrategyFromString takes a string describing a | [
"StrategyFromString",
"takes",
"a",
"string",
"describing",
"a"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/client/group.go#L36-L43 |
161,528 | cloudflare/cfssl | api/client/group.go | NewGroup | func NewGroup(remotes []string, tlsConfig *tls.Config, strategy Strategy) (Remote, error) {
var servers = make([]*server, len(remotes))
for i := range remotes {
u, err := normalizeURL(remotes[i])
if err != nil {
return nil, err
}
servers[i] = newServer(u, tlsConfig)
}
switch strategy {
case StrategyOrderedList:
return newOrdererdListGroup(servers)
default:
return nil, errors.New("unrecognised strategy")
}
} | go | func NewGroup(remotes []string, tlsConfig *tls.Config, strategy Strategy) (Remote, error) {
var servers = make([]*server, len(remotes))
for i := range remotes {
u, err := normalizeURL(remotes[i])
if err != nil {
return nil, err
}
servers[i] = newServer(u, tlsConfig)
}
switch strategy {
case StrategyOrderedList:
return newOrdererdListGroup(servers)
default:
return nil, errors.New("unrecognised strategy")
}
} | [
"func",
"NewGroup",
"(",
"remotes",
"[",
"]",
"string",
",",
"tlsConfig",
"*",
"tls",
".",
"Config",
",",
"strategy",
"Strategy",
")",
"(",
"Remote",
",",
"error",
")",
"{",
"var",
"servers",
"=",
"make",
"(",
"[",
"]",
"*",
"server",
",",
"len",
"... | // NewGroup will use the collection of remotes specified with the
// given strategy. | [
"NewGroup",
"will",
"use",
"the",
"collection",
"of",
"remotes",
"specified",
"with",
"the",
"given",
"strategy",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/client/group.go#L47-L63 |
161,529 | cloudflare/cfssl | auth/auth.go | New | func New(key string, ad []byte) (*Standard, error) {
if splitKey := strings.SplitN(key, ":", 2); len(splitKey) == 2 {
switch splitKey[0] {
case "env":
key = os.Getenv(splitKey[1])
case "file":
data, err := ioutil.ReadFile(splitKey[1])
if err != nil {
return nil, err
}
key = strings.TrimSpace(string(data))
default:
return nil, fmt.Errorf("unknown key prefix: %s", splitKey[0])
}
}
keyBytes, err := hex.DecodeString(key)
if err != nil {
return nil, err
}
return &Standard{keyBytes, ad}, nil
} | go | func New(key string, ad []byte) (*Standard, error) {
if splitKey := strings.SplitN(key, ":", 2); len(splitKey) == 2 {
switch splitKey[0] {
case "env":
key = os.Getenv(splitKey[1])
case "file":
data, err := ioutil.ReadFile(splitKey[1])
if err != nil {
return nil, err
}
key = strings.TrimSpace(string(data))
default:
return nil, fmt.Errorf("unknown key prefix: %s", splitKey[0])
}
}
keyBytes, err := hex.DecodeString(key)
if err != nil {
return nil, err
}
return &Standard{keyBytes, ad}, nil
} | [
"func",
"New",
"(",
"key",
"string",
",",
"ad",
"[",
"]",
"byte",
")",
"(",
"*",
"Standard",
",",
"error",
")",
"{",
"if",
"splitKey",
":=",
"strings",
".",
"SplitN",
"(",
"key",
",",
"\"",
"\"",
",",
"2",
")",
";",
"len",
"(",
"splitKey",
")",... | // New generates a new standard authentication provider from the key
// and additional data. The additional data will be used when
// generating a new token. | [
"New",
"generates",
"a",
"new",
"standard",
"authentication",
"provider",
"from",
"the",
"key",
"and",
"additional",
"data",
".",
"The",
"additional",
"data",
"will",
"be",
"used",
"when",
"generating",
"a",
"new",
"token",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/auth/auth.go#L49-L71 |
161,530 | cloudflare/cfssl | auth/auth.go | Token | func (p Standard) Token(req []byte) (token []byte, err error) {
h := hmac.New(sha256.New, p.key)
h.Write(req)
h.Write(p.ad)
return h.Sum(nil), nil
} | go | func (p Standard) Token(req []byte) (token []byte, err error) {
h := hmac.New(sha256.New, p.key)
h.Write(req)
h.Write(p.ad)
return h.Sum(nil), nil
} | [
"func",
"(",
"p",
"Standard",
")",
"Token",
"(",
"req",
"[",
"]",
"byte",
")",
"(",
"token",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"h",
":=",
"hmac",
".",
"New",
"(",
"sha256",
".",
"New",
",",
"p",
".",
"key",
")",
"\n",
"h",
".... | // Token generates a new authentication token from the request. | [
"Token",
"generates",
"a",
"new",
"authentication",
"token",
"from",
"the",
"request",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/auth/auth.go#L74-L79 |
161,531 | cloudflare/cfssl | auth/auth.go | Verify | func (p Standard) Verify(ad *AuthenticatedRequest) bool {
if ad == nil {
return false
}
// Standard token generation returns no error.
token, _ := p.Token(ad.Request)
if len(ad.Token) != len(token) {
return false
}
return hmac.Equal(token, ad.Token)
} | go | func (p Standard) Verify(ad *AuthenticatedRequest) bool {
if ad == nil {
return false
}
// Standard token generation returns no error.
token, _ := p.Token(ad.Request)
if len(ad.Token) != len(token) {
return false
}
return hmac.Equal(token, ad.Token)
} | [
"func",
"(",
"p",
"Standard",
")",
"Verify",
"(",
"ad",
"*",
"AuthenticatedRequest",
")",
"bool",
"{",
"if",
"ad",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Standard token generation returns no error.",
"token",
",",
"_",
":=",
"p",
".",
... | // Verify determines whether an authenticated request is valid. | [
"Verify",
"determines",
"whether",
"an",
"authenticated",
"request",
"is",
"valid",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/auth/auth.go#L82-L94 |
161,532 | cloudflare/cfssl | api/scan/scan.go | NewHandler | func NewHandler(caBundleFile string) (http.Handler, error) {
return api.HTTPHandler{
Handler: api.HandlerFunc(scanHandler),
Methods: []string{"GET"},
}, scan.LoadRootCAs(caBundleFile)
} | go | func NewHandler(caBundleFile string) (http.Handler, error) {
return api.HTTPHandler{
Handler: api.HandlerFunc(scanHandler),
Methods: []string{"GET"},
}, scan.LoadRootCAs(caBundleFile)
} | [
"func",
"NewHandler",
"(",
"caBundleFile",
"string",
")",
"(",
"http",
".",
"Handler",
",",
"error",
")",
"{",
"return",
"api",
".",
"HTTPHandler",
"{",
"Handler",
":",
"api",
".",
"HandlerFunc",
"(",
"scanHandler",
")",
",",
"Methods",
":",
"[",
"]",
... | // NewHandler returns a new http.Handler that handles a scan request. | [
"NewHandler",
"returns",
"a",
"new",
"http",
".",
"Handler",
"that",
"handles",
"a",
"scan",
"request",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/scan/scan.go#L54-L59 |
161,533 | cloudflare/cfssl | api/scan/scan.go | scanInfoHandler | func scanInfoHandler(w http.ResponseWriter, r *http.Request) error {
log.Info("setting up scaninfo handler")
response := api.NewSuccessResponse(scan.Default)
enc := json.NewEncoder(w)
return enc.Encode(response)
} | go | func scanInfoHandler(w http.ResponseWriter, r *http.Request) error {
log.Info("setting up scaninfo handler")
response := api.NewSuccessResponse(scan.Default)
enc := json.NewEncoder(w)
return enc.Encode(response)
} | [
"func",
"scanInfoHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"response",
":=",
"api",
".",
"NewSuccessResponse",
"(",
"scan",
".",
"Default... | // scanInfoHandler is an HTTP handler that returns a JSON blob result describing
// the possible families and scans to be run. | [
"scanInfoHandler",
"is",
"an",
"HTTP",
"handler",
"that",
"returns",
"a",
"JSON",
"blob",
"result",
"describing",
"the",
"possible",
"families",
"and",
"scans",
"to",
"be",
"run",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/scan/scan.go#L63-L68 |
161,534 | cloudflare/cfssl | api/scan/scan.go | NewInfoHandler | func NewInfoHandler() http.Handler {
return api.HTTPHandler{
Handler: api.HandlerFunc(scanInfoHandler),
Methods: []string{"GET"},
}
} | go | func NewInfoHandler() http.Handler {
return api.HTTPHandler{
Handler: api.HandlerFunc(scanInfoHandler),
Methods: []string{"GET"},
}
} | [
"func",
"NewInfoHandler",
"(",
")",
"http",
".",
"Handler",
"{",
"return",
"api",
".",
"HTTPHandler",
"{",
"Handler",
":",
"api",
".",
"HandlerFunc",
"(",
"scanInfoHandler",
")",
",",
"Methods",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"}",
... | // NewInfoHandler returns a new http.Handler that handles a request for scan info. | [
"NewInfoHandler",
"returns",
"a",
"new",
"http",
".",
"Handler",
"that",
"handles",
"a",
"request",
"for",
"scan",
"info",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/scan/scan.go#L71-L76 |
161,535 | cloudflare/cfssl | bundler/bundler.go | WithKeyUsages | func WithKeyUsages(usages ...x509.ExtKeyUsage) Option {
return func(o *options) {
o.keyUsages = usages
}
} | go | func WithKeyUsages(usages ...x509.ExtKeyUsage) Option {
return func(o *options) {
o.keyUsages = usages
}
} | [
"func",
"WithKeyUsages",
"(",
"usages",
"...",
"x509",
".",
"ExtKeyUsage",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"options",
")",
"{",
"o",
".",
"keyUsages",
"=",
"usages",
"\n",
"}",
"\n",
"}"
] | // WithKeyUsages lets you set which Extended Key Usage values are acceptable. By
// default x509.ExtKeyUsageAny will be used. | [
"WithKeyUsages",
"lets",
"you",
"set",
"which",
"Extended",
"Key",
"Usage",
"values",
"are",
"acceptable",
".",
"By",
"default",
"x509",
".",
"ExtKeyUsageAny",
"will",
"be",
"used",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L84-L88 |
161,536 | cloudflare/cfssl | bundler/bundler.go | NewBundler | func NewBundler(caBundleFile, intBundleFile string, opt ...Option) (*Bundler, error) {
var caBundle, intBundle []byte
var err error
if caBundleFile != "" {
log.Debug("Loading CA bundle: ", caBundleFile)
caBundle, err = ioutil.ReadFile(caBundleFile)
if err != nil {
log.Errorf("root bundle failed to load: %v", err)
return nil, errors.Wrap(errors.RootError, errors.ReadFailed, err)
}
}
if intBundleFile != "" {
log.Debug("Loading Intermediate bundle: ", intBundleFile)
intBundle, err = ioutil.ReadFile(intBundleFile)
if err != nil {
log.Errorf("intermediate bundle failed to load: %v", err)
return nil, errors.Wrap(errors.IntermediatesError, errors.ReadFailed, err)
}
}
if IntermediateStash != "" {
if _, err = os.Stat(IntermediateStash); err != nil && os.IsNotExist(err) {
log.Infof("intermediate stash directory %s doesn't exist, creating", IntermediateStash)
err = os.MkdirAll(IntermediateStash, 0755)
if err != nil {
log.Errorf("failed to create intermediate stash directory %s: %v",
IntermediateStash, err)
return nil, err
}
log.Infof("intermediate stash directory %s created", IntermediateStash)
}
}
return NewBundlerFromPEM(caBundle, intBundle, opt...)
} | go | func NewBundler(caBundleFile, intBundleFile string, opt ...Option) (*Bundler, error) {
var caBundle, intBundle []byte
var err error
if caBundleFile != "" {
log.Debug("Loading CA bundle: ", caBundleFile)
caBundle, err = ioutil.ReadFile(caBundleFile)
if err != nil {
log.Errorf("root bundle failed to load: %v", err)
return nil, errors.Wrap(errors.RootError, errors.ReadFailed, err)
}
}
if intBundleFile != "" {
log.Debug("Loading Intermediate bundle: ", intBundleFile)
intBundle, err = ioutil.ReadFile(intBundleFile)
if err != nil {
log.Errorf("intermediate bundle failed to load: %v", err)
return nil, errors.Wrap(errors.IntermediatesError, errors.ReadFailed, err)
}
}
if IntermediateStash != "" {
if _, err = os.Stat(IntermediateStash); err != nil && os.IsNotExist(err) {
log.Infof("intermediate stash directory %s doesn't exist, creating", IntermediateStash)
err = os.MkdirAll(IntermediateStash, 0755)
if err != nil {
log.Errorf("failed to create intermediate stash directory %s: %v",
IntermediateStash, err)
return nil, err
}
log.Infof("intermediate stash directory %s created", IntermediateStash)
}
}
return NewBundlerFromPEM(caBundle, intBundle, opt...)
} | [
"func",
"NewBundler",
"(",
"caBundleFile",
",",
"intBundleFile",
"string",
",",
"opt",
"...",
"Option",
")",
"(",
"*",
"Bundler",
",",
"error",
")",
"{",
"var",
"caBundle",
",",
"intBundle",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n\n",
"if",
... | // NewBundler creates a new Bundler from the files passed in; these
// files should contain a list of valid root certificates and a list
// of valid intermediate certificates, respectively. | [
"NewBundler",
"creates",
"a",
"new",
"Bundler",
"from",
"the",
"files",
"passed",
"in",
";",
"these",
"files",
"should",
"contain",
"a",
"list",
"of",
"valid",
"root",
"certificates",
"and",
"a",
"list",
"of",
"valid",
"intermediate",
"certificates",
"respecti... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L93-L130 |
161,537 | cloudflare/cfssl | bundler/bundler.go | NewBundlerFromPEM | func NewBundlerFromPEM(caBundlePEM, intBundlePEM []byte, opt ...Option) (*Bundler, error) {
opts := defaultOptions
for _, o := range opt {
o(&opts)
}
log.Debug("parsing root certificates from PEM")
roots, err := helpers.ParseCertificatesPEM(caBundlePEM)
if err != nil {
log.Errorf("failed to parse root bundle: %v", err)
return nil, errors.New(errors.RootError, errors.ParseFailed)
}
log.Debug("parse intermediate certificates from PEM")
intermediates, err := helpers.ParseCertificatesPEM(intBundlePEM)
if err != nil {
log.Errorf("failed to parse intermediate bundle: %v", err)
return nil, errors.New(errors.IntermediatesError, errors.ParseFailed)
}
b := &Bundler{
KnownIssuers: map[string]bool{},
IntermediatePool: x509.NewCertPool(),
opts: opts,
}
log.Debug("building certificate pools")
// RootPool will be nil if caBundlePEM is nil, also
// that translates to caBundleFile is "".
// Systems root store will be used.
if caBundlePEM != nil {
b.RootPool = x509.NewCertPool()
}
for _, c := range roots {
b.RootPool.AddCert(c)
b.KnownIssuers[string(c.Signature)] = true
}
for _, c := range intermediates {
b.IntermediatePool.AddCert(c)
b.KnownIssuers[string(c.Signature)] = true
}
log.Debug("bundler set up")
return b, nil
} | go | func NewBundlerFromPEM(caBundlePEM, intBundlePEM []byte, opt ...Option) (*Bundler, error) {
opts := defaultOptions
for _, o := range opt {
o(&opts)
}
log.Debug("parsing root certificates from PEM")
roots, err := helpers.ParseCertificatesPEM(caBundlePEM)
if err != nil {
log.Errorf("failed to parse root bundle: %v", err)
return nil, errors.New(errors.RootError, errors.ParseFailed)
}
log.Debug("parse intermediate certificates from PEM")
intermediates, err := helpers.ParseCertificatesPEM(intBundlePEM)
if err != nil {
log.Errorf("failed to parse intermediate bundle: %v", err)
return nil, errors.New(errors.IntermediatesError, errors.ParseFailed)
}
b := &Bundler{
KnownIssuers: map[string]bool{},
IntermediatePool: x509.NewCertPool(),
opts: opts,
}
log.Debug("building certificate pools")
// RootPool will be nil if caBundlePEM is nil, also
// that translates to caBundleFile is "".
// Systems root store will be used.
if caBundlePEM != nil {
b.RootPool = x509.NewCertPool()
}
for _, c := range roots {
b.RootPool.AddCert(c)
b.KnownIssuers[string(c.Signature)] = true
}
for _, c := range intermediates {
b.IntermediatePool.AddCert(c)
b.KnownIssuers[string(c.Signature)] = true
}
log.Debug("bundler set up")
return b, nil
} | [
"func",
"NewBundlerFromPEM",
"(",
"caBundlePEM",
",",
"intBundlePEM",
"[",
"]",
"byte",
",",
"opt",
"...",
"Option",
")",
"(",
"*",
"Bundler",
",",
"error",
")",
"{",
"opts",
":=",
"defaultOptions",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"opt",
"{"... | // NewBundlerFromPEM creates a new Bundler from PEM-encoded root certificates and
// intermediate certificates.
// If caBundlePEM is nil, the resulting Bundler can only do "Force" bundle. | [
"NewBundlerFromPEM",
"creates",
"a",
"new",
"Bundler",
"from",
"PEM",
"-",
"encoded",
"root",
"certificates",
"and",
"intermediate",
"certificates",
".",
"If",
"caBundlePEM",
"is",
"nil",
"the",
"resulting",
"Bundler",
"can",
"only",
"do",
"Force",
"bundle",
"."... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L135-L182 |
161,538 | cloudflare/cfssl | bundler/bundler.go | VerifyOptions | func (b *Bundler) VerifyOptions() x509.VerifyOptions {
return x509.VerifyOptions{
Roots: b.RootPool,
Intermediates: b.IntermediatePool,
KeyUsages: b.opts.keyUsages,
}
} | go | func (b *Bundler) VerifyOptions() x509.VerifyOptions {
return x509.VerifyOptions{
Roots: b.RootPool,
Intermediates: b.IntermediatePool,
KeyUsages: b.opts.keyUsages,
}
} | [
"func",
"(",
"b",
"*",
"Bundler",
")",
"VerifyOptions",
"(",
")",
"x509",
".",
"VerifyOptions",
"{",
"return",
"x509",
".",
"VerifyOptions",
"{",
"Roots",
":",
"b",
".",
"RootPool",
",",
"Intermediates",
":",
"b",
".",
"IntermediatePool",
",",
"KeyUsages",... | // VerifyOptions generates an x509 VerifyOptions structure that can be
// used for verifying certificates. | [
"VerifyOptions",
"generates",
"an",
"x509",
"VerifyOptions",
"structure",
"that",
"can",
"be",
"used",
"for",
"verifying",
"certificates",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L186-L192 |
161,539 | cloudflare/cfssl | bundler/bundler.go | fetchRemoteCertificate | func fetchRemoteCertificate(certURL string) (fi *fetchedIntermediate, err error) {
log.Debugf("fetching remote certificate: %s", certURL)
var resp *http.Response
resp, err = http.Get(certURL)
if err != nil {
log.Debugf("failed HTTP get: %v", err)
return
}
defer resp.Body.Close()
var certData []byte
certData, err = ioutil.ReadAll(resp.Body)
if err != nil {
log.Debugf("failed to read response body: %v", err)
return
}
log.Debugf("attempting to parse certificate as DER")
crt, err := x509.ParseCertificate(certData)
if err != nil {
log.Debugf("attempting to parse certificate as PEM")
crt, err = helpers.ParseCertificatePEM(certData)
if err != nil {
log.Debugf("failed to parse certificate: %v", err)
return
}
}
log.Debugf("certificate fetch succeeds")
fi = &fetchedIntermediate{Cert: crt, Name: constructCertFileName(crt)}
return
} | go | func fetchRemoteCertificate(certURL string) (fi *fetchedIntermediate, err error) {
log.Debugf("fetching remote certificate: %s", certURL)
var resp *http.Response
resp, err = http.Get(certURL)
if err != nil {
log.Debugf("failed HTTP get: %v", err)
return
}
defer resp.Body.Close()
var certData []byte
certData, err = ioutil.ReadAll(resp.Body)
if err != nil {
log.Debugf("failed to read response body: %v", err)
return
}
log.Debugf("attempting to parse certificate as DER")
crt, err := x509.ParseCertificate(certData)
if err != nil {
log.Debugf("attempting to parse certificate as PEM")
crt, err = helpers.ParseCertificatePEM(certData)
if err != nil {
log.Debugf("failed to parse certificate: %v", err)
return
}
}
log.Debugf("certificate fetch succeeds")
fi = &fetchedIntermediate{Cert: crt, Name: constructCertFileName(crt)}
return
} | [
"func",
"fetchRemoteCertificate",
"(",
"certURL",
"string",
")",
"(",
"fi",
"*",
"fetchedIntermediate",
",",
"err",
"error",
")",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"certURL",
")",
"\n",
"var",
"resp",
"*",
"http",
".",
"Response",
"\n",
... | // fetchRemoteCertificate retrieves a single URL pointing to a certificate
// and attempts to first parse it as a DER-encoded certificate; if
// this fails, it attempts to decode it as a PEM-encoded certificate. | [
"fetchRemoteCertificate",
"retrieves",
"a",
"single",
"URL",
"pointing",
"to",
"a",
"certificate",
"and",
"attempts",
"to",
"first",
"parse",
"it",
"as",
"a",
"DER",
"-",
"encoded",
"certificate",
";",
"if",
"this",
"fails",
"it",
"attempts",
"to",
"decode",
... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L333-L364 |
161,540 | cloudflare/cfssl | bundler/bundler.go | constructCertFileName | func constructCertFileName(cert *x509.Certificate) string {
// construct the filename as the CN with no period and space
name := strings.Replace(cert.Subject.CommonName, ".", "", -1)
name = strings.Replace(name, " ", "", -1)
// add SKI and serial number as extra identifier
name += fmt.Sprintf("_%x", cert.SubjectKeyId)
name += fmt.Sprintf("_%x", cert.SerialNumber.Bytes())
name += ".crt"
return name
} | go | func constructCertFileName(cert *x509.Certificate) string {
// construct the filename as the CN with no period and space
name := strings.Replace(cert.Subject.CommonName, ".", "", -1)
name = strings.Replace(name, " ", "", -1)
// add SKI and serial number as extra identifier
name += fmt.Sprintf("_%x", cert.SubjectKeyId)
name += fmt.Sprintf("_%x", cert.SerialNumber.Bytes())
name += ".crt"
return name
} | [
"func",
"constructCertFileName",
"(",
"cert",
"*",
"x509",
".",
"Certificate",
")",
"string",
"{",
"// construct the filename as the CN with no period and space",
"name",
":=",
"strings",
".",
"Replace",
"(",
"cert",
".",
"Subject",
".",
"CommonName",
",",
"\"",
"\"... | // constructCertFileName returns a uniquely identifying file name for a certificate | [
"constructCertFileName",
"returns",
"a",
"uniquely",
"identifying",
"file",
"name",
"for",
"a",
"certificate"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L454-L465 |
161,541 | cloudflare/cfssl | bundler/bundler.go | fetchIntermediates | func (b *Bundler) fetchIntermediates(certs []*x509.Certificate) (err error) {
if IntermediateStash != "" {
log.Debugf("searching intermediates")
if _, err := os.Stat(IntermediateStash); err != nil && os.IsNotExist(err) {
log.Infof("intermediate stash directory %s doesn't exist, creating", IntermediateStash)
err = os.MkdirAll(IntermediateStash, 0755)
if err != nil {
log.Errorf("failed to create intermediate stash directory %s: %v", IntermediateStash, err)
return err
}
log.Infof("intermediate stash directory %s created", IntermediateStash)
}
}
// stores URLs and certificate signatures that have been seen
seen := map[string]bool{}
var foundChains int
// Construct a verify chain as a reversed partial bundle,
// such that the certs are ordered by promxity to the root CAs.
var chain []*fetchedIntermediate
for i, cert := range certs {
var name string
// Only construct filenames for non-leaf intermediate certs
// so they will be saved to disk if necessary.
// Leaf cert gets a empty name and will be skipped.
if i > 0 {
name = constructCertFileName(cert)
}
chain = append([]*fetchedIntermediate{{cert, name}}, chain...)
seen[string(cert.Signature)] = true
}
// Verify the chain and store valid intermediates in the chain.
// If it doesn't verify, fetch the intermediates and extend the chain
// in a DFS manner and verify each time we hit a root.
for {
if len(chain) == 0 {
log.Debugf("search complete")
if foundChains == 0 {
return x509.UnknownAuthorityError{}
}
return nil
}
current := chain[0]
var advanced bool
if b.verifyChain(chain) {
foundChains++
}
log.Debugf("walk AIA issuers")
for _, url := range current.Cert.IssuingCertificateURL {
if seen[url] {
log.Debugf("url %s has been seen", url)
continue
}
crt, err := fetchRemoteCertificate(url)
if err != nil {
continue
} else if seen[string(crt.Cert.Signature)] {
log.Debugf("fetched certificate is known")
continue
}
seen[url] = true
seen[string(crt.Cert.Signature)] = true
chain = append([]*fetchedIntermediate{crt}, chain...)
advanced = true
break
}
if !advanced {
log.Debugf("didn't advance, stepping back")
chain = chain[1:]
}
}
} | go | func (b *Bundler) fetchIntermediates(certs []*x509.Certificate) (err error) {
if IntermediateStash != "" {
log.Debugf("searching intermediates")
if _, err := os.Stat(IntermediateStash); err != nil && os.IsNotExist(err) {
log.Infof("intermediate stash directory %s doesn't exist, creating", IntermediateStash)
err = os.MkdirAll(IntermediateStash, 0755)
if err != nil {
log.Errorf("failed to create intermediate stash directory %s: %v", IntermediateStash, err)
return err
}
log.Infof("intermediate stash directory %s created", IntermediateStash)
}
}
// stores URLs and certificate signatures that have been seen
seen := map[string]bool{}
var foundChains int
// Construct a verify chain as a reversed partial bundle,
// such that the certs are ordered by promxity to the root CAs.
var chain []*fetchedIntermediate
for i, cert := range certs {
var name string
// Only construct filenames for non-leaf intermediate certs
// so they will be saved to disk if necessary.
// Leaf cert gets a empty name and will be skipped.
if i > 0 {
name = constructCertFileName(cert)
}
chain = append([]*fetchedIntermediate{{cert, name}}, chain...)
seen[string(cert.Signature)] = true
}
// Verify the chain and store valid intermediates in the chain.
// If it doesn't verify, fetch the intermediates and extend the chain
// in a DFS manner and verify each time we hit a root.
for {
if len(chain) == 0 {
log.Debugf("search complete")
if foundChains == 0 {
return x509.UnknownAuthorityError{}
}
return nil
}
current := chain[0]
var advanced bool
if b.verifyChain(chain) {
foundChains++
}
log.Debugf("walk AIA issuers")
for _, url := range current.Cert.IssuingCertificateURL {
if seen[url] {
log.Debugf("url %s has been seen", url)
continue
}
crt, err := fetchRemoteCertificate(url)
if err != nil {
continue
} else if seen[string(crt.Cert.Signature)] {
log.Debugf("fetched certificate is known")
continue
}
seen[url] = true
seen[string(crt.Cert.Signature)] = true
chain = append([]*fetchedIntermediate{crt}, chain...)
advanced = true
break
}
if !advanced {
log.Debugf("didn't advance, stepping back")
chain = chain[1:]
}
}
} | [
"func",
"(",
"b",
"*",
"Bundler",
")",
"fetchIntermediates",
"(",
"certs",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"(",
"err",
"error",
")",
"{",
"if",
"IntermediateStash",
"!=",
"\"",
"\"",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
")",
... | // fetchIntermediates goes through each of the URLs in the AIA "Issuing
// CA" extensions and fetches those certificates. If those
// certificates are not present in either the root pool or
// intermediate pool, the certificate is saved to file and added to
// the list of intermediates to be used for verification. This will
// not add any new certificates to the root pool; if the ultimate
// issuer is not trusted, fetching the certicate here will not change
// that. | [
"fetchIntermediates",
"goes",
"through",
"each",
"of",
"the",
"URLs",
"in",
"the",
"AIA",
"Issuing",
"CA",
"extensions",
"and",
"fetches",
"those",
"certificates",
".",
"If",
"those",
"certificates",
"are",
"not",
"present",
"in",
"either",
"the",
"root",
"poo... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L475-L551 |
161,542 | cloudflare/cfssl | bundler/bundler.go | checkExpiringCerts | func checkExpiringCerts(chain []*x509.Certificate) (expiringIntermediates []int) {
now := time.Now()
for i, cert := range chain {
if cert.NotAfter.Sub(now).Hours() < 720 {
expiringIntermediates = append(expiringIntermediates, i)
}
}
return
} | go | func checkExpiringCerts(chain []*x509.Certificate) (expiringIntermediates []int) {
now := time.Now()
for i, cert := range chain {
if cert.NotAfter.Sub(now).Hours() < 720 {
expiringIntermediates = append(expiringIntermediates, i)
}
}
return
} | [
"func",
"checkExpiringCerts",
"(",
"chain",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"(",
"expiringIntermediates",
"[",
"]",
"int",
")",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"for",
"i",
",",
"cert",
":=",
"range",
"chain",
"{"... | // checkExpiringCerts returns indices of certs that are expiring within 30 days. | [
"checkExpiringCerts",
"returns",
"indices",
"of",
"certs",
"that",
"are",
"expiring",
"within",
"30",
"days",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L736-L744 |
161,543 | cloudflare/cfssl | bundler/bundler.go | getSKIs | func getSKIs(chain []*x509.Certificate, indices []int) (skis []string) {
for _, index := range indices {
ski := fmt.Sprintf("%X", chain[index].SubjectKeyId)
skis = append(skis, ski)
}
return
} | go | func getSKIs(chain []*x509.Certificate, indices []int) (skis []string) {
for _, index := range indices {
ski := fmt.Sprintf("%X", chain[index].SubjectKeyId)
skis = append(skis, ski)
}
return
} | [
"func",
"getSKIs",
"(",
"chain",
"[",
"]",
"*",
"x509",
".",
"Certificate",
",",
"indices",
"[",
"]",
"int",
")",
"(",
"skis",
"[",
"]",
"string",
")",
"{",
"for",
"_",
",",
"index",
":=",
"range",
"indices",
"{",
"ski",
":=",
"fmt",
".",
"Sprint... | // getSKIs returns a list of cert subject key id in the bundle chain with matched indices. | [
"getSKIs",
"returns",
"a",
"list",
"of",
"cert",
"subject",
"key",
"id",
"in",
"the",
"bundle",
"chain",
"with",
"matched",
"indices",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L747-L753 |
161,544 | cloudflare/cfssl | bundler/bundler.go | expirationWarning | func expirationWarning(expiringIntermediates []int) (ret string) {
if len(expiringIntermediates) == 0 {
return
}
ret = expiringWarningStub
if len(expiringIntermediates) > 1 {
ret = ret + "The expiring certs are"
} else {
ret = ret + "The expiring cert is"
}
for _, index := range expiringIntermediates {
ret = ret + " #" + strconv.Itoa(index+1)
}
ret = ret + " in the chain."
return
} | go | func expirationWarning(expiringIntermediates []int) (ret string) {
if len(expiringIntermediates) == 0 {
return
}
ret = expiringWarningStub
if len(expiringIntermediates) > 1 {
ret = ret + "The expiring certs are"
} else {
ret = ret + "The expiring cert is"
}
for _, index := range expiringIntermediates {
ret = ret + " #" + strconv.Itoa(index+1)
}
ret = ret + " in the chain."
return
} | [
"func",
"expirationWarning",
"(",
"expiringIntermediates",
"[",
"]",
"int",
")",
"(",
"ret",
"string",
")",
"{",
"if",
"len",
"(",
"expiringIntermediates",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"ret",
"=",
"expiringWarningStub",
"\n",
"if",
"le... | // expirationWarning generates a warning message with expiring certs. | [
"expirationWarning",
"generates",
"a",
"warning",
"message",
"with",
"expiring",
"certs",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L756-L772 |
161,545 | cloudflare/cfssl | bundler/bundler.go | untrustedPlatformsWarning | func untrustedPlatformsWarning(platforms []string) string {
if len(ubiquity.Platforms) == 0 {
return ubiquityWarning
}
if len(platforms) == 0 {
return ""
}
msg := untrustedWarningStub
for i, platform := range platforms {
if i > 0 {
msg += ","
}
msg += " " + platform
}
msg += "."
return msg
} | go | func untrustedPlatformsWarning(platforms []string) string {
if len(ubiquity.Platforms) == 0 {
return ubiquityWarning
}
if len(platforms) == 0 {
return ""
}
msg := untrustedWarningStub
for i, platform := range platforms {
if i > 0 {
msg += ","
}
msg += " " + platform
}
msg += "."
return msg
} | [
"func",
"untrustedPlatformsWarning",
"(",
"platforms",
"[",
"]",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"ubiquity",
".",
"Platforms",
")",
"==",
"0",
"{",
"return",
"ubiquityWarning",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"platforms",
")",
"==",
... | // untrustedPlatformsWarning generates a warning message with untrusted platform names. | [
"untrustedPlatformsWarning",
"generates",
"a",
"warning",
"message",
"with",
"untrusted",
"platform",
"names",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L775-L793 |
161,546 | cloudflare/cfssl | bundler/bundler.go | optimalChains | func optimalChains(chains [][]*x509.Certificate) [][]*x509.Certificate {
// Find shortest chains
chains = ubiquity.Filter(chains, ubiquity.CompareChainLength)
// Find the chains with longest expiry.
chains = ubiquity.Filter(chains, ubiquity.CompareChainExpiry)
// Find the chains with more advanced crypto suite
chains = ubiquity.Filter(chains, ubiquity.CompareChainCryptoSuite)
return chains
} | go | func optimalChains(chains [][]*x509.Certificate) [][]*x509.Certificate {
// Find shortest chains
chains = ubiquity.Filter(chains, ubiquity.CompareChainLength)
// Find the chains with longest expiry.
chains = ubiquity.Filter(chains, ubiquity.CompareChainExpiry)
// Find the chains with more advanced crypto suite
chains = ubiquity.Filter(chains, ubiquity.CompareChainCryptoSuite)
return chains
} | [
"func",
"optimalChains",
"(",
"chains",
"[",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"[",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
"{",
"// Find shortest chains",
"chains",
"=",
"ubiquity",
".",
"Filter",
"(",
"chains",
",",
"ubiquity... | // Optimal chains are the shortest chains, with newest intermediates and most advanced crypto suite being the tie breaker. | [
"Optimal",
"chains",
"are",
"the",
"shortest",
"chains",
"with",
"newest",
"intermediates",
"and",
"most",
"advanced",
"crypto",
"suite",
"being",
"the",
"tie",
"breaker",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L796-L805 |
161,547 | cloudflare/cfssl | bundler/bundler.go | ubiquitousChains | func ubiquitousChains(chains [][]*x509.Certificate) [][]*x509.Certificate {
// Filter out chains with highest cross platform ubiquity.
chains = ubiquity.Filter(chains, ubiquity.ComparePlatformUbiquity)
// Prefer that all intermediates are SHA-2 certs if the leaf is a SHA-2 cert, in order to improve ubiquity.
chains = ubiquity.Filter(chains, ubiquity.CompareSHA2Homogeneity)
// Filter shortest chains
chains = ubiquity.Filter(chains, ubiquity.CompareChainLength)
// Filter chains with highest signature hash ubiquity.
chains = ubiquity.Filter(chains, ubiquity.CompareChainHashUbiquity)
// Filter chains with highest keyAlgo ubiquity.
chains = ubiquity.Filter(chains, ubiquity.CompareChainKeyAlgoUbiquity)
// Filter chains with intermediates that last longer.
chains = ubiquity.Filter(chains, ubiquity.CompareExpiryUbiquity)
// Use the optimal strategy as final tie breaker.
return optimalChains(chains)
} | go | func ubiquitousChains(chains [][]*x509.Certificate) [][]*x509.Certificate {
// Filter out chains with highest cross platform ubiquity.
chains = ubiquity.Filter(chains, ubiquity.ComparePlatformUbiquity)
// Prefer that all intermediates are SHA-2 certs if the leaf is a SHA-2 cert, in order to improve ubiquity.
chains = ubiquity.Filter(chains, ubiquity.CompareSHA2Homogeneity)
// Filter shortest chains
chains = ubiquity.Filter(chains, ubiquity.CompareChainLength)
// Filter chains with highest signature hash ubiquity.
chains = ubiquity.Filter(chains, ubiquity.CompareChainHashUbiquity)
// Filter chains with highest keyAlgo ubiquity.
chains = ubiquity.Filter(chains, ubiquity.CompareChainKeyAlgoUbiquity)
// Filter chains with intermediates that last longer.
chains = ubiquity.Filter(chains, ubiquity.CompareExpiryUbiquity)
// Use the optimal strategy as final tie breaker.
return optimalChains(chains)
} | [
"func",
"ubiquitousChains",
"(",
"chains",
"[",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"[",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
"{",
"// Filter out chains with highest cross platform ubiquity.",
"chains",
"=",
"ubiquity",
".",
"Filter",... | // Ubiquitous chains are the chains with highest platform coverage and break ties with the optimal strategy. | [
"Ubiquitous",
"chains",
"are",
"the",
"chains",
"with",
"highest",
"platform",
"coverage",
"and",
"break",
"ties",
"with",
"the",
"optimal",
"strategy",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L808-L823 |
161,548 | cloudflare/cfssl | bundler/bundler.go | diff | func diff(chain1, chain2 []*x509.Certificate) bool {
// Check if bundled one is different from the input.
diff := false
if len(chain1) != len(chain2) {
diff = true
} else {
for i := 0; i < len(chain1); i++ {
cert1 := chain1[i]
cert2 := chain2[i]
// Use signature to differentiate.
if !bytes.Equal(cert1.Signature, cert2.Signature) {
diff = true
break
}
}
}
return diff
} | go | func diff(chain1, chain2 []*x509.Certificate) bool {
// Check if bundled one is different from the input.
diff := false
if len(chain1) != len(chain2) {
diff = true
} else {
for i := 0; i < len(chain1); i++ {
cert1 := chain1[i]
cert2 := chain2[i]
// Use signature to differentiate.
if !bytes.Equal(cert1.Signature, cert2.Signature) {
diff = true
break
}
}
}
return diff
} | [
"func",
"diff",
"(",
"chain1",
",",
"chain2",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"bool",
"{",
"// Check if bundled one is different from the input.",
"diff",
":=",
"false",
"\n",
"if",
"len",
"(",
"chain1",
")",
"!=",
"len",
"(",
"chain2",
")",
... | // diff checkes if two input cert chains are not identical | [
"diff",
"checkes",
"if",
"two",
"input",
"cert",
"chains",
"are",
"not",
"identical"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/bundler/bundler.go#L826-L843 |
161,549 | cloudflare/cfssl | scan/tls_handshake.go | cipherSuiteScan | func cipherSuiteScan(addr, hostname string) (grade Grade, output Output, err error) {
var cvList cipherVersionList
allCiphers := allCiphersIDs()
var vers uint16
for vers = tls.VersionTLS12; vers >= tls.VersionSSL30; vers-- {
ciphers := make([]uint16, len(allCiphers))
copy(ciphers, allCiphers)
for len(ciphers) > 0 {
var cipherIndex int
cipherIndex, _, _, err = sayHello(addr, hostname, ciphers, nil, vers, nil)
if err != nil {
if err == errHelloFailed {
err = nil
break
}
return
}
if vers == tls.VersionSSL30 {
grade = Warning
}
cipherID := ciphers[cipherIndex]
// If this is an EC cipher suite, do a second scan for curve support
var supportedCurves []tls.CurveID
if tls.CipherSuites[cipherID].EllipticCurve {
supportedCurves, err = doCurveScan(addr, hostname, vers, cipherID, ciphers)
if len(supportedCurves) == 0 {
err = errors.New("couldn't negotiate any curves")
}
}
for i, c := range cvList {
if cipherID == c.cipherID {
cvList[i].data = append(c.data, cipherDatum{vers, supportedCurves})
goto exists
}
}
cvList = append(cvList, cipherVersions{cipherID, []cipherDatum{{vers, supportedCurves}}})
exists:
ciphers = append(ciphers[:cipherIndex], ciphers[cipherIndex+1:]...)
}
}
if len(cvList) == 0 {
err = errors.New("couldn't negotiate any cipher suites")
return
}
if grade != Warning {
grade = Good
}
output = cvList
return
} | go | func cipherSuiteScan(addr, hostname string) (grade Grade, output Output, err error) {
var cvList cipherVersionList
allCiphers := allCiphersIDs()
var vers uint16
for vers = tls.VersionTLS12; vers >= tls.VersionSSL30; vers-- {
ciphers := make([]uint16, len(allCiphers))
copy(ciphers, allCiphers)
for len(ciphers) > 0 {
var cipherIndex int
cipherIndex, _, _, err = sayHello(addr, hostname, ciphers, nil, vers, nil)
if err != nil {
if err == errHelloFailed {
err = nil
break
}
return
}
if vers == tls.VersionSSL30 {
grade = Warning
}
cipherID := ciphers[cipherIndex]
// If this is an EC cipher suite, do a second scan for curve support
var supportedCurves []tls.CurveID
if tls.CipherSuites[cipherID].EllipticCurve {
supportedCurves, err = doCurveScan(addr, hostname, vers, cipherID, ciphers)
if len(supportedCurves) == 0 {
err = errors.New("couldn't negotiate any curves")
}
}
for i, c := range cvList {
if cipherID == c.cipherID {
cvList[i].data = append(c.data, cipherDatum{vers, supportedCurves})
goto exists
}
}
cvList = append(cvList, cipherVersions{cipherID, []cipherDatum{{vers, supportedCurves}}})
exists:
ciphers = append(ciphers[:cipherIndex], ciphers[cipherIndex+1:]...)
}
}
if len(cvList) == 0 {
err = errors.New("couldn't negotiate any cipher suites")
return
}
if grade != Warning {
grade = Good
}
output = cvList
return
} | [
"func",
"cipherSuiteScan",
"(",
"addr",
",",
"hostname",
"string",
")",
"(",
"grade",
"Grade",
",",
"output",
"Output",
",",
"err",
"error",
")",
"{",
"var",
"cvList",
"cipherVersionList",
"\n",
"allCiphers",
":=",
"allCiphersIDs",
"(",
")",
"\n\n",
"var",
... | // cipherSuiteScan returns, by TLS Version, the sort list of cipher suites
// supported by the host | [
"cipherSuiteScan",
"returns",
"by",
"TLS",
"Version",
"the",
"sort",
"list",
"of",
"cipher",
"suites",
"supported",
"by",
"the",
"host"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/tls_handshake.go#L271-L325 |
161,550 | cloudflare/cfssl | scan/tls_handshake.go | sigAlgsScan | func sigAlgsScan(addr, hostname string) (grade Grade, output Output, err error) {
var supportedSigAlgs []tls.SignatureAndHash
for _, sigAlg := range tls.AllSignatureAndHashAlgorithms {
_, _, _, e := sayHello(addr, hostname, nil, nil, tls.VersionTLS12, []tls.SignatureAndHash{sigAlg})
if e == nil {
supportedSigAlgs = append(supportedSigAlgs, sigAlg)
}
}
if len(supportedSigAlgs) > 0 {
grade = Good
output = supportedSigAlgs
} else {
err = errors.New("no SigAlgs supported")
}
return
} | go | func sigAlgsScan(addr, hostname string) (grade Grade, output Output, err error) {
var supportedSigAlgs []tls.SignatureAndHash
for _, sigAlg := range tls.AllSignatureAndHashAlgorithms {
_, _, _, e := sayHello(addr, hostname, nil, nil, tls.VersionTLS12, []tls.SignatureAndHash{sigAlg})
if e == nil {
supportedSigAlgs = append(supportedSigAlgs, sigAlg)
}
}
if len(supportedSigAlgs) > 0 {
grade = Good
output = supportedSigAlgs
} else {
err = errors.New("no SigAlgs supported")
}
return
} | [
"func",
"sigAlgsScan",
"(",
"addr",
",",
"hostname",
"string",
")",
"(",
"grade",
"Grade",
",",
"output",
"Output",
",",
"err",
"error",
")",
"{",
"var",
"supportedSigAlgs",
"[",
"]",
"tls",
".",
"SignatureAndHash",
"\n",
"for",
"_",
",",
"sigAlg",
":=",... | // sigAlgsScan returns the accepted signature and hash algorithms of the host | [
"sigAlgsScan",
"returns",
"the",
"accepted",
"signature",
"and",
"hash",
"algorithms",
"of",
"the",
"host"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/tls_handshake.go#L328-L344 |
161,551 | cloudflare/cfssl | scan/tls_handshake.go | certSigAlgsScan | func certSigAlgsScan(addr, hostname string) (grade Grade, output Output, err error) {
var certSigAlgs = make(map[string]string)
for _, sigAlg := range tls.AllSignatureAndHashAlgorithms {
_, _, derCerts, e := sayHello(addr, hostname, nil, nil, tls.VersionTLS12, []tls.SignatureAndHash{sigAlg})
if e == nil {
if len(derCerts) == 0 {
return Bad, nil, errors.New("no certs returned")
}
certs, _, err := helpers.ParseCertificatesDER(derCerts[0], "")
if err != nil {
return Bad, nil, err
}
certSigAlgs[sigAlg.String()] = helpers.SignatureString(certs[0].SignatureAlgorithm)
//certSigAlgs = append(certSigAlgs, certs[0].SignatureAlgorithm)
}
}
if len(certSigAlgs) > 0 {
grade = Good
output = certSigAlgs
} else {
err = errors.New("no SigAlgs supported")
}
return
} | go | func certSigAlgsScan(addr, hostname string) (grade Grade, output Output, err error) {
var certSigAlgs = make(map[string]string)
for _, sigAlg := range tls.AllSignatureAndHashAlgorithms {
_, _, derCerts, e := sayHello(addr, hostname, nil, nil, tls.VersionTLS12, []tls.SignatureAndHash{sigAlg})
if e == nil {
if len(derCerts) == 0 {
return Bad, nil, errors.New("no certs returned")
}
certs, _, err := helpers.ParseCertificatesDER(derCerts[0], "")
if err != nil {
return Bad, nil, err
}
certSigAlgs[sigAlg.String()] = helpers.SignatureString(certs[0].SignatureAlgorithm)
//certSigAlgs = append(certSigAlgs, certs[0].SignatureAlgorithm)
}
}
if len(certSigAlgs) > 0 {
grade = Good
output = certSigAlgs
} else {
err = errors.New("no SigAlgs supported")
}
return
} | [
"func",
"certSigAlgsScan",
"(",
"addr",
",",
"hostname",
"string",
")",
"(",
"grade",
"Grade",
",",
"output",
"Output",
",",
"err",
"error",
")",
"{",
"var",
"certSigAlgs",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"_",
... | // certSigAlgScan returns the server certificate with various sigature and hash algorithms in the ClientHello | [
"certSigAlgScan",
"returns",
"the",
"server",
"certificate",
"with",
"various",
"sigature",
"and",
"hash",
"algorithms",
"in",
"the",
"ClientHello"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/tls_handshake.go#L347-L373 |
161,552 | cloudflare/cfssl | scan/tls_handshake.go | certSigAlgsScanByCipher | func certSigAlgsScanByCipher(addr, hostname string) (grade Grade, output Output, err error) {
var certSigAlgs = make(map[string]string)
for cipherID := range tls.CipherSuites {
_, _, derCerts, e := sayHello(addr, hostname, []uint16{cipherID}, nil, tls.VersionTLS12, []tls.SignatureAndHash{})
if e == nil {
if len(derCerts) == 0 {
return Bad, nil, errors.New("no certs returned")
}
certs, _, err := helpers.ParseCertificatesDER(derCerts[0], "")
if err != nil {
return Bad, nil, err
}
certSigAlgs[tls.CipherSuites[cipherID].Name] = helpers.SignatureString(certs[0].SignatureAlgorithm)
//certSigAlgs = append(certSigAlgs, certs[0].SignatureAlgorithm)
}
}
if len(certSigAlgs) > 0 {
grade = Good
output = certSigAlgs
} else {
err = errors.New("no cipher supported")
}
return
} | go | func certSigAlgsScanByCipher(addr, hostname string) (grade Grade, output Output, err error) {
var certSigAlgs = make(map[string]string)
for cipherID := range tls.CipherSuites {
_, _, derCerts, e := sayHello(addr, hostname, []uint16{cipherID}, nil, tls.VersionTLS12, []tls.SignatureAndHash{})
if e == nil {
if len(derCerts) == 0 {
return Bad, nil, errors.New("no certs returned")
}
certs, _, err := helpers.ParseCertificatesDER(derCerts[0], "")
if err != nil {
return Bad, nil, err
}
certSigAlgs[tls.CipherSuites[cipherID].Name] = helpers.SignatureString(certs[0].SignatureAlgorithm)
//certSigAlgs = append(certSigAlgs, certs[0].SignatureAlgorithm)
}
}
if len(certSigAlgs) > 0 {
grade = Good
output = certSigAlgs
} else {
err = errors.New("no cipher supported")
}
return
} | [
"func",
"certSigAlgsScanByCipher",
"(",
"addr",
",",
"hostname",
"string",
")",
"(",
"grade",
"Grade",
",",
"output",
"Output",
",",
"err",
"error",
")",
"{",
"var",
"certSigAlgs",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
... | // certSigAlgScan returns the server certificate with various ciphers in the ClientHello | [
"certSigAlgScan",
"returns",
"the",
"server",
"certificate",
"with",
"various",
"ciphers",
"in",
"the",
"ClientHello"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/tls_handshake.go#L376-L401 |
161,553 | cloudflare/cfssl | scan/tls_handshake.go | ecCurveScan | func ecCurveScan(addr, hostname string) (grade Grade, output Output, err error) {
allCurves := allCurvesIDs()
curves := make([]tls.CurveID, len(allCurves))
copy(curves, allCurves)
var supportedCurves []string
for len(curves) > 0 {
var curveIndex int
_, curveIndex, _, err = sayHello(addr, hostname, allECDHECiphersIDs(), curves, tls.VersionTLS12, nil)
if err != nil {
// This case is expected, because eventually we ask only for curves the server doesn't support
if err == errHelloFailed {
err = nil
break
}
return
}
curveID := curves[curveIndex]
supportedCurves = append(supportedCurves, tls.Curves[curveID])
curves = append(curves[:curveIndex], curves[curveIndex+1:]...)
}
output = supportedCurves
grade = Good
return
} | go | func ecCurveScan(addr, hostname string) (grade Grade, output Output, err error) {
allCurves := allCurvesIDs()
curves := make([]tls.CurveID, len(allCurves))
copy(curves, allCurves)
var supportedCurves []string
for len(curves) > 0 {
var curveIndex int
_, curveIndex, _, err = sayHello(addr, hostname, allECDHECiphersIDs(), curves, tls.VersionTLS12, nil)
if err != nil {
// This case is expected, because eventually we ask only for curves the server doesn't support
if err == errHelloFailed {
err = nil
break
}
return
}
curveID := curves[curveIndex]
supportedCurves = append(supportedCurves, tls.Curves[curveID])
curves = append(curves[:curveIndex], curves[curveIndex+1:]...)
}
output = supportedCurves
grade = Good
return
} | [
"func",
"ecCurveScan",
"(",
"addr",
",",
"hostname",
"string",
")",
"(",
"grade",
"Grade",
",",
"output",
"Output",
",",
"err",
"error",
")",
"{",
"allCurves",
":=",
"allCurvesIDs",
"(",
")",
"\n",
"curves",
":=",
"make",
"(",
"[",
"]",
"tls",
".",
"... | // ecCurveScan returns the elliptic curves supported by the host. | [
"ecCurveScan",
"returns",
"the",
"elliptic",
"curves",
"supported",
"by",
"the",
"host",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/tls_handshake.go#L404-L427 |
161,554 | cloudflare/cfssl | api/generator/generator.go | NewHandler | func NewHandler(validator Validator) (http.Handler, error) {
log.Info("setting up key / CSR generator")
return &api.HTTPHandler{
Handler: &Handler{
generator: &csr.Generator{Validator: validator},
},
Methods: []string{"POST"},
}, nil
} | go | func NewHandler(validator Validator) (http.Handler, error) {
log.Info("setting up key / CSR generator")
return &api.HTTPHandler{
Handler: &Handler{
generator: &csr.Generator{Validator: validator},
},
Methods: []string{"POST"},
}, nil
} | [
"func",
"NewHandler",
"(",
"validator",
"Validator",
")",
"(",
"http",
".",
"Handler",
",",
"error",
")",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"&",
"api",
".",
"HTTPHandler",
"{",
"Handler",
":",
"&",
"Handler",
"{",
"genera... | // NewHandler builds a new Handler from the
// validation function provided. | [
"NewHandler",
"builds",
"a",
"new",
"Handler",
"from",
"the",
"validation",
"function",
"provided",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/generator/generator.go#L60-L68 |
161,555 | cloudflare/cfssl | api/generator/generator.go | Handle | func (g *Handler) Handle(w http.ResponseWriter, r *http.Request) error {
log.Info("request for CSR")
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Warningf("failed to read request body: %v", err)
return errors.NewBadRequest(err)
}
r.Body.Close()
req := new(csr.CertificateRequest)
req.KeyRequest = csr.NewBasicKeyRequest()
err = json.Unmarshal(body, req)
if err != nil {
log.Warningf("failed to unmarshal request: %v", err)
return errors.NewBadRequest(err)
}
if req.CA != nil {
log.Warningf("request received with CA section")
return errors.NewBadRequestString("ca section only permitted in initca")
}
csr, key, err := g.generator.ProcessRequest(req)
if err != nil {
log.Warningf("failed to process CSR: %v", err)
// The validator returns a *cfssl/errors.HttpError
return err
}
sum, err := computeSum(csr)
if err != nil {
return errors.NewBadRequest(err)
}
// Both key and csr are returned PEM-encoded.
response := api.NewSuccessResponse(&CertRequest{
Key: string(key),
CSR: string(csr),
Sums: map[string]Sum{"certificate_request": sum},
})
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
err = enc.Encode(response)
return err
} | go | func (g *Handler) Handle(w http.ResponseWriter, r *http.Request) error {
log.Info("request for CSR")
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Warningf("failed to read request body: %v", err)
return errors.NewBadRequest(err)
}
r.Body.Close()
req := new(csr.CertificateRequest)
req.KeyRequest = csr.NewBasicKeyRequest()
err = json.Unmarshal(body, req)
if err != nil {
log.Warningf("failed to unmarshal request: %v", err)
return errors.NewBadRequest(err)
}
if req.CA != nil {
log.Warningf("request received with CA section")
return errors.NewBadRequestString("ca section only permitted in initca")
}
csr, key, err := g.generator.ProcessRequest(req)
if err != nil {
log.Warningf("failed to process CSR: %v", err)
// The validator returns a *cfssl/errors.HttpError
return err
}
sum, err := computeSum(csr)
if err != nil {
return errors.NewBadRequest(err)
}
// Both key and csr are returned PEM-encoded.
response := api.NewSuccessResponse(&CertRequest{
Key: string(key),
CSR: string(csr),
Sums: map[string]Sum{"certificate_request": sum},
})
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
err = enc.Encode(response)
return err
} | [
"func",
"(",
"g",
"*",
"Handler",
")",
"Handle",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll"... | // Handle responds to requests for the CA to generate a new private
// key and certificate request on behalf of the client. The format for
// these requests is documented in the API documentation. | [
"Handle",
"responds",
"to",
"requests",
"for",
"the",
"CA",
"to",
"generate",
"a",
"new",
"private",
"key",
"and",
"certificate",
"request",
"on",
"behalf",
"of",
"the",
"client",
".",
"The",
"format",
"for",
"these",
"requests",
"is",
"documented",
"in",
... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/generator/generator.go#L108-L152 |
161,556 | cloudflare/cfssl | api/generator/generator.go | NewCertGeneratorHandler | func NewCertGeneratorHandler(validator Validator, caFile, caKeyFile string, policy *config.Signing) (http.Handler, error) {
var err error
log.Info("setting up new generator / signer")
cg := new(CertGeneratorHandler)
if policy == nil {
policy = &config.Signing{
Default: config.DefaultConfig(),
Profiles: nil,
}
}
root := universal.Root{
Config: map[string]string{
"ca-file": caFile,
"ca-key-file": caKeyFile,
},
}
if cg.signer, err = universal.NewSigner(root, policy); err != nil {
log.Errorf("setting up signer failed: %v", err)
return nil, err
}
cg.generator = &csr.Generator{Validator: validator}
return api.HTTPHandler{Handler: cg, Methods: []string{"POST"}}, nil
} | go | func NewCertGeneratorHandler(validator Validator, caFile, caKeyFile string, policy *config.Signing) (http.Handler, error) {
var err error
log.Info("setting up new generator / signer")
cg := new(CertGeneratorHandler)
if policy == nil {
policy = &config.Signing{
Default: config.DefaultConfig(),
Profiles: nil,
}
}
root := universal.Root{
Config: map[string]string{
"ca-file": caFile,
"ca-key-file": caKeyFile,
},
}
if cg.signer, err = universal.NewSigner(root, policy); err != nil {
log.Errorf("setting up signer failed: %v", err)
return nil, err
}
cg.generator = &csr.Generator{Validator: validator}
return api.HTTPHandler{Handler: cg, Methods: []string{"POST"}}, nil
} | [
"func",
"NewCertGeneratorHandler",
"(",
"validator",
"Validator",
",",
"caFile",
",",
"caKeyFile",
"string",
",",
"policy",
"*",
"config",
".",
"Signing",
")",
"(",
"http",
".",
"Handler",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"log",
".",
... | // NewCertGeneratorHandler builds a new handler for generating
// certificates directly from certificate requests; the validator covers
// the certificate request and the CA's key and certificate are used to
// sign the generated request. If remote is not an empty string, the
// handler will send signature requests to the CFSSL instance contained
// in remote. | [
"NewCertGeneratorHandler",
"builds",
"a",
"new",
"handler",
"for",
"generating",
"certificates",
"directly",
"from",
"certificate",
"requests",
";",
"the",
"validator",
"covers",
"the",
"certificate",
"request",
"and",
"the",
"CA",
"s",
"key",
"and",
"certificate",
... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/generator/generator.go#L169-L195 |
161,557 | cloudflare/cfssl | api/generator/generator.go | NewCertGeneratorHandlerFromSigner | func NewCertGeneratorHandlerFromSigner(validator Validator, signer signer.Signer) http.Handler {
return api.HTTPHandler{
Handler: &CertGeneratorHandler{
generator: &csr.Generator{Validator: validator},
signer: signer,
},
Methods: []string{"POST"},
}
} | go | func NewCertGeneratorHandlerFromSigner(validator Validator, signer signer.Signer) http.Handler {
return api.HTTPHandler{
Handler: &CertGeneratorHandler{
generator: &csr.Generator{Validator: validator},
signer: signer,
},
Methods: []string{"POST"},
}
} | [
"func",
"NewCertGeneratorHandlerFromSigner",
"(",
"validator",
"Validator",
",",
"signer",
"signer",
".",
"Signer",
")",
"http",
".",
"Handler",
"{",
"return",
"api",
".",
"HTTPHandler",
"{",
"Handler",
":",
"&",
"CertGeneratorHandler",
"{",
"generator",
":",
"&... | // NewCertGeneratorHandlerFromSigner returns a handler directly from
// the signer and validation function. | [
"NewCertGeneratorHandlerFromSigner",
"returns",
"a",
"handler",
"directly",
"from",
"the",
"signer",
"and",
"validation",
"function",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/generator/generator.go#L199-L207 |
161,558 | cloudflare/cfssl | api/generator/generator.go | SetBundler | func (cg *CertGeneratorHandler) SetBundler(caBundleFile, intBundleFile string) (err error) {
cg.bundler, err = bundler.NewBundler(caBundleFile, intBundleFile)
return err
} | go | func (cg *CertGeneratorHandler) SetBundler(caBundleFile, intBundleFile string) (err error) {
cg.bundler, err = bundler.NewBundler(caBundleFile, intBundleFile)
return err
} | [
"func",
"(",
"cg",
"*",
"CertGeneratorHandler",
")",
"SetBundler",
"(",
"caBundleFile",
",",
"intBundleFile",
"string",
")",
"(",
"err",
"error",
")",
"{",
"cg",
".",
"bundler",
",",
"err",
"=",
"bundler",
".",
"NewBundler",
"(",
"caBundleFile",
",",
"intB... | // SetBundler allows injecting an optional Bundler into the CertGeneratorHandler. | [
"SetBundler",
"allows",
"injecting",
"an",
"optional",
"Bundler",
"into",
"the",
"CertGeneratorHandler",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/generator/generator.go#L210-L213 |
161,559 | cloudflare/cfssl | api/generator/generator.go | Handle | func (cg *CertGeneratorHandler) Handle(w http.ResponseWriter, r *http.Request) error {
log.Info("request for CSR")
req := new(genSignRequest)
req.Request = csr.New()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Warningf("failed to read request body: %v", err)
return errors.NewBadRequest(err)
}
r.Body.Close()
err = json.Unmarshal(body, req)
if err != nil {
log.Warningf("failed to unmarshal request: %v", err)
return errors.NewBadRequest(err)
}
if req.Request == nil {
log.Warning("empty request received")
return errors.NewBadRequestString("missing request section")
}
if req.Request.CA != nil {
log.Warningf("request received with CA section")
return errors.NewBadRequestString("ca section only permitted in initca")
}
csr, key, err := cg.generator.ProcessRequest(req.Request)
if err != nil {
log.Warningf("failed to process CSR: %v", err)
// The validator returns a *cfssl/errors.HttpError
return err
}
signReq := signer.SignRequest{
Request: string(csr),
Profile: req.Profile,
Label: req.Label,
}
certBytes, err := cg.signer.Sign(signReq)
if err != nil {
log.Warningf("failed to sign request: %v", err)
return err
}
reqSum, err := computeSum(csr)
if err != nil {
return errors.NewBadRequest(err)
}
certSum, err := computeSum(certBytes)
if err != nil {
return errors.NewBadRequest(err)
}
result := map[string]interface{}{
"private_key": string(key),
"certificate_request": string(csr),
"certificate": string(certBytes),
"sums": map[string]Sum{
"certificate_request": reqSum,
"certificate": certSum,
},
}
if req.Bundle {
if cg.bundler == nil {
return api.SendResponseWithMessage(w, result, NoBundlerMessage,
errors.New(errors.PolicyError, errors.InvalidRequest).ErrorCode)
}
bundle, err := cg.bundler.BundleFromPEMorDER(certBytes, nil, bundler.Optimal, "")
if err != nil {
return err
}
result["bundle"] = bundle
}
if len(req.Request.Hosts) == 0 {
return api.SendResponseWithMessage(w, result, CSRNoHostMessage,
errors.New(errors.PolicyError, errors.InvalidRequest).ErrorCode)
}
return api.SendResponse(w, result)
} | go | func (cg *CertGeneratorHandler) Handle(w http.ResponseWriter, r *http.Request) error {
log.Info("request for CSR")
req := new(genSignRequest)
req.Request = csr.New()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Warningf("failed to read request body: %v", err)
return errors.NewBadRequest(err)
}
r.Body.Close()
err = json.Unmarshal(body, req)
if err != nil {
log.Warningf("failed to unmarshal request: %v", err)
return errors.NewBadRequest(err)
}
if req.Request == nil {
log.Warning("empty request received")
return errors.NewBadRequestString("missing request section")
}
if req.Request.CA != nil {
log.Warningf("request received with CA section")
return errors.NewBadRequestString("ca section only permitted in initca")
}
csr, key, err := cg.generator.ProcessRequest(req.Request)
if err != nil {
log.Warningf("failed to process CSR: %v", err)
// The validator returns a *cfssl/errors.HttpError
return err
}
signReq := signer.SignRequest{
Request: string(csr),
Profile: req.Profile,
Label: req.Label,
}
certBytes, err := cg.signer.Sign(signReq)
if err != nil {
log.Warningf("failed to sign request: %v", err)
return err
}
reqSum, err := computeSum(csr)
if err != nil {
return errors.NewBadRequest(err)
}
certSum, err := computeSum(certBytes)
if err != nil {
return errors.NewBadRequest(err)
}
result := map[string]interface{}{
"private_key": string(key),
"certificate_request": string(csr),
"certificate": string(certBytes),
"sums": map[string]Sum{
"certificate_request": reqSum,
"certificate": certSum,
},
}
if req.Bundle {
if cg.bundler == nil {
return api.SendResponseWithMessage(w, result, NoBundlerMessage,
errors.New(errors.PolicyError, errors.InvalidRequest).ErrorCode)
}
bundle, err := cg.bundler.BundleFromPEMorDER(certBytes, nil, bundler.Optimal, "")
if err != nil {
return err
}
result["bundle"] = bundle
}
if len(req.Request.Hosts) == 0 {
return api.SendResponseWithMessage(w, result, CSRNoHostMessage,
errors.New(errors.PolicyError, errors.InvalidRequest).ErrorCode)
}
return api.SendResponse(w, result)
} | [
"func",
"(",
"cg",
"*",
"CertGeneratorHandler",
")",
"Handle",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"req",
":=",
"new",
"(",
"genSignReque... | // Handle responds to requests for the CA to generate a new private
// key and certificate on behalf of the client. The format for these
// requests is documented in the API documentation. | [
"Handle",
"responds",
"to",
"requests",
"for",
"the",
"CA",
"to",
"generate",
"a",
"new",
"private",
"key",
"and",
"certificate",
"on",
"behalf",
"of",
"the",
"client",
".",
"The",
"format",
"for",
"these",
"requests",
"is",
"documented",
"in",
"the",
"API... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/generator/generator.go#L225-L313 |
161,560 | cloudflare/cfssl | transport/listener.go | Listen | func Listen(address string, tr *Transport) (*Listener, error) {
var err error
l := &Listener{Transport: tr}
config, err := tr.getConfig()
if err != nil {
return nil, err
}
l.Listener, err = tls.Listen("tcp", address, config)
return l, err
} | go | func Listen(address string, tr *Transport) (*Listener, error) {
var err error
l := &Listener{Transport: tr}
config, err := tr.getConfig()
if err != nil {
return nil, err
}
l.Listener, err = tls.Listen("tcp", address, config)
return l, err
} | [
"func",
"Listen",
"(",
"address",
"string",
",",
"tr",
"*",
"Transport",
")",
"(",
"*",
"Listener",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"l",
":=",
"&",
"Listener",
"{",
"Transport",
":",
"tr",
"}",
"\n",
"config",
",",
"err",
":=",... | // Listen sets up a new server. If an error is returned, it means
// the server isn't ready to begin listening. | [
"Listen",
"sets",
"up",
"a",
"new",
"server",
".",
"If",
"an",
"error",
"is",
"returned",
"it",
"means",
"the",
"server",
"isn",
"t",
"ready",
"to",
"begin",
"listening",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/listener.go#L19-L29 |
161,561 | cloudflare/cfssl | crl/crl.go | NewCRLFromFile | func NewCRLFromFile(serialList, issuerFile, keyFile []byte, expiryTime string) ([]byte, error) {
var revokedCerts []pkix.RevokedCertificate
var oneWeek = time.Duration(604800) * time.Second
expiryInt, err := strconv.ParseInt(expiryTime, 0, 32)
if err != nil {
return nil, err
}
newDurationFromInt := time.Duration(expiryInt) * time.Second
newExpiryTime := time.Now().Add(newDurationFromInt)
if expiryInt == 0 {
newExpiryTime = time.Now().Add(oneWeek)
}
// Parse the PEM encoded certificate
issuerCert, err := helpers.ParseCertificatePEM(issuerFile)
if err != nil {
return nil, err
}
// Split input file by new lines
individualCerts := strings.Split(string(serialList), "\n")
// For every new line, create a new revokedCertificate and add it to slice
for _, value := range individualCerts {
if len(strings.TrimSpace(value)) == 0 {
continue
}
tempBigInt := new(big.Int)
tempBigInt.SetString(value, 10)
tempCert := pkix.RevokedCertificate{
SerialNumber: tempBigInt,
RevocationTime: time.Now(),
}
revokedCerts = append(revokedCerts, tempCert)
}
strPassword := os.Getenv("CFSSL_CA_PK_PASSWORD")
password := []byte(strPassword)
if strPassword == "" {
password = nil
}
// Parse the key given
key, err := helpers.ParsePrivateKeyPEMWithPassword(keyFile, password)
if err != nil {
log.Debug("Malformed private key %v", err)
return nil, err
}
return CreateGenericCRL(revokedCerts, key, issuerCert, newExpiryTime)
} | go | func NewCRLFromFile(serialList, issuerFile, keyFile []byte, expiryTime string) ([]byte, error) {
var revokedCerts []pkix.RevokedCertificate
var oneWeek = time.Duration(604800) * time.Second
expiryInt, err := strconv.ParseInt(expiryTime, 0, 32)
if err != nil {
return nil, err
}
newDurationFromInt := time.Duration(expiryInt) * time.Second
newExpiryTime := time.Now().Add(newDurationFromInt)
if expiryInt == 0 {
newExpiryTime = time.Now().Add(oneWeek)
}
// Parse the PEM encoded certificate
issuerCert, err := helpers.ParseCertificatePEM(issuerFile)
if err != nil {
return nil, err
}
// Split input file by new lines
individualCerts := strings.Split(string(serialList), "\n")
// For every new line, create a new revokedCertificate and add it to slice
for _, value := range individualCerts {
if len(strings.TrimSpace(value)) == 0 {
continue
}
tempBigInt := new(big.Int)
tempBigInt.SetString(value, 10)
tempCert := pkix.RevokedCertificate{
SerialNumber: tempBigInt,
RevocationTime: time.Now(),
}
revokedCerts = append(revokedCerts, tempCert)
}
strPassword := os.Getenv("CFSSL_CA_PK_PASSWORD")
password := []byte(strPassword)
if strPassword == "" {
password = nil
}
// Parse the key given
key, err := helpers.ParsePrivateKeyPEMWithPassword(keyFile, password)
if err != nil {
log.Debug("Malformed private key %v", err)
return nil, err
}
return CreateGenericCRL(revokedCerts, key, issuerCert, newExpiryTime)
} | [
"func",
"NewCRLFromFile",
"(",
"serialList",
",",
"issuerFile",
",",
"keyFile",
"[",
"]",
"byte",
",",
"expiryTime",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"revokedCerts",
"[",
"]",
"pkix",
".",
"RevokedCertificate",
"\n",
"... | // NewCRLFromFile takes in a list of serial numbers, one per line, as well as the issuing certificate
// of the CRL, and the private key. This function is then used to parse the list and generate a CRL | [
"NewCRLFromFile",
"takes",
"in",
"a",
"list",
"of",
"serial",
"numbers",
"one",
"per",
"line",
"as",
"well",
"as",
"the",
"issuing",
"certificate",
"of",
"the",
"CRL",
"and",
"the",
"private",
"key",
".",
"This",
"function",
"is",
"then",
"used",
"to",
"... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/crl/crl.go#L22-L75 |
161,562 | cloudflare/cfssl | crl/crl.go | NewCRLFromDB | func NewCRLFromDB(certs []certdb.CertificateRecord, issuerCert *x509.Certificate, key crypto.Signer, expiryTime time.Duration) ([]byte, error) {
var revokedCerts []pkix.RevokedCertificate
newExpiryTime := time.Now().Add(expiryTime)
// For every record, create a new revokedCertificate and add it to slice
for _, certRecord := range certs {
serialInt := new(big.Int)
serialInt.SetString(certRecord.Serial, 10)
tempCert := pkix.RevokedCertificate{
SerialNumber: serialInt,
RevocationTime: certRecord.RevokedAt,
}
revokedCerts = append(revokedCerts, tempCert)
}
return CreateGenericCRL(revokedCerts, key, issuerCert, newExpiryTime)
} | go | func NewCRLFromDB(certs []certdb.CertificateRecord, issuerCert *x509.Certificate, key crypto.Signer, expiryTime time.Duration) ([]byte, error) {
var revokedCerts []pkix.RevokedCertificate
newExpiryTime := time.Now().Add(expiryTime)
// For every record, create a new revokedCertificate and add it to slice
for _, certRecord := range certs {
serialInt := new(big.Int)
serialInt.SetString(certRecord.Serial, 10)
tempCert := pkix.RevokedCertificate{
SerialNumber: serialInt,
RevocationTime: certRecord.RevokedAt,
}
revokedCerts = append(revokedCerts, tempCert)
}
return CreateGenericCRL(revokedCerts, key, issuerCert, newExpiryTime)
} | [
"func",
"NewCRLFromDB",
"(",
"certs",
"[",
"]",
"certdb",
".",
"CertificateRecord",
",",
"issuerCert",
"*",
"x509",
".",
"Certificate",
",",
"key",
"crypto",
".",
"Signer",
",",
"expiryTime",
"time",
".",
"Duration",
")",
"(",
"[",
"]",
"byte",
",",
"err... | // NewCRLFromDB takes in a list of CertificateRecords, as well as the issuing certificate
// of the CRL, and the private key. This function is then used to parse the records and generate a CRL | [
"NewCRLFromDB",
"takes",
"in",
"a",
"list",
"of",
"CertificateRecords",
"as",
"well",
"as",
"the",
"issuing",
"certificate",
"of",
"the",
"CRL",
"and",
"the",
"private",
"key",
".",
"This",
"function",
"is",
"then",
"used",
"to",
"parse",
"the",
"records",
... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/crl/crl.go#L79-L96 |
161,563 | cloudflare/cfssl | crl/crl.go | CreateGenericCRL | func CreateGenericCRL(certList []pkix.RevokedCertificate, key crypto.Signer, issuingCert *x509.Certificate, expiryTime time.Time) ([]byte, error) {
crlBytes, err := issuingCert.CreateCRL(rand.Reader, key, certList, time.Now(), expiryTime)
if err != nil {
log.Debug("error creating CRL: %s", err)
}
return crlBytes, err
} | go | func CreateGenericCRL(certList []pkix.RevokedCertificate, key crypto.Signer, issuingCert *x509.Certificate, expiryTime time.Time) ([]byte, error) {
crlBytes, err := issuingCert.CreateCRL(rand.Reader, key, certList, time.Now(), expiryTime)
if err != nil {
log.Debug("error creating CRL: %s", err)
}
return crlBytes, err
} | [
"func",
"CreateGenericCRL",
"(",
"certList",
"[",
"]",
"pkix",
".",
"RevokedCertificate",
",",
"key",
"crypto",
".",
"Signer",
",",
"issuingCert",
"*",
"x509",
".",
"Certificate",
",",
"expiryTime",
"time",
".",
"Time",
")",
"(",
"[",
"]",
"byte",
",",
"... | // CreateGenericCRL is a helper function that takes in all of the information above, and then calls the createCRL
// function. This outputs the bytes of the created CRL. | [
"CreateGenericCRL",
"is",
"a",
"helper",
"function",
"that",
"takes",
"in",
"all",
"of",
"the",
"information",
"above",
"and",
"then",
"calls",
"the",
"createCRL",
"function",
".",
"This",
"outputs",
"the",
"bytes",
"of",
"the",
"created",
"CRL",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/crl/crl.go#L100-L108 |
161,564 | cloudflare/cfssl | transport/kp/key_provider.go | NewStandardProvider | func NewStandardProvider(id *core.Identity) (*StandardProvider, error) {
if id == nil {
return nil, errors.New("transport: the identity hasn't been initialised. Has it been loaded from disk?")
}
paths := id.Profiles["paths"]
if paths == nil {
return &StandardProvider{}, nil
}
sp := &StandardProvider{
Paths: StandardPaths{
KeyFile: paths["private_key"],
CertFile: paths["certificate"],
},
}
err := sp.Check()
if err != nil {
return nil, err
}
return sp, nil
} | go | func NewStandardProvider(id *core.Identity) (*StandardProvider, error) {
if id == nil {
return nil, errors.New("transport: the identity hasn't been initialised. Has it been loaded from disk?")
}
paths := id.Profiles["paths"]
if paths == nil {
return &StandardProvider{}, nil
}
sp := &StandardProvider{
Paths: StandardPaths{
KeyFile: paths["private_key"],
CertFile: paths["certificate"],
},
}
err := sp.Check()
if err != nil {
return nil, err
}
return sp, nil
} | [
"func",
"NewStandardProvider",
"(",
"id",
"*",
"core",
".",
"Identity",
")",
"(",
"*",
"StandardProvider",
",",
"error",
")",
"{",
"if",
"id",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"p... | // NewStandardProvider sets up new StandardProvider from the
// information contained in an Identity. | [
"NewStandardProvider",
"sets",
"up",
"new",
"StandardProvider",
"from",
"the",
"information",
"contained",
"in",
"an",
"Identity",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L120-L143 |
161,565 | cloudflare/cfssl | transport/kp/key_provider.go | Check | func (sp *StandardProvider) Check() error {
if sp.Paths.KeyFile == "" && sp.Paths.CertFile == "" {
return nil
}
if sp.Paths.KeyFile == "" {
return ErrMissingKeyPath
}
if sp.Paths.CertFile == "" {
return ErrMissingCertPath
}
return nil
} | go | func (sp *StandardProvider) Check() error {
if sp.Paths.KeyFile == "" && sp.Paths.CertFile == "" {
return nil
}
if sp.Paths.KeyFile == "" {
return ErrMissingKeyPath
}
if sp.Paths.CertFile == "" {
return ErrMissingCertPath
}
return nil
} | [
"func",
"(",
"sp",
"*",
"StandardProvider",
")",
"Check",
"(",
")",
"error",
"{",
"if",
"sp",
".",
"Paths",
".",
"KeyFile",
"==",
"\"",
"\"",
"&&",
"sp",
".",
"Paths",
".",
"CertFile",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"i... | // Check ensures that the paths are valid for the provider. | [
"Check",
"ensures",
"that",
"the",
"paths",
"are",
"valid",
"for",
"the",
"provider",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L166-L180 |
161,566 | cloudflare/cfssl | transport/kp/key_provider.go | Persistent | func (sp *StandardProvider) Persistent() bool {
return sp.Paths.KeyFile != "" && sp.Paths.CertFile != ""
} | go | func (sp *StandardProvider) Persistent() bool {
return sp.Paths.KeyFile != "" && sp.Paths.CertFile != ""
} | [
"func",
"(",
"sp",
"*",
"StandardProvider",
")",
"Persistent",
"(",
")",
"bool",
"{",
"return",
"sp",
".",
"Paths",
".",
"KeyFile",
"!=",
"\"",
"\"",
"&&",
"sp",
".",
"Paths",
".",
"CertFile",
"!=",
"\"",
"\"",
"\n",
"}"
] | // Persistent returns true if the key and certificate will be stored
// on disk. | [
"Persistent",
"returns",
"true",
"if",
"the",
"key",
"and",
"certificate",
"will",
"be",
"stored",
"on",
"disk",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L184-L186 |
161,567 | cloudflare/cfssl | transport/kp/key_provider.go | Generate | func (sp *StandardProvider) Generate(algo string, size int) (err error) {
sp.resetKey()
sp.resetCert()
algo = strings.ToLower(algo)
switch algo {
case "rsa":
var priv *rsa.PrivateKey
if size < 2048 {
return errors.New("transport: RSA keys must be at least 2048 bits")
}
priv, err = rsa.GenerateKey(rand.Reader, size)
if err != nil {
return err
}
keyPEM := x509.MarshalPKCS1PrivateKey(priv)
p := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: keyPEM,
}
sp.internal.keyPEM = pem.EncodeToMemory(p)
sp.internal.priv = priv
case "ecdsa":
var priv *ecdsa.PrivateKey
var curve elliptic.Curve
switch size {
case curveP256:
curve = elliptic.P256()
case curveP384:
curve = elliptic.P384()
case curveP521:
curve = elliptic.P521()
default:
return errors.New("transport: invalid elliptic curve key size; only 256-, 384-, and 521-bit keys are accepted")
}
priv, err = ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return err
}
var keyPEM []byte
keyPEM, err = x509.MarshalECPrivateKey(priv)
if err != nil {
return err
}
p := &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: keyPEM,
}
sp.internal.keyPEM = pem.EncodeToMemory(p)
sp.internal.priv = priv
default:
return errors.New("transport: invalid key algorithm; only RSA and ECDSA are supported")
}
return nil
} | go | func (sp *StandardProvider) Generate(algo string, size int) (err error) {
sp.resetKey()
sp.resetCert()
algo = strings.ToLower(algo)
switch algo {
case "rsa":
var priv *rsa.PrivateKey
if size < 2048 {
return errors.New("transport: RSA keys must be at least 2048 bits")
}
priv, err = rsa.GenerateKey(rand.Reader, size)
if err != nil {
return err
}
keyPEM := x509.MarshalPKCS1PrivateKey(priv)
p := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: keyPEM,
}
sp.internal.keyPEM = pem.EncodeToMemory(p)
sp.internal.priv = priv
case "ecdsa":
var priv *ecdsa.PrivateKey
var curve elliptic.Curve
switch size {
case curveP256:
curve = elliptic.P256()
case curveP384:
curve = elliptic.P384()
case curveP521:
curve = elliptic.P521()
default:
return errors.New("transport: invalid elliptic curve key size; only 256-, 384-, and 521-bit keys are accepted")
}
priv, err = ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return err
}
var keyPEM []byte
keyPEM, err = x509.MarshalECPrivateKey(priv)
if err != nil {
return err
}
p := &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: keyPEM,
}
sp.internal.keyPEM = pem.EncodeToMemory(p)
sp.internal.priv = priv
default:
return errors.New("transport: invalid key algorithm; only RSA and ECDSA are supported")
}
return nil
} | [
"func",
"(",
"sp",
"*",
"StandardProvider",
")",
"Generate",
"(",
"algo",
"string",
",",
"size",
"int",
")",
"(",
"err",
"error",
")",
"{",
"sp",
".",
"resetKey",
"(",
")",
"\n",
"sp",
".",
"resetCert",
"(",
")",
"\n\n",
"algo",
"=",
"strings",
"."... | // Generate generates a new private key. | [
"Generate",
"generates",
"a",
"new",
"private",
"key",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L189-L250 |
161,568 | cloudflare/cfssl | transport/kp/key_provider.go | CertificateRequest | func (sp *StandardProvider) CertificateRequest(req *csr.CertificateRequest) ([]byte, error) {
if sp.internal.priv == nil {
if req.KeyRequest == nil {
return nil, errors.New("transport: invalid key request in csr.CertificateRequest")
}
sp.Generate(req.KeyRequest.Algo(), req.KeyRequest.Size())
}
return csr.Generate(sp.internal.priv, req)
} | go | func (sp *StandardProvider) CertificateRequest(req *csr.CertificateRequest) ([]byte, error) {
if sp.internal.priv == nil {
if req.KeyRequest == nil {
return nil, errors.New("transport: invalid key request in csr.CertificateRequest")
}
sp.Generate(req.KeyRequest.Algo(), req.KeyRequest.Size())
}
return csr.Generate(sp.internal.priv, req)
} | [
"func",
"(",
"sp",
"*",
"StandardProvider",
")",
"CertificateRequest",
"(",
"req",
"*",
"csr",
".",
"CertificateRequest",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"sp",
".",
"internal",
".",
"priv",
"==",
"nil",
"{",
"if",
"req",
"."... | // CertificateRequest takes some metadata about a certificate request,
// and attempts to produce a certificate signing request suitable for
// sending to a certificate authority. | [
"CertificateRequest",
"takes",
"some",
"metadata",
"about",
"a",
"certificate",
"request",
"and",
"attempts",
"to",
"produce",
"a",
"certificate",
"signing",
"request",
"suitable",
"for",
"sending",
"to",
"a",
"certificate",
"authority",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L261-L269 |
161,569 | cloudflare/cfssl | transport/kp/key_provider.go | Load | func (sp *StandardProvider) Load() (err error) {
if !sp.Persistent() {
return
}
var clearKey = true
defer func() {
if err != nil {
if clearKey {
sp.resetKey()
}
sp.resetCert()
}
}()
sp.internal.keyPEM, err = ioutil.ReadFile(sp.Paths.KeyFile)
if err != nil {
return
}
sp.internal.priv, err = helpers.ParsePrivateKeyPEM(sp.internal.keyPEM)
if err != nil {
return
}
clearKey = false
sp.internal.certPEM, err = ioutil.ReadFile(sp.Paths.CertFile)
if err != nil {
return ErrCertificateUnavailable
}
sp.internal.cert, err = helpers.ParseCertificatePEM(sp.internal.certPEM)
if err != nil {
err = errors.New("transport: invalid certificate")
return
}
p, _ := pem.Decode(sp.internal.keyPEM)
switch sp.internal.cert.PublicKey.(type) {
case *rsa.PublicKey:
if p.Type != "RSA PRIVATE KEY" {
err = errors.New("transport: PEM type " + p.Type + " is invalid for an RSA key")
return
}
case *ecdsa.PublicKey:
if p.Type != "EC PRIVATE KEY" {
err = errors.New("transport: PEM type " + p.Type + " is invalid for an ECDSA key")
return
}
default:
err = errors.New("transport: invalid public key type")
}
if err != nil {
clearKey = true
return
}
return nil
} | go | func (sp *StandardProvider) Load() (err error) {
if !sp.Persistent() {
return
}
var clearKey = true
defer func() {
if err != nil {
if clearKey {
sp.resetKey()
}
sp.resetCert()
}
}()
sp.internal.keyPEM, err = ioutil.ReadFile(sp.Paths.KeyFile)
if err != nil {
return
}
sp.internal.priv, err = helpers.ParsePrivateKeyPEM(sp.internal.keyPEM)
if err != nil {
return
}
clearKey = false
sp.internal.certPEM, err = ioutil.ReadFile(sp.Paths.CertFile)
if err != nil {
return ErrCertificateUnavailable
}
sp.internal.cert, err = helpers.ParseCertificatePEM(sp.internal.certPEM)
if err != nil {
err = errors.New("transport: invalid certificate")
return
}
p, _ := pem.Decode(sp.internal.keyPEM)
switch sp.internal.cert.PublicKey.(type) {
case *rsa.PublicKey:
if p.Type != "RSA PRIVATE KEY" {
err = errors.New("transport: PEM type " + p.Type + " is invalid for an RSA key")
return
}
case *ecdsa.PublicKey:
if p.Type != "EC PRIVATE KEY" {
err = errors.New("transport: PEM type " + p.Type + " is invalid for an ECDSA key")
return
}
default:
err = errors.New("transport: invalid public key type")
}
if err != nil {
clearKey = true
return
}
return nil
} | [
"func",
"(",
"sp",
"*",
"StandardProvider",
")",
"Load",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"!",
"sp",
".",
"Persistent",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"clearKey",
"=",
"true",
"\n",
"defer",
"func",
"(",
")",
"{"... | // Load a private key and certificate from disk. | [
"Load",
"a",
"private",
"key",
"and",
"certificate",
"from",
"disk",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L276-L337 |
161,570 | cloudflare/cfssl | transport/kp/key_provider.go | Ready | func (sp *StandardProvider) Ready() bool {
switch {
case sp.internal.priv == nil:
return false
case sp.internal.cert == nil:
return false
case sp.internal.keyPEM == nil:
return false
case sp.internal.certPEM == nil:
return false
default:
return true
}
} | go | func (sp *StandardProvider) Ready() bool {
switch {
case sp.internal.priv == nil:
return false
case sp.internal.cert == nil:
return false
case sp.internal.keyPEM == nil:
return false
case sp.internal.certPEM == nil:
return false
default:
return true
}
} | [
"func",
"(",
"sp",
"*",
"StandardProvider",
")",
"Ready",
"(",
")",
"bool",
"{",
"switch",
"{",
"case",
"sp",
".",
"internal",
".",
"priv",
"==",
"nil",
":",
"return",
"false",
"\n",
"case",
"sp",
".",
"internal",
".",
"cert",
"==",
"nil",
":",
"re... | // Ready returns true if the provider has a key and certificate
// loaded. The certificate should be checked by the end user for
// validity. | [
"Ready",
"returns",
"true",
"if",
"the",
"provider",
"has",
"a",
"key",
"and",
"certificate",
"loaded",
".",
"The",
"certificate",
"should",
"be",
"checked",
"by",
"the",
"end",
"user",
"for",
"validity",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L342-L355 |
161,571 | cloudflare/cfssl | transport/kp/key_provider.go | SetCertificatePEM | func (sp *StandardProvider) SetCertificatePEM(certPEM []byte) error {
cert, err := helpers.ParseCertificatePEM(certPEM)
if err != nil {
return errors.New("transport: invalid certificate")
}
sp.internal.certPEM = certPEM
sp.internal.cert = cert
return nil
} | go | func (sp *StandardProvider) SetCertificatePEM(certPEM []byte) error {
cert, err := helpers.ParseCertificatePEM(certPEM)
if err != nil {
return errors.New("transport: invalid certificate")
}
sp.internal.certPEM = certPEM
sp.internal.cert = cert
return nil
} | [
"func",
"(",
"sp",
"*",
"StandardProvider",
")",
"SetCertificatePEM",
"(",
"certPEM",
"[",
"]",
"byte",
")",
"error",
"{",
"cert",
",",
"err",
":=",
"helpers",
".",
"ParseCertificatePEM",
"(",
"certPEM",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return"... | // SetCertificatePEM receives a PEM-encoded certificate and loads it
// into the provider. | [
"SetCertificatePEM",
"receives",
"a",
"PEM",
"-",
"encoded",
"certificate",
"and",
"loads",
"it",
"into",
"the",
"provider",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L359-L368 |
161,572 | cloudflare/cfssl | transport/kp/key_provider.go | SignCSR | func (sp *StandardProvider) SignCSR(tpl *x509.CertificateRequest) ([]byte, error) {
return x509.CreateCertificateRequest(rand.Reader, tpl, sp.internal.priv)
} | go | func (sp *StandardProvider) SignCSR(tpl *x509.CertificateRequest) ([]byte, error) {
return x509.CreateCertificateRequest(rand.Reader, tpl, sp.internal.priv)
} | [
"func",
"(",
"sp",
"*",
"StandardProvider",
")",
"SignCSR",
"(",
"tpl",
"*",
"x509",
".",
"CertificateRequest",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"x509",
".",
"CreateCertificateRequest",
"(",
"rand",
".",
"Reader",
",",
"tpl",... | // SignCSR takes a template certificate request and signs it. | [
"SignCSR",
"takes",
"a",
"template",
"certificate",
"request",
"and",
"signs",
"it",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L377-L379 |
161,573 | cloudflare/cfssl | transport/kp/key_provider.go | Store | func (sp *StandardProvider) Store() error {
if !sp.Ready() {
return errors.New("transport: provider does not have a key and certificate")
}
err := ioutil.WriteFile(sp.Paths.CertFile, sp.internal.certPEM, 0644)
if err != nil {
return err
}
return ioutil.WriteFile(sp.Paths.KeyFile, sp.internal.keyPEM, 0600)
} | go | func (sp *StandardProvider) Store() error {
if !sp.Ready() {
return errors.New("transport: provider does not have a key and certificate")
}
err := ioutil.WriteFile(sp.Paths.CertFile, sp.internal.certPEM, 0644)
if err != nil {
return err
}
return ioutil.WriteFile(sp.Paths.KeyFile, sp.internal.keyPEM, 0600)
} | [
"func",
"(",
"sp",
"*",
"StandardProvider",
")",
"Store",
"(",
")",
"error",
"{",
"if",
"!",
"sp",
".",
"Ready",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",... | // Store writes the key and certificate to disk, if necessary. | [
"Store",
"writes",
"the",
"key",
"and",
"certificate",
"to",
"disk",
"if",
"necessary",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L382-L393 |
161,574 | cloudflare/cfssl | transport/kp/key_provider.go | X509KeyPair | func (sp *StandardProvider) X509KeyPair() (tls.Certificate, error) {
cert, err := tls.X509KeyPair(sp.internal.certPEM, sp.internal.keyPEM)
if err != nil {
return tls.Certificate{}, err
}
if cert.Leaf == nil {
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return tls.Certificate{}, err
}
}
return cert, nil
} | go | func (sp *StandardProvider) X509KeyPair() (tls.Certificate, error) {
cert, err := tls.X509KeyPair(sp.internal.certPEM, sp.internal.keyPEM)
if err != nil {
return tls.Certificate{}, err
}
if cert.Leaf == nil {
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return tls.Certificate{}, err
}
}
return cert, nil
} | [
"func",
"(",
"sp",
"*",
"StandardProvider",
")",
"X509KeyPair",
"(",
")",
"(",
"tls",
".",
"Certificate",
",",
"error",
")",
"{",
"cert",
",",
"err",
":=",
"tls",
".",
"X509KeyPair",
"(",
"sp",
".",
"internal",
".",
"certPEM",
",",
"sp",
".",
"intern... | // X509KeyPair returns a tls.Certificate for the provider. | [
"X509KeyPair",
"returns",
"a",
"tls",
".",
"Certificate",
"for",
"the",
"provider",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/kp/key_provider.go#L396-L409 |
161,575 | cloudflare/cfssl | transport/roots/system/root_windows.go | extractSimpleChain | func extractSimpleChain(simpleChain **syscall.CertSimpleChain, count int) (chain []*Certificate, err error) {
if simpleChain == nil || count == 0 {
return nil, errors.New("x509: invalid simple chain")
}
simpleChains := (*[1 << 20]*syscall.CertSimpleChain)(unsafe.Pointer(simpleChain))[:]
lastChain := simpleChains[count-1]
elements := (*[1 << 20]*syscall.CertChainElement)(unsafe.Pointer(lastChain.Elements))[:]
for i := 0; i < int(lastChain.NumElements); i++ {
// Copy the buf, since ParseCertificate does not create its own copy.
cert := elements[i].CertContext
encodedCert := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:]
buf := make([]byte, cert.Length)
copy(buf, encodedCert[:])
parsedCert, err := ParseCertificate(buf)
if err != nil {
return nil, err
}
chain = append(chain, parsedCert)
}
return chain, nil
} | go | func extractSimpleChain(simpleChain **syscall.CertSimpleChain, count int) (chain []*Certificate, err error) {
if simpleChain == nil || count == 0 {
return nil, errors.New("x509: invalid simple chain")
}
simpleChains := (*[1 << 20]*syscall.CertSimpleChain)(unsafe.Pointer(simpleChain))[:]
lastChain := simpleChains[count-1]
elements := (*[1 << 20]*syscall.CertChainElement)(unsafe.Pointer(lastChain.Elements))[:]
for i := 0; i < int(lastChain.NumElements); i++ {
// Copy the buf, since ParseCertificate does not create its own copy.
cert := elements[i].CertContext
encodedCert := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:]
buf := make([]byte, cert.Length)
copy(buf, encodedCert[:])
parsedCert, err := ParseCertificate(buf)
if err != nil {
return nil, err
}
chain = append(chain, parsedCert)
}
return chain, nil
} | [
"func",
"extractSimpleChain",
"(",
"simpleChain",
"*",
"*",
"syscall",
".",
"CertSimpleChain",
",",
"count",
"int",
")",
"(",
"chain",
"[",
"]",
"*",
"Certificate",
",",
"err",
"error",
")",
"{",
"if",
"simpleChain",
"==",
"nil",
"||",
"count",
"==",
"0"... | // extractSimpleChain extracts the final certificate chain from a CertSimpleChain. | [
"extractSimpleChain",
"extracts",
"the",
"final",
"certificate",
"chain",
"from",
"a",
"CertSimpleChain",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/roots/system/root_windows.go#L60-L82 |
161,576 | cloudflare/cfssl | transport/roots/system/root_windows.go | checkChainTrustStatus | func checkChainTrustStatus(c *Certificate, chainCtx *syscall.CertChainContext) error {
if chainCtx.TrustStatus.ErrorStatus != syscall.CERT_TRUST_NO_ERROR {
status := chainCtx.TrustStatus.ErrorStatus
switch status {
case syscall.CERT_TRUST_IS_NOT_TIME_VALID:
return CertificateInvalidError{c, Expired}
default:
return UnknownAuthorityError{c, nil, nil}
}
}
return nil
} | go | func checkChainTrustStatus(c *Certificate, chainCtx *syscall.CertChainContext) error {
if chainCtx.TrustStatus.ErrorStatus != syscall.CERT_TRUST_NO_ERROR {
status := chainCtx.TrustStatus.ErrorStatus
switch status {
case syscall.CERT_TRUST_IS_NOT_TIME_VALID:
return CertificateInvalidError{c, Expired}
default:
return UnknownAuthorityError{c, nil, nil}
}
}
return nil
} | [
"func",
"checkChainTrustStatus",
"(",
"c",
"*",
"Certificate",
",",
"chainCtx",
"*",
"syscall",
".",
"CertChainContext",
")",
"error",
"{",
"if",
"chainCtx",
".",
"TrustStatus",
".",
"ErrorStatus",
"!=",
"syscall",
".",
"CERT_TRUST_NO_ERROR",
"{",
"status",
":="... | // checkChainTrustStatus checks the trust status of the certificate chain, translating
// any errors it finds into Go errors in the process. | [
"checkChainTrustStatus",
"checks",
"the",
"trust",
"status",
"of",
"the",
"certificate",
"chain",
"translating",
"any",
"errors",
"it",
"finds",
"into",
"Go",
"errors",
"in",
"the",
"process",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/roots/system/root_windows.go#L86-L97 |
161,577 | cloudflare/cfssl | scan/crypto/tls/handshake_client.go | clientSessionCacheKey | func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
if len(config.ServerName) > 0 {
return config.ServerName
}
return serverAddr.String()
} | go | func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
if len(config.ServerName) > 0 {
return config.ServerName
}
return serverAddr.String()
} | [
"func",
"clientSessionCacheKey",
"(",
"serverAddr",
"net",
".",
"Addr",
",",
"config",
"*",
"Config",
")",
"string",
"{",
"if",
"len",
"(",
"config",
".",
"ServerName",
")",
">",
"0",
"{",
"return",
"config",
".",
"ServerName",
"\n",
"}",
"\n",
"return",... | // clientSessionCacheKey returns a key used to cache sessionTickets that could
// be used to resume previously negotiated TLS sessions with a server. | [
"clientSessionCacheKey",
"returns",
"a",
"key",
"used",
"to",
"cache",
"sessionTickets",
"that",
"could",
"be",
"used",
"to",
"resume",
"previously",
"negotiated",
"TLS",
"sessions",
"with",
"a",
"server",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/handshake_client.go#L646-L651 |
161,578 | cloudflare/cfssl | scan/crypto/tls/handshake_client.go | mutualProtocol | func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
for _, s := range preferenceProtos {
for _, c := range protos {
if s == c {
return s, false
}
}
}
return protos[0], true
} | go | func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
for _, s := range preferenceProtos {
for _, c := range protos {
if s == c {
return s, false
}
}
}
return protos[0], true
} | [
"func",
"mutualProtocol",
"(",
"protos",
",",
"preferenceProtos",
"[",
"]",
"string",
")",
"(",
"string",
",",
"bool",
")",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"preferenceProtos",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"protos",
"{",
"if",
"... | // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
// given list of possible protocols and a list of the preference order. The
// first list must not be empty. It returns the resulting protocol and flag
// indicating if the fallback case was reached. | [
"mutualProtocol",
"finds",
"the",
"mutual",
"Next",
"Protocol",
"Negotiation",
"or",
"ALPN",
"protocol",
"given",
"list",
"of",
"possible",
"protocols",
"and",
"a",
"list",
"of",
"the",
"preference",
"order",
".",
"The",
"first",
"list",
"must",
"not",
"be",
... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/handshake_client.go#L657-L667 |
161,579 | cloudflare/cfssl | scan/crypto/tls/handshake_server.go | serverHandshake | func (c *Conn) serverHandshake() error {
config := c.config
// If this is the first server handshake, we generate a random key to
// encrypt the tickets with.
config.serverInitOnce.Do(config.serverInit)
hs := serverHandshakeState{
c: c,
}
isResume, err := hs.readClientHello()
if err != nil {
return err
}
// For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
if isResume {
// The client has included a session ticket and so we do an abbreviated handshake.
if err := hs.doResumeHandshake(); err != nil {
return err
}
if err := hs.establishKeys(); err != nil {
return err
}
// ticketSupported is set in a resumption handshake if the
// ticket from the client was encrypted with an old session
// ticket key and thus a refreshed ticket should be sent.
if hs.hello.ticketSupported {
if err := hs.sendSessionTicket(); err != nil {
return err
}
}
if err := hs.sendFinished(c.firstFinished[:]); err != nil {
return err
}
if err := hs.readFinished(nil); err != nil {
return err
}
c.didResume = true
} else {
// The client didn't include a session ticket, or it wasn't
// valid so we do a full handshake.
if err := hs.doFullHandshake(); err != nil {
return err
}
if err := hs.establishKeys(); err != nil {
return err
}
if err := hs.readFinished(c.firstFinished[:]); err != nil {
return err
}
if err := hs.sendSessionTicket(); err != nil {
return err
}
if err := hs.sendFinished(nil); err != nil {
return err
}
}
c.handshakeComplete = true
return nil
} | go | func (c *Conn) serverHandshake() error {
config := c.config
// If this is the first server handshake, we generate a random key to
// encrypt the tickets with.
config.serverInitOnce.Do(config.serverInit)
hs := serverHandshakeState{
c: c,
}
isResume, err := hs.readClientHello()
if err != nil {
return err
}
// For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
if isResume {
// The client has included a session ticket and so we do an abbreviated handshake.
if err := hs.doResumeHandshake(); err != nil {
return err
}
if err := hs.establishKeys(); err != nil {
return err
}
// ticketSupported is set in a resumption handshake if the
// ticket from the client was encrypted with an old session
// ticket key and thus a refreshed ticket should be sent.
if hs.hello.ticketSupported {
if err := hs.sendSessionTicket(); err != nil {
return err
}
}
if err := hs.sendFinished(c.firstFinished[:]); err != nil {
return err
}
if err := hs.readFinished(nil); err != nil {
return err
}
c.didResume = true
} else {
// The client didn't include a session ticket, or it wasn't
// valid so we do a full handshake.
if err := hs.doFullHandshake(); err != nil {
return err
}
if err := hs.establishKeys(); err != nil {
return err
}
if err := hs.readFinished(c.firstFinished[:]); err != nil {
return err
}
if err := hs.sendSessionTicket(); err != nil {
return err
}
if err := hs.sendFinished(nil); err != nil {
return err
}
}
c.handshakeComplete = true
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"serverHandshake",
"(",
")",
"error",
"{",
"config",
":=",
"c",
".",
"config",
"\n\n",
"// If this is the first server handshake, we generate a random key to",
"// encrypt the tickets with.",
"config",
".",
"serverInitOnce",
".",
"Do"... | // serverHandshake performs a TLS handshake as a server. | [
"serverHandshake",
"performs",
"a",
"TLS",
"handshake",
"as",
"a",
"server",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/handshake_server.go#L38-L99 |
161,580 | cloudflare/cfssl | scan/crypto/tls/handshake_server.go | checkForResumption | func (hs *serverHandshakeState) checkForResumption() bool {
c := hs.c
if c.config.SessionTicketsDisabled {
return false
}
var ok bool
var sessionTicket = append([]uint8{}, hs.clientHello.sessionTicket...)
if hs.sessionState, ok = c.decryptTicket(sessionTicket); !ok {
return false
}
if hs.sessionState.vers > hs.clientHello.vers {
return false
}
if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
return false
}
cipherSuiteOk := false
// Check that the client is still offering the ciphersuite in the session.
for _, id := range hs.clientHello.cipherSuites {
if id == hs.sessionState.cipherSuite {
cipherSuiteOk = true
break
}
}
if !cipherSuiteOk {
return false
}
// Check that we also support the ciphersuite from the session.
if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
return false
}
sessionHasClientCerts := len(hs.sessionState.certificates) != 0
needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
if needClientCerts && !sessionHasClientCerts {
return false
}
if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
return false
}
return true
} | go | func (hs *serverHandshakeState) checkForResumption() bool {
c := hs.c
if c.config.SessionTicketsDisabled {
return false
}
var ok bool
var sessionTicket = append([]uint8{}, hs.clientHello.sessionTicket...)
if hs.sessionState, ok = c.decryptTicket(sessionTicket); !ok {
return false
}
if hs.sessionState.vers > hs.clientHello.vers {
return false
}
if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
return false
}
cipherSuiteOk := false
// Check that the client is still offering the ciphersuite in the session.
for _, id := range hs.clientHello.cipherSuites {
if id == hs.sessionState.cipherSuite {
cipherSuiteOk = true
break
}
}
if !cipherSuiteOk {
return false
}
// Check that we also support the ciphersuite from the session.
if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
return false
}
sessionHasClientCerts := len(hs.sessionState.certificates) != 0
needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
if needClientCerts && !sessionHasClientCerts {
return false
}
if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
return false
}
return true
} | [
"func",
"(",
"hs",
"*",
"serverHandshakeState",
")",
"checkForResumption",
"(",
")",
"bool",
"{",
"c",
":=",
"hs",
".",
"c",
"\n\n",
"if",
"c",
".",
"config",
".",
"SessionTicketsDisabled",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"var",
"ok",
"bool",
... | // checkForResumption reports whether we should perform resumption on this connection. | [
"checkForResumption",
"reports",
"whether",
"we",
"should",
"perform",
"resumption",
"on",
"this",
"connection",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/handshake_server.go#L264-L311 |
161,581 | cloudflare/cfssl | scan/crypto/tls/handshake_server.go | processCertsFromClient | func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
c := hs.c
hs.certsFromClient = certificates
certs := make([]*x509.Certificate, len(certificates))
var err error
for i, asn1Data := range certificates {
if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
c.sendAlert(alertBadCertificate)
return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
}
}
if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
opts := x509.VerifyOptions{
Roots: c.config.ClientCAs,
CurrentTime: c.config.time(),
Intermediates: x509.NewCertPool(),
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
}
for _, cert := range certs[1:] {
opts.Intermediates.AddCert(cert)
}
chains, err := certs[0].Verify(opts)
if err != nil {
c.sendAlert(alertBadCertificate)
return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
}
c.verifiedChains = chains
}
if len(certs) > 0 {
var pub crypto.PublicKey
switch key := certs[0].PublicKey.(type) {
case *ecdsa.PublicKey, *rsa.PublicKey:
pub = key
default:
c.sendAlert(alertUnsupportedCertificate)
return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
}
c.peerCertificates = certs
return pub, nil
}
return nil, nil
} | go | func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
c := hs.c
hs.certsFromClient = certificates
certs := make([]*x509.Certificate, len(certificates))
var err error
for i, asn1Data := range certificates {
if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
c.sendAlert(alertBadCertificate)
return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
}
}
if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
opts := x509.VerifyOptions{
Roots: c.config.ClientCAs,
CurrentTime: c.config.time(),
Intermediates: x509.NewCertPool(),
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
}
for _, cert := range certs[1:] {
opts.Intermediates.AddCert(cert)
}
chains, err := certs[0].Verify(opts)
if err != nil {
c.sendAlert(alertBadCertificate)
return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
}
c.verifiedChains = chains
}
if len(certs) > 0 {
var pub crypto.PublicKey
switch key := certs[0].PublicKey.(type) {
case *ecdsa.PublicKey, *rsa.PublicKey:
pub = key
default:
c.sendAlert(alertUnsupportedCertificate)
return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
}
c.peerCertificates = certs
return pub, nil
}
return nil, nil
} | [
"func",
"(",
"hs",
"*",
"serverHandshakeState",
")",
"processCertsFromClient",
"(",
"certificates",
"[",
"]",
"[",
"]",
"byte",
")",
"(",
"crypto",
".",
"PublicKey",
",",
"error",
")",
"{",
"c",
":=",
"hs",
".",
"c",
"\n\n",
"hs",
".",
"certsFromClient",... | // processCertsFromClient takes a chain of client certificates either from a
// Certificates message or from a sessionState and verifies them. It returns
// the public key of the leaf certificate. | [
"processCertsFromClient",
"takes",
"a",
"chain",
"of",
"client",
"certificates",
"either",
"from",
"a",
"Certificates",
"message",
"or",
"from",
"a",
"sessionState",
"and",
"verifies",
"them",
".",
"It",
"returns",
"the",
"public",
"key",
"of",
"the",
"leaf",
... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/handshake_server.go#L659-L707 |
161,582 | cloudflare/cfssl | scan/crypto/tls/handshake_server.go | setCipherSuite | func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
for _, supported := range supportedCipherSuites {
if id == supported {
var candidate *cipherSuite
for _, s := range cipherSuites {
if s.id == id {
candidate = s
break
}
}
if candidate == nil {
continue
}
// Don't select a ciphersuite which we can't
// support for this client.
if candidate.flags&suiteECDHE != 0 {
if !hs.ellipticOk {
continue
}
if candidate.flags&suiteECDSA != 0 {
if !hs.ecdsaOk {
continue
}
} else if !hs.rsaSignOk {
continue
}
} else if !hs.rsaDecryptOk {
continue
}
if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
continue
}
hs.suite = candidate
return true
}
}
return false
} | go | func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
for _, supported := range supportedCipherSuites {
if id == supported {
var candidate *cipherSuite
for _, s := range cipherSuites {
if s.id == id {
candidate = s
break
}
}
if candidate == nil {
continue
}
// Don't select a ciphersuite which we can't
// support for this client.
if candidate.flags&suiteECDHE != 0 {
if !hs.ellipticOk {
continue
}
if candidate.flags&suiteECDSA != 0 {
if !hs.ecdsaOk {
continue
}
} else if !hs.rsaSignOk {
continue
}
} else if !hs.rsaDecryptOk {
continue
}
if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
continue
}
hs.suite = candidate
return true
}
}
return false
} | [
"func",
"(",
"hs",
"*",
"serverHandshakeState",
")",
"setCipherSuite",
"(",
"id",
"uint16",
",",
"supportedCipherSuites",
"[",
"]",
"uint16",
",",
"version",
"uint16",
")",
"bool",
"{",
"for",
"_",
",",
"supported",
":=",
"range",
"supportedCipherSuites",
"{",... | // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
// suite if that cipher suite is acceptable to use.
// It returns a bool indicating if the suite was set. | [
"setCipherSuite",
"sets",
"a",
"cipherSuite",
"with",
"the",
"given",
"id",
"as",
"the",
"serverHandshakeState",
"suite",
"if",
"that",
"cipher",
"suite",
"is",
"acceptable",
"to",
"use",
".",
"It",
"returns",
"a",
"bool",
"indicating",
"if",
"the",
"suite",
... | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/handshake_server.go#L712-L750 |
161,583 | cloudflare/cfssl | ubiquity/ubiquity_platform.go | SHA1RawPublicKey | func SHA1RawPublicKey(cert *x509.Certificate) string {
return fmt.Sprintf("%x", sha1.Sum(cert.RawSubjectPublicKeyInfo))
} | go | func SHA1RawPublicKey(cert *x509.Certificate) string {
return fmt.Sprintf("%x", sha1.Sum(cert.RawSubjectPublicKeyInfo))
} | [
"func",
"SHA1RawPublicKey",
"(",
"cert",
"*",
"x509",
".",
"Certificate",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sha1",
".",
"Sum",
"(",
"cert",
".",
"RawSubjectPublicKeyInfo",
")",
")",
"\n",
"}"
] | // SHA1RawPublicKey returns a SHA1 hash of the raw certificate public key | [
"SHA1RawPublicKey",
"returns",
"a",
"SHA1",
"hash",
"of",
"the",
"raw",
"certificate",
"public",
"key"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/ubiquity/ubiquity_platform.go#L21-L23 |
161,584 | cloudflare/cfssl | ubiquity/ubiquity_platform.go | Lookup | func (s CertSet) Lookup(cert *x509.Certificate) bool {
return s[SHA1RawPublicKey(cert)]
} | go | func (s CertSet) Lookup(cert *x509.Certificate) bool {
return s[SHA1RawPublicKey(cert)]
} | [
"func",
"(",
"s",
"CertSet",
")",
"Lookup",
"(",
"cert",
"*",
"x509",
".",
"Certificate",
")",
"bool",
"{",
"return",
"s",
"[",
"SHA1RawPublicKey",
"(",
"cert",
")",
"]",
"\n",
"}"
] | // Lookup returns whether a certificate is stored in the set. | [
"Lookup",
"returns",
"whether",
"a",
"certificate",
"is",
"stored",
"in",
"the",
"set",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/ubiquity/ubiquity_platform.go#L29-L31 |
161,585 | cloudflare/cfssl | ubiquity/ubiquity_platform.go | Add | func (s CertSet) Add(cert *x509.Certificate) {
s[SHA1RawPublicKey(cert)] = true
} | go | func (s CertSet) Add(cert *x509.Certificate) {
s[SHA1RawPublicKey(cert)] = true
} | [
"func",
"(",
"s",
"CertSet",
")",
"Add",
"(",
"cert",
"*",
"x509",
".",
"Certificate",
")",
"{",
"s",
"[",
"SHA1RawPublicKey",
"(",
"cert",
")",
"]",
"=",
"true",
"\n",
"}"
] | // Add adds a certificate to the set. | [
"Add",
"adds",
"a",
"certificate",
"to",
"the",
"set",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/ubiquity/ubiquity_platform.go#L34-L36 |
161,586 | cloudflare/cfssl | ubiquity/ubiquity_platform.go | Trust | func (p Platform) Trust(root *x509.Certificate) bool {
// the key store is empty iff the platform doesn't carry a root store and trust whatever root store
// is supplied. An example is Chrome. Such platforms should not show up in the untrusted platform
// list. So always return true here. Also this won't hurt ubiquity scoring because such platforms give
// no differentiation on root cert selection.
if len(p.KeyStore) == 0 {
return true
}
return p.KeyStore.Lookup(root)
} | go | func (p Platform) Trust(root *x509.Certificate) bool {
// the key store is empty iff the platform doesn't carry a root store and trust whatever root store
// is supplied. An example is Chrome. Such platforms should not show up in the untrusted platform
// list. So always return true here. Also this won't hurt ubiquity scoring because such platforms give
// no differentiation on root cert selection.
if len(p.KeyStore) == 0 {
return true
}
return p.KeyStore.Lookup(root)
} | [
"func",
"(",
"p",
"Platform",
")",
"Trust",
"(",
"root",
"*",
"x509",
".",
"Certificate",
")",
"bool",
"{",
"// the key store is empty iff the platform doesn't carry a root store and trust whatever root store",
"// is supplied. An example is Chrome. Such platforms should not show up ... | // Trust returns whether the platform has the root cert in the trusted store. | [
"Trust",
"returns",
"whether",
"the",
"platform",
"has",
"the",
"root",
"cert",
"in",
"the",
"trusted",
"store",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/ubiquity/ubiquity_platform.go#L51-L61 |
161,587 | cloudflare/cfssl | ubiquity/ubiquity_platform.go | ParseAndLoad | func (p *Platform) ParseAndLoad() (ok bool) {
p.HashUbiquity = p.hashUbiquity()
p.KeyAlgoUbiquity = p.keyAlgoUbiquity()
p.KeyStore = map[string]bool{}
if p.KeyStoreFile != "" {
pemBytes, err := ioutil.ReadFile(p.KeyStoreFile)
if err != nil {
log.Error(err)
return false
}
// Best effort parsing the PEMs such that ignore all borken pem,
// since some of CA certs have negative serial number which trigger errors.
for len(pemBytes) > 0 {
var certs []*x509.Certificate
certs, rest, err := helpers.ParseOneCertificateFromPEM(pemBytes)
// If one certificate object is parsed, possibly a PKCS#7
// structure containing multiple certs, record the raw SHA1 hash(es).
if err == nil && certs != nil {
for _, cert := range certs {
p.KeyStore.Add(cert)
}
}
if len(rest) < len(pemBytes) {
pemBytes = rest
} else {
// No progress in bytes parsing, bail out.
break
}
}
}
if p.HashUbiquity <= UnknownHashUbiquity ||
p.KeyAlgoUbiquity <= UnknownAlgoUbiquity {
return false
}
return true
} | go | func (p *Platform) ParseAndLoad() (ok bool) {
p.HashUbiquity = p.hashUbiquity()
p.KeyAlgoUbiquity = p.keyAlgoUbiquity()
p.KeyStore = map[string]bool{}
if p.KeyStoreFile != "" {
pemBytes, err := ioutil.ReadFile(p.KeyStoreFile)
if err != nil {
log.Error(err)
return false
}
// Best effort parsing the PEMs such that ignore all borken pem,
// since some of CA certs have negative serial number which trigger errors.
for len(pemBytes) > 0 {
var certs []*x509.Certificate
certs, rest, err := helpers.ParseOneCertificateFromPEM(pemBytes)
// If one certificate object is parsed, possibly a PKCS#7
// structure containing multiple certs, record the raw SHA1 hash(es).
if err == nil && certs != nil {
for _, cert := range certs {
p.KeyStore.Add(cert)
}
}
if len(rest) < len(pemBytes) {
pemBytes = rest
} else {
// No progress in bytes parsing, bail out.
break
}
}
}
if p.HashUbiquity <= UnknownHashUbiquity ||
p.KeyAlgoUbiquity <= UnknownAlgoUbiquity {
return false
}
return true
} | [
"func",
"(",
"p",
"*",
"Platform",
")",
"ParseAndLoad",
"(",
")",
"(",
"ok",
"bool",
")",
"{",
"p",
".",
"HashUbiquity",
"=",
"p",
".",
"hashUbiquity",
"(",
")",
"\n",
"p",
".",
"KeyAlgoUbiquity",
"=",
"p",
".",
"keyAlgoUbiquity",
"(",
")",
"\n",
"... | // ParseAndLoad converts HashAlgo and KeyAlgo to corresponding ubiquity value and load
// certificates into internal KeyStore from KeyStoreFiles | [
"ParseAndLoad",
"converts",
"HashAlgo",
"and",
"KeyAlgo",
"to",
"corresponding",
"ubiquity",
"value",
"and",
"load",
"certificates",
"into",
"internal",
"KeyStore",
"from",
"KeyStoreFiles"
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/ubiquity/ubiquity_platform.go#L91-L127 |
161,588 | cloudflare/cfssl | ubiquity/ubiquity_platform.go | LoadPlatforms | func LoadPlatforms(filename string) error {
// if filename is empty, skip the metadata loading
if filename == "" {
return nil
}
relativePath := filepath.Dir(filename)
// Attempt to load root certificate metadata
log.Debug("Loading platform metadata: ", filename)
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return fmt.Errorf("platform metadata failed to load: %v", err)
}
var rawPlatforms []Platform
if bytes != nil {
err = json.Unmarshal(bytes, &rawPlatforms)
if err != nil {
return fmt.Errorf("platform metadata failed to parse: %v", err)
}
}
for _, platform := range rawPlatforms {
if platform.KeyStoreFile != "" {
platform.KeyStoreFile = path.Join(relativePath, platform.KeyStoreFile)
}
ok := platform.ParseAndLoad()
if !ok {
// erase all loaded platforms
Platforms = nil
return fmt.Errorf("fail to finalize the parsing of platform metadata: %v", platform)
}
log.Infof("Platform metadata is loaded: %v %v", platform.Name, len(platform.KeyStore))
Platforms = append(Platforms, platform)
}
return nil
} | go | func LoadPlatforms(filename string) error {
// if filename is empty, skip the metadata loading
if filename == "" {
return nil
}
relativePath := filepath.Dir(filename)
// Attempt to load root certificate metadata
log.Debug("Loading platform metadata: ", filename)
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return fmt.Errorf("platform metadata failed to load: %v", err)
}
var rawPlatforms []Platform
if bytes != nil {
err = json.Unmarshal(bytes, &rawPlatforms)
if err != nil {
return fmt.Errorf("platform metadata failed to parse: %v", err)
}
}
for _, platform := range rawPlatforms {
if platform.KeyStoreFile != "" {
platform.KeyStoreFile = path.Join(relativePath, platform.KeyStoreFile)
}
ok := platform.ParseAndLoad()
if !ok {
// erase all loaded platforms
Platforms = nil
return fmt.Errorf("fail to finalize the parsing of platform metadata: %v", platform)
}
log.Infof("Platform metadata is loaded: %v %v", platform.Name, len(platform.KeyStore))
Platforms = append(Platforms, platform)
}
return nil
} | [
"func",
"LoadPlatforms",
"(",
"filename",
"string",
")",
"error",
"{",
"// if filename is empty, skip the metadata loading",
"if",
"filename",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"relativePath",
":=",
"filepath",
".",
"Dir",
"(",
"filename",... | // LoadPlatforms reads the file content as a json object array and convert it
// to Platforms. | [
"LoadPlatforms",
"reads",
"the",
"file",
"content",
"as",
"a",
"json",
"object",
"array",
"and",
"convert",
"it",
"to",
"Platforms",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/ubiquity/ubiquity_platform.go#L134-L171 |
161,589 | cloudflare/cfssl | ubiquity/ubiquity_platform.go | UntrustedPlatforms | func UntrustedPlatforms(root *x509.Certificate) []string {
ret := []string{}
for _, platform := range Platforms {
if !platform.Trust(root) {
ret = append(ret, platform.Name)
}
}
return ret
} | go | func UntrustedPlatforms(root *x509.Certificate) []string {
ret := []string{}
for _, platform := range Platforms {
if !platform.Trust(root) {
ret = append(ret, platform.Name)
}
}
return ret
} | [
"func",
"UntrustedPlatforms",
"(",
"root",
"*",
"x509",
".",
"Certificate",
")",
"[",
"]",
"string",
"{",
"ret",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"platform",
":=",
"range",
"Platforms",
"{",
"if",
"!",
"platform",
".",
"Trus... | // UntrustedPlatforms returns a list of platforms which don't trust the root certificate. | [
"UntrustedPlatforms",
"returns",
"a",
"list",
"of",
"platforms",
"which",
"don",
"t",
"trust",
"the",
"root",
"certificate",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/ubiquity/ubiquity_platform.go#L174-L182 |
161,590 | cloudflare/cfssl | ubiquity/ubiquity_platform.go | ComparePlatformUbiquity | func ComparePlatformUbiquity(chain1, chain2 []*x509.Certificate) int {
w1 := CrossPlatformUbiquity(chain1)
w2 := CrossPlatformUbiquity(chain2)
return w1 - w2
} | go | func ComparePlatformUbiquity(chain1, chain2 []*x509.Certificate) int {
w1 := CrossPlatformUbiquity(chain1)
w2 := CrossPlatformUbiquity(chain2)
return w1 - w2
} | [
"func",
"ComparePlatformUbiquity",
"(",
"chain1",
",",
"chain2",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"int",
"{",
"w1",
":=",
"CrossPlatformUbiquity",
"(",
"chain1",
")",
"\n",
"w2",
":=",
"CrossPlatformUbiquity",
"(",
"chain2",
")",
"\n",
"return... | // ComparePlatformUbiquity compares the cross-platform ubiquity between chain1 and chain2. | [
"ComparePlatformUbiquity",
"compares",
"the",
"cross",
"-",
"platform",
"ubiquity",
"between",
"chain1",
"and",
"chain2",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/ubiquity/ubiquity_platform.go#L209-L213 |
161,591 | cloudflare/cfssl | whitelist/whitelist.go | Add | func (wl *Basic) Add(ip net.IP) {
if !validIP(ip) {
return
}
wl.lock.Lock()
defer wl.lock.Unlock()
wl.whitelist[ip.String()] = true
} | go | func (wl *Basic) Add(ip net.IP) {
if !validIP(ip) {
return
}
wl.lock.Lock()
defer wl.lock.Unlock()
wl.whitelist[ip.String()] = true
} | [
"func",
"(",
"wl",
"*",
"Basic",
")",
"Add",
"(",
"ip",
"net",
".",
"IP",
")",
"{",
"if",
"!",
"validIP",
"(",
"ip",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"wl",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"wl",
".",
"lock",
".",
"Un... | // Add whitelists an IP. | [
"Add",
"whitelists",
"an",
"IP",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/whitelist.go#L73-L81 |
161,592 | cloudflare/cfssl | whitelist/whitelist.go | Remove | func (wl *Basic) Remove(ip net.IP) {
if !validIP(ip) {
return
}
wl.lock.Lock()
defer wl.lock.Unlock()
delete(wl.whitelist, ip.String())
} | go | func (wl *Basic) Remove(ip net.IP) {
if !validIP(ip) {
return
}
wl.lock.Lock()
defer wl.lock.Unlock()
delete(wl.whitelist, ip.String())
} | [
"func",
"(",
"wl",
"*",
"Basic",
")",
"Remove",
"(",
"ip",
"net",
".",
"IP",
")",
"{",
"if",
"!",
"validIP",
"(",
"ip",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"wl",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"wl",
".",
"lock",
".",
... | // Remove clears the IP from the whitelist. | [
"Remove",
"clears",
"the",
"IP",
"from",
"the",
"whitelist",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/whitelist.go#L84-L92 |
161,593 | cloudflare/cfssl | whitelist/whitelist.go | NewBasic | func NewBasic() *Basic {
return &Basic{
lock: new(sync.Mutex),
whitelist: map[string]bool{},
}
} | go | func NewBasic() *Basic {
return &Basic{
lock: new(sync.Mutex),
whitelist: map[string]bool{},
}
} | [
"func",
"NewBasic",
"(",
")",
"*",
"Basic",
"{",
"return",
"&",
"Basic",
"{",
"lock",
":",
"new",
"(",
"sync",
".",
"Mutex",
")",
",",
"whitelist",
":",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
",",
"}",
"\n",
"}"
] | // NewBasic returns a new initialised basic whitelist. | [
"NewBasic",
"returns",
"a",
"new",
"initialised",
"basic",
"whitelist",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/whitelist.go#L95-L100 |
161,594 | cloudflare/cfssl | whitelist/whitelist.go | MarshalJSON | func (wl *Basic) MarshalJSON() ([]byte, error) {
wl.lock.Lock()
defer wl.lock.Unlock()
var ss = make([]string, 0, len(wl.whitelist))
for ip := range wl.whitelist {
ss = append(ss, ip)
}
out := []byte(`"` + strings.Join(ss, ",") + `"`)
return out, nil
} | go | func (wl *Basic) MarshalJSON() ([]byte, error) {
wl.lock.Lock()
defer wl.lock.Unlock()
var ss = make([]string, 0, len(wl.whitelist))
for ip := range wl.whitelist {
ss = append(ss, ip)
}
out := []byte(`"` + strings.Join(ss, ",") + `"`)
return out, nil
} | [
"func",
"(",
"wl",
"*",
"Basic",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"wl",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"wl",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"var",
"ss",
"=",
"make",... | // MarshalJSON serialises a host whitelist to a comma-separated list of
// hosts, implementing the json.Marshaler interface. | [
"MarshalJSON",
"serialises",
"a",
"host",
"whitelist",
"to",
"a",
"comma",
"-",
"separated",
"list",
"of",
"hosts",
"implementing",
"the",
"json",
".",
"Marshaler",
"interface",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/whitelist.go#L104-L114 |
161,595 | cloudflare/cfssl | whitelist/whitelist.go | UnmarshalJSON | func (wl *Basic) UnmarshalJSON(in []byte) error {
if in[0] != '"' || in[len(in)-1] != '"' {
return errors.New("whitelist: invalid whitelist")
}
if wl.lock == nil {
wl.lock = new(sync.Mutex)
}
wl.lock.Lock()
defer wl.lock.Unlock()
netString := strings.TrimSpace(string(in[1 : len(in)-1]))
nets := strings.Split(netString, ",")
wl.whitelist = map[string]bool{}
for i := range nets {
addr := strings.TrimSpace(nets[i])
if addr == "" {
continue
}
ip := net.ParseIP(addr)
if ip == nil {
wl.whitelist = nil
return errors.New("whitelist: invalid IP address " + addr)
}
wl.whitelist[addr] = true
}
return nil
} | go | func (wl *Basic) UnmarshalJSON(in []byte) error {
if in[0] != '"' || in[len(in)-1] != '"' {
return errors.New("whitelist: invalid whitelist")
}
if wl.lock == nil {
wl.lock = new(sync.Mutex)
}
wl.lock.Lock()
defer wl.lock.Unlock()
netString := strings.TrimSpace(string(in[1 : len(in)-1]))
nets := strings.Split(netString, ",")
wl.whitelist = map[string]bool{}
for i := range nets {
addr := strings.TrimSpace(nets[i])
if addr == "" {
continue
}
ip := net.ParseIP(addr)
if ip == nil {
wl.whitelist = nil
return errors.New("whitelist: invalid IP address " + addr)
}
wl.whitelist[addr] = true
}
return nil
} | [
"func",
"(",
"wl",
"*",
"Basic",
")",
"UnmarshalJSON",
"(",
"in",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"in",
"[",
"0",
"]",
"!=",
"'\"'",
"||",
"in",
"[",
"len",
"(",
"in",
")",
"-",
"1",
"]",
"!=",
"'\"'",
"{",
"return",
"errors",
".",... | // UnmarshalJSON implements the json.Unmarshaler interface for host
// whitelists, taking a comma-separated string of hosts. | [
"UnmarshalJSON",
"implements",
"the",
"json",
".",
"Unmarshaler",
"interface",
"for",
"host",
"whitelists",
"taking",
"a",
"comma",
"-",
"separated",
"string",
"of",
"hosts",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/whitelist.go#L118-L149 |
161,596 | cloudflare/cfssl | whitelist/whitelist.go | DumpBasic | func DumpBasic(wl *Basic) []byte {
wl.lock.Lock()
defer wl.lock.Unlock()
var addrs = make([]string, 0, len(wl.whitelist))
for ip := range wl.whitelist {
addrs = append(addrs, ip)
}
sort.Strings(addrs)
addrList := strings.Join(addrs, "\n")
return []byte(addrList)
} | go | func DumpBasic(wl *Basic) []byte {
wl.lock.Lock()
defer wl.lock.Unlock()
var addrs = make([]string, 0, len(wl.whitelist))
for ip := range wl.whitelist {
addrs = append(addrs, ip)
}
sort.Strings(addrs)
addrList := strings.Join(addrs, "\n")
return []byte(addrList)
} | [
"func",
"DumpBasic",
"(",
"wl",
"*",
"Basic",
")",
"[",
"]",
"byte",
"{",
"wl",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"wl",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"addrs",
"=",
"make",
"(",
"[",
"]",
"string",
",",
... | // DumpBasic returns a whitelist as a byte slice where each IP is on
// its own line. | [
"DumpBasic",
"returns",
"a",
"whitelist",
"as",
"a",
"byte",
"slice",
"where",
"each",
"IP",
"is",
"on",
"its",
"own",
"line",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/whitelist.go#L153-L166 |
161,597 | cloudflare/cfssl | whitelist/whitelist.go | LoadBasic | func LoadBasic(in []byte) (*Basic, error) {
wl := NewBasic()
addrs := strings.Split(string(in), "\n")
for _, addr := range addrs {
ip := net.ParseIP(addr)
if ip == nil {
return nil, errors.New("whitelist: invalid address")
}
wl.Add(ip)
}
return wl, nil
} | go | func LoadBasic(in []byte) (*Basic, error) {
wl := NewBasic()
addrs := strings.Split(string(in), "\n")
for _, addr := range addrs {
ip := net.ParseIP(addr)
if ip == nil {
return nil, errors.New("whitelist: invalid address")
}
wl.Add(ip)
}
return wl, nil
} | [
"func",
"LoadBasic",
"(",
"in",
"[",
"]",
"byte",
")",
"(",
"*",
"Basic",
",",
"error",
")",
"{",
"wl",
":=",
"NewBasic",
"(",
")",
"\n",
"addrs",
":=",
"strings",
".",
"Split",
"(",
"string",
"(",
"in",
")",
",",
"\"",
"\\n",
"\"",
")",
"\n\n"... | // LoadBasic loads a whitelist from a byteslice. | [
"LoadBasic",
"loads",
"a",
"whitelist",
"from",
"a",
"byteslice",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/whitelist.go#L169-L181 |
161,598 | cloudflare/cfssl | whitelist/whitelist.go | Permitted | func (wl HostStub) Permitted(ip net.IP) bool {
log.Printf("WARNING: whitelist check for %s but whitelisting is stubbed", ip)
return true
} | go | func (wl HostStub) Permitted(ip net.IP) bool {
log.Printf("WARNING: whitelist check for %s but whitelisting is stubbed", ip)
return true
} | [
"func",
"(",
"wl",
"HostStub",
")",
"Permitted",
"(",
"ip",
"net",
".",
"IP",
")",
"bool",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"ip",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // Permitted always returns true, but prints a warning message alerting
// that whitelisting is stubbed. | [
"Permitted",
"always",
"returns",
"true",
"but",
"prints",
"a",
"warning",
"message",
"alerting",
"that",
"whitelisting",
"is",
"stubbed",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/whitelist.go#L192-L195 |
161,599 | cloudflare/cfssl | initca/initca.go | validator | func validator(req *csr.CertificateRequest) error {
if req.CN != "" {
return nil
}
if len(req.Names) == 0 {
return cferr.Wrap(cferr.PolicyError, cferr.InvalidRequest, errors.New("missing subject information"))
}
for i := range req.Names {
if csr.IsNameEmpty(req.Names[i]) {
return cferr.Wrap(cferr.PolicyError, cferr.InvalidRequest, errors.New("missing subject information"))
}
}
return nil
} | go | func validator(req *csr.CertificateRequest) error {
if req.CN != "" {
return nil
}
if len(req.Names) == 0 {
return cferr.Wrap(cferr.PolicyError, cferr.InvalidRequest, errors.New("missing subject information"))
}
for i := range req.Names {
if csr.IsNameEmpty(req.Names[i]) {
return cferr.Wrap(cferr.PolicyError, cferr.InvalidRequest, errors.New("missing subject information"))
}
}
return nil
} | [
"func",
"validator",
"(",
"req",
"*",
"csr",
".",
"CertificateRequest",
")",
"error",
"{",
"if",
"req",
".",
"CN",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"req",
".",
"Names",
")",
"==",
"0",
"{",
"return",
"c... | // validator contains the default validation logic for certificate
// authority certificates. The only requirement here is that the
// certificate have a non-empty subject field. | [
"validator",
"contains",
"the",
"default",
"validation",
"logic",
"for",
"certificate",
"authority",
"certificates",
".",
"The",
"only",
"requirement",
"here",
"is",
"that",
"the",
"certificate",
"have",
"a",
"non",
"-",
"empty",
"subject",
"field",
"."
] | 768cd563887febaad559b511aaa5964823ccb4ab | https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/initca/initca.go#L27-L43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.