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
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
src-d/go-git
plumbing/format/config/common.go
Section
func (c *Config) Section(name string) *Section { for i := len(c.Sections) - 1; i >= 0; i-- { s := c.Sections[i] if s.IsName(name) { return s } } s := &Section{Name: name} c.Sections = append(c.Sections, s) return s }
go
func (c *Config) Section(name string) *Section { for i := len(c.Sections) - 1; i >= 0; i-- { s := c.Sections[i] if s.IsName(name) { return s } } s := &Section{Name: name} c.Sections = append(c.Sections, s) return s }
[ "func", "(", "c", "*", "Config", ")", "Section", "(", "name", "string", ")", "*", "Section", "{", "for", "i", ":=", "len", "(", "c", ".", "Sections", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "s", ":=", "c", ".", "Sections", "[", "i", "]", "\n", "if", "s", ".", "IsName", "(", "name", ")", "{", "return", "s", "\n", "}", "\n", "}", "\n\n", "s", ":=", "&", "Section", "{", "Name", ":", "name", "}", "\n", "c", ".", "Sections", "=", "append", "(", "c", ".", "Sections", ",", "s", ")", "\n", "return", "s", "\n", "}" ]
// Section returns a existing section with the given name or creates a new one.
[ "Section", "returns", "a", "existing", "section", "with", "the", "given", "name", "or", "creates", "a", "new", "one", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/plumbing/format/config/common.go#L34-L45
train
src-d/go-git
plumbing/format/config/common.go
AddOption
func (c *Config) AddOption(section string, subsection string, key string, value string) *Config { if subsection == "" { c.Section(section).AddOption(key, value) } else { c.Section(section).Subsection(subsection).AddOption(key, value) } return c }
go
func (c *Config) AddOption(section string, subsection string, key string, value string) *Config { if subsection == "" { c.Section(section).AddOption(key, value) } else { c.Section(section).Subsection(subsection).AddOption(key, value) } return c }
[ "func", "(", "c", "*", "Config", ")", "AddOption", "(", "section", "string", ",", "subsection", "string", ",", "key", "string", ",", "value", "string", ")", "*", "Config", "{", "if", "subsection", "==", "\"", "\"", "{", "c", ".", "Section", "(", "section", ")", ".", "AddOption", "(", "key", ",", "value", ")", "\n", "}", "else", "{", "c", ".", "Section", "(", "section", ")", ".", "Subsection", "(", "subsection", ")", ".", "AddOption", "(", "key", ",", "value", ")", "\n", "}", "\n\n", "return", "c", "\n", "}" ]
// AddOption adds an option to a given section and subsection. Use the // NoSubsection constant for the subsection argument if no subsection is wanted.
[ "AddOption", "adds", "an", "option", "to", "a", "given", "section", "and", "subsection", ".", "Use", "the", "NoSubsection", "constant", "for", "the", "subsection", "argument", "if", "no", "subsection", "is", "wanted", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/plumbing/format/config/common.go#L49-L57
train
src-d/go-git
plumbing/format/config/common.go
RemoveSection
func (c *Config) RemoveSection(name string) *Config { result := Sections{} for _, s := range c.Sections { if !s.IsName(name) { result = append(result, s) } } c.Sections = result return c }
go
func (c *Config) RemoveSection(name string) *Config { result := Sections{} for _, s := range c.Sections { if !s.IsName(name) { result = append(result, s) } } c.Sections = result return c }
[ "func", "(", "c", "*", "Config", ")", "RemoveSection", "(", "name", "string", ")", "*", "Config", "{", "result", ":=", "Sections", "{", "}", "\n", "for", "_", ",", "s", ":=", "range", "c", ".", "Sections", "{", "if", "!", "s", ".", "IsName", "(", "name", ")", "{", "result", "=", "append", "(", "result", ",", "s", ")", "\n", "}", "\n", "}", "\n\n", "c", ".", "Sections", "=", "result", "\n", "return", "c", "\n", "}" ]
// RemoveSection removes a section from a config file.
[ "RemoveSection", "removes", "a", "section", "from", "a", "config", "file", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/plumbing/format/config/common.go#L72-L82
train
src-d/go-git
plumbing/format/config/common.go
RemoveSubsection
func (c *Config) RemoveSubsection(section string, subsection string) *Config { for _, s := range c.Sections { if s.IsName(section) { result := Subsections{} for _, ss := range s.Subsections { if !ss.IsName(subsection) { result = append(result, ss) } } s.Subsections = result } } return c }
go
func (c *Config) RemoveSubsection(section string, subsection string) *Config { for _, s := range c.Sections { if s.IsName(section) { result := Subsections{} for _, ss := range s.Subsections { if !ss.IsName(subsection) { result = append(result, ss) } } s.Subsections = result } } return c }
[ "func", "(", "c", "*", "Config", ")", "RemoveSubsection", "(", "section", "string", ",", "subsection", "string", ")", "*", "Config", "{", "for", "_", ",", "s", ":=", "range", "c", ".", "Sections", "{", "if", "s", ".", "IsName", "(", "section", ")", "{", "result", ":=", "Subsections", "{", "}", "\n", "for", "_", ",", "ss", ":=", "range", "s", ".", "Subsections", "{", "if", "!", "ss", ".", "IsName", "(", "subsection", ")", "{", "result", "=", "append", "(", "result", ",", "ss", ")", "\n", "}", "\n", "}", "\n", "s", ".", "Subsections", "=", "result", "\n", "}", "\n", "}", "\n\n", "return", "c", "\n", "}" ]
// RemoveSubsection remove s a subsection from a config file.
[ "RemoveSubsection", "remove", "s", "a", "subsection", "from", "a", "config", "file", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/plumbing/format/config/common.go#L85-L99
train
src-d/go-git
_examples/tag/main.go
main
func main() { CheckArgs("<path>") path := os.Args[1] // We instanciate a new repository targeting the given path (the .git folder) r, err := git.PlainOpen(path) CheckIfError(err) // List all tag references, both lightweight tags and annotated tags Info("git show-ref --tag") tagrefs, err := r.Tags() CheckIfError(err) err = tagrefs.ForEach(func(t *plumbing.Reference) error { fmt.Println(t) return nil }) CheckIfError(err) // Print each annotated tag object (lightweight tags are not included) Info("for t in $(git show-ref --tag); do if [ \"$(git cat-file -t $t)\" = \"tag\" ]; then git cat-file -p $t ; fi; done") tags, err := r.TagObjects() CheckIfError(err) err = tags.ForEach(func(t *object.Tag) error { fmt.Println(t) return nil }) CheckIfError(err) }
go
func main() { CheckArgs("<path>") path := os.Args[1] // We instanciate a new repository targeting the given path (the .git folder) r, err := git.PlainOpen(path) CheckIfError(err) // List all tag references, both lightweight tags and annotated tags Info("git show-ref --tag") tagrefs, err := r.Tags() CheckIfError(err) err = tagrefs.ForEach(func(t *plumbing.Reference) error { fmt.Println(t) return nil }) CheckIfError(err) // Print each annotated tag object (lightweight tags are not included) Info("for t in $(git show-ref --tag); do if [ \"$(git cat-file -t $t)\" = \"tag\" ]; then git cat-file -p $t ; fi; done") tags, err := r.TagObjects() CheckIfError(err) err = tags.ForEach(func(t *object.Tag) error { fmt.Println(t) return nil }) CheckIfError(err) }
[ "func", "main", "(", ")", "{", "CheckArgs", "(", "\"", "\"", ")", "\n", "path", ":=", "os", ".", "Args", "[", "1", "]", "\n\n", "// We instanciate a new repository targeting the given path (the .git folder)", "r", ",", "err", ":=", "git", ".", "PlainOpen", "(", "path", ")", "\n", "CheckIfError", "(", "err", ")", "\n\n", "// List all tag references, both lightweight tags and annotated tags", "Info", "(", "\"", "\"", ")", "\n\n", "tagrefs", ",", "err", ":=", "r", ".", "Tags", "(", ")", "\n", "CheckIfError", "(", "err", ")", "\n", "err", "=", "tagrefs", ".", "ForEach", "(", "func", "(", "t", "*", "plumbing", ".", "Reference", ")", "error", "{", "fmt", ".", "Println", "(", "t", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "CheckIfError", "(", "err", ")", "\n\n", "// Print each annotated tag object (lightweight tags are not included)", "Info", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ")", "\n\n", "tags", ",", "err", ":=", "r", ".", "TagObjects", "(", ")", "\n", "CheckIfError", "(", "err", ")", "\n", "err", "=", "tags", ".", "ForEach", "(", "func", "(", "t", "*", "object", ".", "Tag", ")", "error", "{", "fmt", ".", "Println", "(", "t", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "CheckIfError", "(", "err", ")", "\n", "}" ]
// Basic example of how to list tags.
[ "Basic", "example", "of", "how", "to", "list", "tags", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/_examples/tag/main.go#L14-L43
train
src-d/go-git
references.go
sortCommits
func sortCommits(l []*object.Commit) { s := &commitSorterer{l} sort.Sort(s) }
go
func sortCommits(l []*object.Commit) { s := &commitSorterer{l} sort.Sort(s) }
[ "func", "sortCommits", "(", "l", "[", "]", "*", "object", ".", "Commit", ")", "{", "s", ":=", "&", "commitSorterer", "{", "l", "}", "\n", "sort", ".", "Sort", "(", "s", ")", "\n", "}" ]
// SortCommits sorts a commit list by commit date, from older to newer.
[ "SortCommits", "sorts", "a", "commit", "list", "by", "commit", "date", "from", "older", "to", "newer", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/references.go#L60-L63
train
src-d/go-git
references.go
walkGraph
func walkGraph(result *[]*object.Commit, seen *map[plumbing.Hash]struct{}, current *object.Commit, path string) error { // check and update seen if _, ok := (*seen)[current.Hash]; ok { return nil } (*seen)[current.Hash] = struct{}{} // if the path is not in the current commit, stop searching. if _, err := current.File(path); err != nil { return nil } // optimization: don't traverse branches that does not // contain the path. parents, err := parentsContainingPath(path, current) if err != nil { return err } switch len(parents) { // if the path is not found in any of its parents, the path was // created by this commit; we must add it to the revisions list and // stop searching. This includes the case when current is the // initial commit. case 0: *result = append(*result, current) return nil case 1: // only one parent contains the path // if the file contents has change, add the current commit different, err := differentContents(path, current, parents) if err != nil { return err } if len(different) == 1 { *result = append(*result, current) } // in any case, walk the parent return walkGraph(result, seen, parents[0], path) default: // more than one parent contains the path // TODO: detect merges that had a conflict, because they must be // included in the result here. for _, p := range parents { err := walkGraph(result, seen, p, path) if err != nil { return err } } } return nil }
go
func walkGraph(result *[]*object.Commit, seen *map[plumbing.Hash]struct{}, current *object.Commit, path string) error { // check and update seen if _, ok := (*seen)[current.Hash]; ok { return nil } (*seen)[current.Hash] = struct{}{} // if the path is not in the current commit, stop searching. if _, err := current.File(path); err != nil { return nil } // optimization: don't traverse branches that does not // contain the path. parents, err := parentsContainingPath(path, current) if err != nil { return err } switch len(parents) { // if the path is not found in any of its parents, the path was // created by this commit; we must add it to the revisions list and // stop searching. This includes the case when current is the // initial commit. case 0: *result = append(*result, current) return nil case 1: // only one parent contains the path // if the file contents has change, add the current commit different, err := differentContents(path, current, parents) if err != nil { return err } if len(different) == 1 { *result = append(*result, current) } // in any case, walk the parent return walkGraph(result, seen, parents[0], path) default: // more than one parent contains the path // TODO: detect merges that had a conflict, because they must be // included in the result here. for _, p := range parents { err := walkGraph(result, seen, p, path) if err != nil { return err } } } return nil }
[ "func", "walkGraph", "(", "result", "*", "[", "]", "*", "object", ".", "Commit", ",", "seen", "*", "map", "[", "plumbing", ".", "Hash", "]", "struct", "{", "}", ",", "current", "*", "object", ".", "Commit", ",", "path", "string", ")", "error", "{", "// check and update seen", "if", "_", ",", "ok", ":=", "(", "*", "seen", ")", "[", "current", ".", "Hash", "]", ";", "ok", "{", "return", "nil", "\n", "}", "\n", "(", "*", "seen", ")", "[", "current", ".", "Hash", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "// if the path is not in the current commit, stop searching.", "if", "_", ",", "err", ":=", "current", ".", "File", "(", "path", ")", ";", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// optimization: don't traverse branches that does not", "// contain the path.", "parents", ",", "err", ":=", "parentsContainingPath", "(", "path", ",", "current", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "len", "(", "parents", ")", "{", "// if the path is not found in any of its parents, the path was", "// created by this commit; we must add it to the revisions list and", "// stop searching. This includes the case when current is the", "// initial commit.", "case", "0", ":", "*", "result", "=", "append", "(", "*", "result", ",", "current", ")", "\n", "return", "nil", "\n", "case", "1", ":", "// only one parent contains the path", "// if the file contents has change, add the current commit", "different", ",", "err", ":=", "differentContents", "(", "path", ",", "current", ",", "parents", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "different", ")", "==", "1", "{", "*", "result", "=", "append", "(", "*", "result", ",", "current", ")", "\n", "}", "\n", "// in any case, walk the parent", "return", "walkGraph", "(", "result", ",", "seen", ",", "parents", "[", "0", "]", ",", "path", ")", "\n", "default", ":", "// more than one parent contains the path", "// TODO: detect merges that had a conflict, because they must be", "// included in the result here.", "for", "_", ",", "p", ":=", "range", "parents", "{", "err", ":=", "walkGraph", "(", "result", ",", "seen", ",", "p", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Recursive traversal of the commit graph, generating a linear history of the // path.
[ "Recursive", "traversal", "of", "the", "commit", "graph", "generating", "a", "linear", "history", "of", "the", "path", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/references.go#L67-L115
train
src-d/go-git
references.go
differentContents
func differentContents(path string, c *object.Commit, cs []*object.Commit) ([]*object.Commit, error) { result := make([]*object.Commit, 0, len(cs)) h, found := blobHash(path, c) if !found { return nil, object.ErrFileNotFound } for _, cx := range cs { if hx, found := blobHash(path, cx); found && h != hx { result = append(result, cx) } } return result, nil }
go
func differentContents(path string, c *object.Commit, cs []*object.Commit) ([]*object.Commit, error) { result := make([]*object.Commit, 0, len(cs)) h, found := blobHash(path, c) if !found { return nil, object.ErrFileNotFound } for _, cx := range cs { if hx, found := blobHash(path, cx); found && h != hx { result = append(result, cx) } } return result, nil }
[ "func", "differentContents", "(", "path", "string", ",", "c", "*", "object", ".", "Commit", ",", "cs", "[", "]", "*", "object", ".", "Commit", ")", "(", "[", "]", "*", "object", ".", "Commit", ",", "error", ")", "{", "result", ":=", "make", "(", "[", "]", "*", "object", ".", "Commit", ",", "0", ",", "len", "(", "cs", ")", ")", "\n", "h", ",", "found", ":=", "blobHash", "(", "path", ",", "c", ")", "\n", "if", "!", "found", "{", "return", "nil", ",", "object", ".", "ErrFileNotFound", "\n", "}", "\n", "for", "_", ",", "cx", ":=", "range", "cs", "{", "if", "hx", ",", "found", ":=", "blobHash", "(", "path", ",", "cx", ")", ";", "found", "&&", "h", "!=", "hx", "{", "result", "=", "append", "(", "result", ",", "cx", ")", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Returns an slice of the commits in "cs" that has the file "path", but with different // contents than what can be found in "c".
[ "Returns", "an", "slice", "of", "the", "commits", "in", "cs", "that", "has", "the", "file", "path", "but", "with", "different", "contents", "than", "what", "can", "be", "found", "in", "c", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/references.go#L138-L150
train
src-d/go-git
references.go
blobHash
func blobHash(path string, commit *object.Commit) (hash plumbing.Hash, found bool) { file, err := commit.File(path) if err != nil { var empty plumbing.Hash return empty, found } return file.Hash, true }
go
func blobHash(path string, commit *object.Commit) (hash plumbing.Hash, found bool) { file, err := commit.File(path) if err != nil { var empty plumbing.Hash return empty, found } return file.Hash, true }
[ "func", "blobHash", "(", "path", "string", ",", "commit", "*", "object", ".", "Commit", ")", "(", "hash", "plumbing", ".", "Hash", ",", "found", "bool", ")", "{", "file", ",", "err", ":=", "commit", ".", "File", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "var", "empty", "plumbing", ".", "Hash", "\n", "return", "empty", ",", "found", "\n", "}", "\n", "return", "file", ".", "Hash", ",", "true", "\n", "}" ]
// blobHash returns the hash of a path in a commit
[ "blobHash", "returns", "the", "hash", "of", "a", "path", "in", "a", "commit" ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/references.go#L153-L160
train
src-d/go-git
references.go
removeComp
func removeComp(path string, cs []*object.Commit, comp contentsComparatorFn) ([]*object.Commit, error) { result := make([]*object.Commit, 0, len(cs)) if len(cs) == 0 { return result, nil } result = append(result, cs[0]) for i := 1; i < len(cs); i++ { equals, err := comp(path, cs[i], cs[i-1]) if err != nil { return nil, err } if !equals { result = append(result, cs[i]) } } return result, nil }
go
func removeComp(path string, cs []*object.Commit, comp contentsComparatorFn) ([]*object.Commit, error) { result := make([]*object.Commit, 0, len(cs)) if len(cs) == 0 { return result, nil } result = append(result, cs[0]) for i := 1; i < len(cs); i++ { equals, err := comp(path, cs[i], cs[i-1]) if err != nil { return nil, err } if !equals { result = append(result, cs[i]) } } return result, nil }
[ "func", "removeComp", "(", "path", "string", ",", "cs", "[", "]", "*", "object", ".", "Commit", ",", "comp", "contentsComparatorFn", ")", "(", "[", "]", "*", "object", ".", "Commit", ",", "error", ")", "{", "result", ":=", "make", "(", "[", "]", "*", "object", ".", "Commit", ",", "0", ",", "len", "(", "cs", ")", ")", "\n", "if", "len", "(", "cs", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "cs", "[", "0", "]", ")", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "cs", ")", ";", "i", "++", "{", "equals", ",", "err", ":=", "comp", "(", "path", ",", "cs", "[", "i", "]", ",", "cs", "[", "i", "-", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "equals", "{", "result", "=", "append", "(", "result", ",", "cs", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Returns a new slice of commits, with duplicates removed. Expects a // sorted commit list. Duplication is defined according to "comp". It // will always keep the first commit of a series of duplicated commits.
[ "Returns", "a", "new", "slice", "of", "commits", "with", "duplicates", "removed", ".", "Expects", "a", "sorted", "commit", "list", ".", "Duplication", "is", "defined", "according", "to", "comp", ".", "It", "will", "always", "keep", "the", "first", "commit", "of", "a", "series", "of", "duplicated", "commits", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/references.go#L167-L183
train
src-d/go-git
references.go
equivalent
func equivalent(path string, a, b *object.Commit) (bool, error) { numParentsA := a.NumParents() numParentsB := b.NumParents() // the first commit is not equivalent to anyone // and "I think" merges can not be equivalent to anything if numParentsA != 1 || numParentsB != 1 { return false, nil } diffsA, err := patch(a, path) if err != nil { return false, err } diffsB, err := patch(b, path) if err != nil { return false, err } return sameDiffs(diffsA, diffsB), nil }
go
func equivalent(path string, a, b *object.Commit) (bool, error) { numParentsA := a.NumParents() numParentsB := b.NumParents() // the first commit is not equivalent to anyone // and "I think" merges can not be equivalent to anything if numParentsA != 1 || numParentsB != 1 { return false, nil } diffsA, err := patch(a, path) if err != nil { return false, err } diffsB, err := patch(b, path) if err != nil { return false, err } return sameDiffs(diffsA, diffsB), nil }
[ "func", "equivalent", "(", "path", "string", ",", "a", ",", "b", "*", "object", ".", "Commit", ")", "(", "bool", ",", "error", ")", "{", "numParentsA", ":=", "a", ".", "NumParents", "(", ")", "\n", "numParentsB", ":=", "b", ".", "NumParents", "(", ")", "\n\n", "// the first commit is not equivalent to anyone", "// and \"I think\" merges can not be equivalent to anything", "if", "numParentsA", "!=", "1", "||", "numParentsB", "!=", "1", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "diffsA", ",", "err", ":=", "patch", "(", "a", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "diffsB", ",", "err", ":=", "patch", "(", "b", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "return", "sameDiffs", "(", "diffsA", ",", "diffsB", ")", ",", "nil", "\n", "}" ]
// Equivalent commits are commits whose patch is the same.
[ "Equivalent", "commits", "are", "commits", "whose", "patch", "is", "the", "same", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/references.go#L186-L206
train
src-d/go-git
plumbing/format/gitignore/dir.go
readIgnoreFile
func readIgnoreFile(fs billy.Filesystem, path []string, ignoreFile string) (ps []Pattern, err error) { f, err := fs.Open(fs.Join(append(path, ignoreFile)...)) if err == nil { defer f.Close() if data, err := ioutil.ReadAll(f); err == nil { for _, s := range strings.Split(string(data), eol) { if !strings.HasPrefix(s, commentPrefix) && len(strings.TrimSpace(s)) > 0 { ps = append(ps, ParsePattern(s, path)) } } } } else if !os.IsNotExist(err) { return nil, err } return }
go
func readIgnoreFile(fs billy.Filesystem, path []string, ignoreFile string) (ps []Pattern, err error) { f, err := fs.Open(fs.Join(append(path, ignoreFile)...)) if err == nil { defer f.Close() if data, err := ioutil.ReadAll(f); err == nil { for _, s := range strings.Split(string(data), eol) { if !strings.HasPrefix(s, commentPrefix) && len(strings.TrimSpace(s)) > 0 { ps = append(ps, ParsePattern(s, path)) } } } } else if !os.IsNotExist(err) { return nil, err } return }
[ "func", "readIgnoreFile", "(", "fs", "billy", ".", "Filesystem", ",", "path", "[", "]", "string", ",", "ignoreFile", "string", ")", "(", "ps", "[", "]", "Pattern", ",", "err", "error", ")", "{", "f", ",", "err", ":=", "fs", ".", "Open", "(", "fs", ".", "Join", "(", "append", "(", "path", ",", "ignoreFile", ")", "...", ")", ")", "\n", "if", "err", "==", "nil", "{", "defer", "f", ".", "Close", "(", ")", "\n\n", "if", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ")", ";", "err", "==", "nil", "{", "for", "_", ",", "s", ":=", "range", "strings", ".", "Split", "(", "string", "(", "data", ")", ",", "eol", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "s", ",", "commentPrefix", ")", "&&", "len", "(", "strings", ".", "TrimSpace", "(", "s", ")", ")", ">", "0", "{", "ps", "=", "append", "(", "ps", ",", "ParsePattern", "(", "s", ",", "path", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "else", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "\n", "}" ]
// readIgnoreFile reads a specific git ignore file.
[ "readIgnoreFile", "reads", "a", "specific", "git", "ignore", "file", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/plumbing/format/gitignore/dir.go#L27-L44
train
src-d/go-git
plumbing/object/change.go
Action
func (c *Change) Action() (merkletrie.Action, error) { if c.From == empty && c.To == empty { return merkletrie.Action(0), fmt.Errorf("malformed change: empty from and to") } if c.From == empty { return merkletrie.Insert, nil } if c.To == empty { return merkletrie.Delete, nil } return merkletrie.Modify, nil }
go
func (c *Change) Action() (merkletrie.Action, error) { if c.From == empty && c.To == empty { return merkletrie.Action(0), fmt.Errorf("malformed change: empty from and to") } if c.From == empty { return merkletrie.Insert, nil } if c.To == empty { return merkletrie.Delete, nil } return merkletrie.Modify, nil }
[ "func", "(", "c", "*", "Change", ")", "Action", "(", ")", "(", "merkletrie", ".", "Action", ",", "error", ")", "{", "if", "c", ".", "From", "==", "empty", "&&", "c", ".", "To", "==", "empty", "{", "return", "merkletrie", ".", "Action", "(", "0", ")", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "From", "==", "empty", "{", "return", "merkletrie", ".", "Insert", ",", "nil", "\n", "}", "\n", "if", "c", ".", "To", "==", "empty", "{", "return", "merkletrie", ".", "Delete", ",", "nil", "\n", "}", "\n\n", "return", "merkletrie", ".", "Modify", ",", "nil", "\n", "}" ]
// Action returns the kind of action represented by the change, an // insertion, a deletion or a modification.
[ "Action", "returns", "the", "kind", "of", "action", "represented", "by", "the", "change", "an", "insertion", "a", "deletion", "or", "a", "modification", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/plumbing/object/change.go#L25-L38
train
src-d/go-git
plumbing/object/change.go
Files
func (c *Change) Files() (from, to *File, err error) { action, err := c.Action() if err != nil { return } if action == merkletrie.Insert || action == merkletrie.Modify { to, err = c.To.Tree.TreeEntryFile(&c.To.TreeEntry) if !c.To.TreeEntry.Mode.IsFile() { return nil, nil, nil } if err != nil { return } } if action == merkletrie.Delete || action == merkletrie.Modify { from, err = c.From.Tree.TreeEntryFile(&c.From.TreeEntry) if !c.From.TreeEntry.Mode.IsFile() { return nil, nil, nil } if err != nil { return } } return }
go
func (c *Change) Files() (from, to *File, err error) { action, err := c.Action() if err != nil { return } if action == merkletrie.Insert || action == merkletrie.Modify { to, err = c.To.Tree.TreeEntryFile(&c.To.TreeEntry) if !c.To.TreeEntry.Mode.IsFile() { return nil, nil, nil } if err != nil { return } } if action == merkletrie.Delete || action == merkletrie.Modify { from, err = c.From.Tree.TreeEntryFile(&c.From.TreeEntry) if !c.From.TreeEntry.Mode.IsFile() { return nil, nil, nil } if err != nil { return } } return }
[ "func", "(", "c", "*", "Change", ")", "Files", "(", ")", "(", "from", ",", "to", "*", "File", ",", "err", "error", ")", "{", "action", ",", "err", ":=", "c", ".", "Action", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "action", "==", "merkletrie", ".", "Insert", "||", "action", "==", "merkletrie", ".", "Modify", "{", "to", ",", "err", "=", "c", ".", "To", ".", "Tree", ".", "TreeEntryFile", "(", "&", "c", ".", "To", ".", "TreeEntry", ")", "\n", "if", "!", "c", ".", "To", ".", "TreeEntry", ".", "Mode", ".", "IsFile", "(", ")", "{", "return", "nil", ",", "nil", ",", "nil", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "if", "action", "==", "merkletrie", ".", "Delete", "||", "action", "==", "merkletrie", ".", "Modify", "{", "from", ",", "err", "=", "c", ".", "From", ".", "Tree", ".", "TreeEntryFile", "(", "&", "c", ".", "From", ".", "TreeEntry", ")", "\n", "if", "!", "c", ".", "From", ".", "TreeEntry", ".", "Mode", ".", "IsFile", "(", ")", "{", "return", "nil", ",", "nil", ",", "nil", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// Files return the files before and after a change. // For insertions from will be nil. For deletions to will be nil.
[ "Files", "return", "the", "files", "before", "and", "after", "a", "change", ".", "For", "insertions", "from", "will", "be", "nil", ".", "For", "deletions", "to", "will", "be", "nil", "." ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/plumbing/object/change.go#L42-L71
train
src-d/go-git
plumbing/object/change.go
PatchContext
func (c Changes) PatchContext(ctx context.Context) (*Patch, error) { return getPatchContext(ctx, "", c...) }
go
func (c Changes) PatchContext(ctx context.Context) (*Patch, error) { return getPatchContext(ctx, "", c...) }
[ "func", "(", "c", "Changes", ")", "PatchContext", "(", "ctx", "context", ".", "Context", ")", "(", "*", "Patch", ",", "error", ")", "{", "return", "getPatchContext", "(", "ctx", ",", "\"", "\"", ",", "c", "...", ")", "\n", "}" ]
// Patch returns a Patch with all the changes in chunks. This // representation can be used to create several diff outputs. // If context expires, an non-nil error will be returned // Provided context must be non-nil
[ "Patch", "returns", "a", "Patch", "with", "all", "the", "changes", "in", "chunks", ".", "This", "representation", "can", "be", "used", "to", "create", "several", "diff", "outputs", ".", "If", "context", "expires", "an", "non", "-", "nil", "error", "will", "be", "returned", "Provided", "context", "must", "be", "non", "-", "nil" ]
e17ee112ca6cc7db0a732c0676b61511e84ec899
https://github.com/src-d/go-git/blob/e17ee112ca6cc7db0a732c0676b61511e84ec899/plumbing/object/change.go#L155-L157
train
cloudflare/cfssl
ocsp/universal/universal.go
NewSignerFromConfig
func NewSignerFromConfig(cfg ocspConfig.Config) (ocsp.Signer, error) { return ocsp.NewSignerFromFile(cfg.CACertFile, cfg.ResponderCertFile, cfg.KeyFile, cfg.Interval) }
go
func NewSignerFromConfig(cfg ocspConfig.Config) (ocsp.Signer, error) { return ocsp.NewSignerFromFile(cfg.CACertFile, cfg.ResponderCertFile, cfg.KeyFile, cfg.Interval) }
[ "func", "NewSignerFromConfig", "(", "cfg", "ocspConfig", ".", "Config", ")", "(", "ocsp", ".", "Signer", ",", "error", ")", "{", "return", "ocsp", ".", "NewSignerFromFile", "(", "cfg", ".", "CACertFile", ",", "cfg", ".", "ResponderCertFile", ",", "cfg", ".", "KeyFile", ",", "cfg", ".", "Interval", ")", "\n", "}" ]
// NewSignerFromConfig generates a new OCSP signer from a config object.
[ "NewSignerFromConfig", "generates", "a", "new", "OCSP", "signer", "from", "a", "config", "object", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/ocsp/universal/universal.go#L9-L12
train
cloudflare/cfssl
cmd/cfssl-certinfo/cfssl-certinfo.go
main
func main() { var certinfoFlagSet = flag.NewFlagSet("certinfo", flag.ExitOnError) var c cli.Config registerFlags(&c, certinfoFlagSet) var usageText = `cfssl-certinfo -- output certinfo about the given cert Usage of certinfo: - Data from local certificate files certinfo -cert file - Data from certificate from remote server. certinfo -domain domain_name - Data from CA storage certinfo -serial serial_number -aki authority_key_id (requires -db-config) Flags: ` certinfoFlagSet.Usage = func() { fmt.Fprintf(os.Stderr, "\t%s", usageText) for _, name := range certinfo.Command.Flags { if f := certinfoFlagSet.Lookup(name); f != nil { printDefaultValue(f) } } } args := os.Args[1:] certinfoFlagSet.Parse(args) args = certinfoFlagSet.Args() var err error c.CFG, err = config.LoadFile(c.ConfigFile) if c.ConfigFile != "" && err != nil { fmt.Fprintf(os.Stderr, "Failed to load config file: %v", err) } if err := certinfo.Command.Main(args, c); err != nil { fmt.Fprintln(os.Stderr, err) } }
go
func main() { var certinfoFlagSet = flag.NewFlagSet("certinfo", flag.ExitOnError) var c cli.Config registerFlags(&c, certinfoFlagSet) var usageText = `cfssl-certinfo -- output certinfo about the given cert Usage of certinfo: - Data from local certificate files certinfo -cert file - Data from certificate from remote server. certinfo -domain domain_name - Data from CA storage certinfo -serial serial_number -aki authority_key_id (requires -db-config) Flags: ` certinfoFlagSet.Usage = func() { fmt.Fprintf(os.Stderr, "\t%s", usageText) for _, name := range certinfo.Command.Flags { if f := certinfoFlagSet.Lookup(name); f != nil { printDefaultValue(f) } } } args := os.Args[1:] certinfoFlagSet.Parse(args) args = certinfoFlagSet.Args() var err error c.CFG, err = config.LoadFile(c.ConfigFile) if c.ConfigFile != "" && err != nil { fmt.Fprintf(os.Stderr, "Failed to load config file: %v", err) } if err := certinfo.Command.Main(args, c); err != nil { fmt.Fprintln(os.Stderr, err) } }
[ "func", "main", "(", ")", "{", "var", "certinfoFlagSet", "=", "flag", ".", "NewFlagSet", "(", "\"", "\"", ",", "flag", ".", "ExitOnError", ")", "\n", "var", "c", "cli", ".", "Config", "\n", "registerFlags", "(", "&", "c", ",", "certinfoFlagSet", ")", "\n", "var", "usageText", "=", "`cfssl-certinfo -- output certinfo about the given cert\n\n\tUsage of certinfo:\n\t\t- Data from local certificate files\n \tcertinfo -cert file\n\t\t- Data from certificate from remote server.\n \tcertinfo -domain domain_name\n\t\t- Data from CA storage\n \tcertinfo -serial serial_number -aki authority_key_id (requires -db-config)\n\n\tFlags:\n\t`", "\n\n", "certinfoFlagSet", ".", "Usage", "=", "func", "(", ")", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\t", "\"", ",", "usageText", ")", "\n", "for", "_", ",", "name", ":=", "range", "certinfo", ".", "Command", ".", "Flags", "{", "if", "f", ":=", "certinfoFlagSet", ".", "Lookup", "(", "name", ")", ";", "f", "!=", "nil", "{", "printDefaultValue", "(", "f", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "args", ":=", "os", ".", "Args", "[", "1", ":", "]", "\n", "certinfoFlagSet", ".", "Parse", "(", "args", ")", "\n", "args", "=", "certinfoFlagSet", ".", "Args", "(", ")", "\n\n", "var", "err", "error", "\n", "c", ".", "CFG", ",", "err", "=", "config", ".", "LoadFile", "(", "c", ".", "ConfigFile", ")", "\n", "if", "c", ".", "ConfigFile", "!=", "\"", "\"", "&&", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "certinfo", ".", "Command", ".", "Main", "(", "args", ",", "c", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "err", ")", "\n", "}", "\n", "}" ]
// main defines the newkey usage and registers all defined commands and flags.
[ "main", "defines", "the", "newkey", "usage", "and", "registers", "all", "defined", "commands", "and", "flags", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cmd/cfssl-certinfo/cfssl-certinfo.go#L18-L57
train
cloudflare/cfssl
cmd/cfssl-certinfo/cfssl-certinfo.go
printDefaultValue
func printDefaultValue(f *flag.Flag) { format := " -%s=%s: %s\n" if f.DefValue == "" { format = " -%s=%q: %s\n" } fmt.Fprintf(os.Stderr, format, f.Name, f.DefValue, f.Usage) }
go
func printDefaultValue(f *flag.Flag) { format := " -%s=%s: %s\n" if f.DefValue == "" { format = " -%s=%q: %s\n" } fmt.Fprintf(os.Stderr, format, f.Name, f.DefValue, f.Usage) }
[ "func", "printDefaultValue", "(", "f", "*", "flag", ".", "Flag", ")", "{", "format", ":=", "\"", "\\n", "\"", "\n", "if", "f", ".", "DefValue", "==", "\"", "\"", "{", "format", "=", "\"", "\\n", "\"", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "format", ",", "f", ".", "Name", ",", "f", ".", "DefValue", ",", "f", ".", "Usage", ")", "\n", "}" ]
// printDefaultValue is a helper function to print out a user friendly // usage message of a flag. It's useful since we want to write customized // usage message on selected subsets of the global flag set. It is // borrowed from standard library source code. Since flag value type is // not exported, default string flag values are printed without // quotes. The only exception is the empty string, which is printed as "".
[ "printDefaultValue", "is", "a", "helper", "function", "to", "print", "out", "a", "user", "friendly", "usage", "message", "of", "a", "flag", ".", "It", "s", "useful", "since", "we", "want", "to", "write", "customized", "usage", "message", "on", "selected", "subsets", "of", "the", "global", "flag", "set", ".", "It", "is", "borrowed", "from", "standard", "library", "source", "code", ".", "Since", "flag", "value", "type", "is", "not", "exported", "default", "string", "flag", "values", "are", "printed", "without", "quotes", ".", "The", "only", "exception", "is", "the", "empty", "string", "which", "is", "printed", "as", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cmd/cfssl-certinfo/cfssl-certinfo.go#L65-L71
train
cloudflare/cfssl
csr/csr.go
Generate
func (kr *BasicKeyRequest) Generate() (crypto.PrivateKey, error) { log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo(), kr.Size()) switch kr.Algo() { case "rsa": if kr.Size() < 2048 { return nil, errors.New("RSA key is too weak") } if kr.Size() > 8192 { return nil, errors.New("RSA key size too large") } return rsa.GenerateKey(rand.Reader, kr.Size()) case "ecdsa": var curve elliptic.Curve switch kr.Size() { case curveP256: curve = elliptic.P256() case curveP384: curve = elliptic.P384() case curveP521: curve = elliptic.P521() default: return nil, errors.New("invalid curve") } return ecdsa.GenerateKey(curve, rand.Reader) default: return nil, errors.New("invalid algorithm") } }
go
func (kr *BasicKeyRequest) Generate() (crypto.PrivateKey, error) { log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo(), kr.Size()) switch kr.Algo() { case "rsa": if kr.Size() < 2048 { return nil, errors.New("RSA key is too weak") } if kr.Size() > 8192 { return nil, errors.New("RSA key size too large") } return rsa.GenerateKey(rand.Reader, kr.Size()) case "ecdsa": var curve elliptic.Curve switch kr.Size() { case curveP256: curve = elliptic.P256() case curveP384: curve = elliptic.P384() case curveP521: curve = elliptic.P521() default: return nil, errors.New("invalid curve") } return ecdsa.GenerateKey(curve, rand.Reader) default: return nil, errors.New("invalid algorithm") } }
[ "func", "(", "kr", "*", "BasicKeyRequest", ")", "Generate", "(", ")", "(", "crypto", ".", "PrivateKey", ",", "error", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "kr", ".", "Algo", "(", ")", ",", "kr", ".", "Size", "(", ")", ")", "\n", "switch", "kr", ".", "Algo", "(", ")", "{", "case", "\"", "\"", ":", "if", "kr", ".", "Size", "(", ")", "<", "2048", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "kr", ".", "Size", "(", ")", ">", "8192", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "rsa", ".", "GenerateKey", "(", "rand", ".", "Reader", ",", "kr", ".", "Size", "(", ")", ")", "\n", "case", "\"", "\"", ":", "var", "curve", "elliptic", ".", "Curve", "\n", "switch", "kr", ".", "Size", "(", ")", "{", "case", "curveP256", ":", "curve", "=", "elliptic", ".", "P256", "(", ")", "\n", "case", "curveP384", ":", "curve", "=", "elliptic", ".", "P384", "(", ")", "\n", "case", "curveP521", ":", "curve", "=", "elliptic", ".", "P521", "(", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "ecdsa", ".", "GenerateKey", "(", "curve", ",", "rand", ".", "Reader", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Generate generates a key as specified in the request. Currently, // only ECDSA and RSA are supported.
[ "Generate", "generates", "a", "key", "as", "specified", "in", "the", "request", ".", "Currently", "only", "ECDSA", "and", "RSA", "are", "supported", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L72-L99
train
cloudflare/cfssl
csr/csr.go
SigAlgo
func (kr *BasicKeyRequest) SigAlgo() x509.SignatureAlgorithm { switch kr.Algo() { case "rsa": switch { case kr.Size() >= 4096: return x509.SHA512WithRSA case kr.Size() >= 3072: return x509.SHA384WithRSA case kr.Size() >= 2048: return x509.SHA256WithRSA default: return x509.SHA1WithRSA } case "ecdsa": switch kr.Size() { case curveP521: return x509.ECDSAWithSHA512 case curveP384: return x509.ECDSAWithSHA384 case curveP256: return x509.ECDSAWithSHA256 default: return x509.ECDSAWithSHA1 } default: return x509.UnknownSignatureAlgorithm } }
go
func (kr *BasicKeyRequest) SigAlgo() x509.SignatureAlgorithm { switch kr.Algo() { case "rsa": switch { case kr.Size() >= 4096: return x509.SHA512WithRSA case kr.Size() >= 3072: return x509.SHA384WithRSA case kr.Size() >= 2048: return x509.SHA256WithRSA default: return x509.SHA1WithRSA } case "ecdsa": switch kr.Size() { case curveP521: return x509.ECDSAWithSHA512 case curveP384: return x509.ECDSAWithSHA384 case curveP256: return x509.ECDSAWithSHA256 default: return x509.ECDSAWithSHA1 } default: return x509.UnknownSignatureAlgorithm } }
[ "func", "(", "kr", "*", "BasicKeyRequest", ")", "SigAlgo", "(", ")", "x509", ".", "SignatureAlgorithm", "{", "switch", "kr", ".", "Algo", "(", ")", "{", "case", "\"", "\"", ":", "switch", "{", "case", "kr", ".", "Size", "(", ")", ">=", "4096", ":", "return", "x509", ".", "SHA512WithRSA", "\n", "case", "kr", ".", "Size", "(", ")", ">=", "3072", ":", "return", "x509", ".", "SHA384WithRSA", "\n", "case", "kr", ".", "Size", "(", ")", ">=", "2048", ":", "return", "x509", ".", "SHA256WithRSA", "\n", "default", ":", "return", "x509", ".", "SHA1WithRSA", "\n", "}", "\n", "case", "\"", "\"", ":", "switch", "kr", ".", "Size", "(", ")", "{", "case", "curveP521", ":", "return", "x509", ".", "ECDSAWithSHA512", "\n", "case", "curveP384", ":", "return", "x509", ".", "ECDSAWithSHA384", "\n", "case", "curveP256", ":", "return", "x509", ".", "ECDSAWithSHA256", "\n", "default", ":", "return", "x509", ".", "ECDSAWithSHA1", "\n", "}", "\n", "default", ":", "return", "x509", ".", "UnknownSignatureAlgorithm", "\n", "}", "\n", "}" ]
// SigAlgo returns an appropriate X.509 signature algorithm given the // key request's type and size.
[ "SigAlgo", "returns", "an", "appropriate", "X", ".", "509", "signature", "algorithm", "given", "the", "key", "request", "s", "type", "and", "size", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L103-L130
train
cloudflare/cfssl
csr/csr.go
appendIf
func appendIf(s string, a *[]string) { if s != "" { *a = append(*a, s) } }
go
func appendIf(s string, a *[]string) { if s != "" { *a = append(*a, s) } }
[ "func", "appendIf", "(", "s", "string", ",", "a", "*", "[", "]", "string", ")", "{", "if", "s", "!=", "\"", "\"", "{", "*", "a", "=", "append", "(", "*", "a", ",", "s", ")", "\n", "}", "\n", "}" ]
// appendIf appends to a if s is not an empty string.
[ "appendIf", "appends", "to", "a", "if", "s", "is", "not", "an", "empty", "string", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L160-L164
train
cloudflare/cfssl
csr/csr.go
Name
func (cr *CertificateRequest) Name() pkix.Name { var name pkix.Name name.CommonName = cr.CN for _, n := range cr.Names { appendIf(n.C, &name.Country) appendIf(n.ST, &name.Province) appendIf(n.L, &name.Locality) appendIf(n.O, &name.Organization) appendIf(n.OU, &name.OrganizationalUnit) } name.SerialNumber = cr.SerialNumber return name }
go
func (cr *CertificateRequest) Name() pkix.Name { var name pkix.Name name.CommonName = cr.CN for _, n := range cr.Names { appendIf(n.C, &name.Country) appendIf(n.ST, &name.Province) appendIf(n.L, &name.Locality) appendIf(n.O, &name.Organization) appendIf(n.OU, &name.OrganizationalUnit) } name.SerialNumber = cr.SerialNumber return name }
[ "func", "(", "cr", "*", "CertificateRequest", ")", "Name", "(", ")", "pkix", ".", "Name", "{", "var", "name", "pkix", ".", "Name", "\n", "name", ".", "CommonName", "=", "cr", ".", "CN", "\n\n", "for", "_", ",", "n", ":=", "range", "cr", ".", "Names", "{", "appendIf", "(", "n", ".", "C", ",", "&", "name", ".", "Country", ")", "\n", "appendIf", "(", "n", ".", "ST", ",", "&", "name", ".", "Province", ")", "\n", "appendIf", "(", "n", ".", "L", ",", "&", "name", ".", "Locality", ")", "\n", "appendIf", "(", "n", ".", "O", ",", "&", "name", ".", "Organization", ")", "\n", "appendIf", "(", "n", ".", "OU", ",", "&", "name", ".", "OrganizationalUnit", ")", "\n", "}", "\n", "name", ".", "SerialNumber", "=", "cr", ".", "SerialNumber", "\n", "return", "name", "\n", "}" ]
// Name returns the PKIX name for the request.
[ "Name", "returns", "the", "PKIX", "name", "for", "the", "request", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L167-L180
train
cloudflare/cfssl
csr/csr.go
ExtractCertificateRequest
func ExtractCertificateRequest(cert *x509.Certificate) *CertificateRequest { req := New() req.CN = cert.Subject.CommonName req.Names = getNames(cert.Subject) req.Hosts = getHosts(cert) req.SerialNumber = cert.Subject.SerialNumber if cert.IsCA { req.CA = new(CAConfig) // CA expiry length is calculated based on the input cert // issue date and expiry date. req.CA.Expiry = cert.NotAfter.Sub(cert.NotBefore).String() req.CA.PathLength = cert.MaxPathLen req.CA.PathLenZero = cert.MaxPathLenZero } return req }
go
func ExtractCertificateRequest(cert *x509.Certificate) *CertificateRequest { req := New() req.CN = cert.Subject.CommonName req.Names = getNames(cert.Subject) req.Hosts = getHosts(cert) req.SerialNumber = cert.Subject.SerialNumber if cert.IsCA { req.CA = new(CAConfig) // CA expiry length is calculated based on the input cert // issue date and expiry date. req.CA.Expiry = cert.NotAfter.Sub(cert.NotBefore).String() req.CA.PathLength = cert.MaxPathLen req.CA.PathLenZero = cert.MaxPathLenZero } return req }
[ "func", "ExtractCertificateRequest", "(", "cert", "*", "x509", ".", "Certificate", ")", "*", "CertificateRequest", "{", "req", ":=", "New", "(", ")", "\n", "req", ".", "CN", "=", "cert", ".", "Subject", ".", "CommonName", "\n", "req", ".", "Names", "=", "getNames", "(", "cert", ".", "Subject", ")", "\n", "req", ".", "Hosts", "=", "getHosts", "(", "cert", ")", "\n", "req", ".", "SerialNumber", "=", "cert", ".", "Subject", ".", "SerialNumber", "\n\n", "if", "cert", ".", "IsCA", "{", "req", ".", "CA", "=", "new", "(", "CAConfig", ")", "\n", "// CA expiry length is calculated based on the input cert", "// issue date and expiry date.", "req", ".", "CA", ".", "Expiry", "=", "cert", ".", "NotAfter", ".", "Sub", "(", "cert", ".", "NotBefore", ")", ".", "String", "(", ")", "\n", "req", ".", "CA", ".", "PathLength", "=", "cert", ".", "MaxPathLen", "\n", "req", ".", "CA", ".", "PathLenZero", "=", "cert", ".", "MaxPathLenZero", "\n", "}", "\n\n", "return", "req", "\n", "}" ]
// ExtractCertificateRequest extracts a CertificateRequest from // x509.Certificate. It is aimed to used for generating a new certificate // from an existing certificate. For a root certificate, the CA expiry // length is calculated as the duration between cert.NotAfter and cert.NotBefore.
[ "ExtractCertificateRequest", "extracts", "a", "CertificateRequest", "from", "x509", ".", "Certificate", ".", "It", "is", "aimed", "to", "used", "for", "generating", "a", "new", "certificate", "from", "an", "existing", "certificate", ".", "For", "a", "root", "certificate", "the", "CA", "expiry", "length", "is", "calculated", "as", "the", "duration", "between", "cert", ".", "NotAfter", "and", "cert", ".", "NotBefore", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L242-L259
train
cloudflare/cfssl
csr/csr.go
getNames
func getNames(sub pkix.Name) []Name { // anonymous func for finding the max of a list of interger max := func(v1 int, vn ...int) (max int) { max = v1 for i := 0; i < len(vn); i++ { if vn[i] > max { max = vn[i] } } return max } nc := len(sub.Country) norg := len(sub.Organization) nou := len(sub.OrganizationalUnit) nl := len(sub.Locality) np := len(sub.Province) n := max(nc, norg, nou, nl, np) names := make([]Name, n) for i := range names { if i < nc { names[i].C = sub.Country[i] } if i < norg { names[i].O = sub.Organization[i] } if i < nou { names[i].OU = sub.OrganizationalUnit[i] } if i < nl { names[i].L = sub.Locality[i] } if i < np { names[i].ST = sub.Province[i] } } return names }
go
func getNames(sub pkix.Name) []Name { // anonymous func for finding the max of a list of interger max := func(v1 int, vn ...int) (max int) { max = v1 for i := 0; i < len(vn); i++ { if vn[i] > max { max = vn[i] } } return max } nc := len(sub.Country) norg := len(sub.Organization) nou := len(sub.OrganizationalUnit) nl := len(sub.Locality) np := len(sub.Province) n := max(nc, norg, nou, nl, np) names := make([]Name, n) for i := range names { if i < nc { names[i].C = sub.Country[i] } if i < norg { names[i].O = sub.Organization[i] } if i < nou { names[i].OU = sub.OrganizationalUnit[i] } if i < nl { names[i].L = sub.Locality[i] } if i < np { names[i].ST = sub.Province[i] } } return names }
[ "func", "getNames", "(", "sub", "pkix", ".", "Name", ")", "[", "]", "Name", "{", "// anonymous func for finding the max of a list of interger", "max", ":=", "func", "(", "v1", "int", ",", "vn", "...", "int", ")", "(", "max", "int", ")", "{", "max", "=", "v1", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "vn", ")", ";", "i", "++", "{", "if", "vn", "[", "i", "]", ">", "max", "{", "max", "=", "vn", "[", "i", "]", "\n", "}", "\n", "}", "\n", "return", "max", "\n", "}", "\n\n", "nc", ":=", "len", "(", "sub", ".", "Country", ")", "\n", "norg", ":=", "len", "(", "sub", ".", "Organization", ")", "\n", "nou", ":=", "len", "(", "sub", ".", "OrganizationalUnit", ")", "\n", "nl", ":=", "len", "(", "sub", ".", "Locality", ")", "\n", "np", ":=", "len", "(", "sub", ".", "Province", ")", "\n\n", "n", ":=", "max", "(", "nc", ",", "norg", ",", "nou", ",", "nl", ",", "np", ")", "\n\n", "names", ":=", "make", "(", "[", "]", "Name", ",", "n", ")", "\n", "for", "i", ":=", "range", "names", "{", "if", "i", "<", "nc", "{", "names", "[", "i", "]", ".", "C", "=", "sub", ".", "Country", "[", "i", "]", "\n", "}", "\n", "if", "i", "<", "norg", "{", "names", "[", "i", "]", ".", "O", "=", "sub", ".", "Organization", "[", "i", "]", "\n", "}", "\n", "if", "i", "<", "nou", "{", "names", "[", "i", "]", ".", "OU", "=", "sub", ".", "OrganizationalUnit", "[", "i", "]", "\n", "}", "\n", "if", "i", "<", "nl", "{", "names", "[", "i", "]", ".", "L", "=", "sub", ".", "Locality", "[", "i", "]", "\n", "}", "\n", "if", "i", "<", "np", "{", "names", "[", "i", "]", ".", "ST", "=", "sub", ".", "Province", "[", "i", "]", "\n", "}", "\n", "}", "\n", "return", "names", "\n", "}" ]
// getNames returns an array of Names from the certificate // It onnly cares about Country, Organization, OrganizationalUnit, Locality, Province
[ "getNames", "returns", "an", "array", "of", "Names", "from", "the", "certificate", "It", "onnly", "cares", "about", "Country", "Organization", "OrganizationalUnit", "Locality", "Province" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L281-L320
train
cloudflare/cfssl
csr/csr.go
ProcessRequest
func (g *Generator) ProcessRequest(req *CertificateRequest) (csr, key []byte, err error) { log.Info("generate received request") err = g.Validator(req) if err != nil { log.Warningf("invalid request: %v", err) return nil, nil, err } csr, key, err = ParseRequest(req) if err != nil { return nil, nil, err } return }
go
func (g *Generator) ProcessRequest(req *CertificateRequest) (csr, key []byte, err error) { log.Info("generate received request") err = g.Validator(req) if err != nil { log.Warningf("invalid request: %v", err) return nil, nil, err } csr, key, err = ParseRequest(req) if err != nil { return nil, nil, err } return }
[ "func", "(", "g", "*", "Generator", ")", "ProcessRequest", "(", "req", "*", "CertificateRequest", ")", "(", "csr", ",", "key", "[", "]", "byte", ",", "err", "error", ")", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "err", "=", "g", ".", "Validator", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "csr", ",", "key", ",", "err", "=", "ParseRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "\n", "}" ]
// ProcessRequest validates and processes the incoming request. It is // a wrapper around a validator and the ParseRequest function.
[ "ProcessRequest", "validates", "and", "processes", "the", "incoming", "request", ".", "It", "is", "a", "wrapper", "around", "a", "validator", "and", "the", "ParseRequest", "function", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L329-L343
train
cloudflare/cfssl
csr/csr.go
IsNameEmpty
func IsNameEmpty(n Name) bool { empty := func(s string) bool { return strings.TrimSpace(s) == "" } if empty(n.C) && empty(n.ST) && empty(n.L) && empty(n.O) && empty(n.OU) { return true } return false }
go
func IsNameEmpty(n Name) bool { empty := func(s string) bool { return strings.TrimSpace(s) == "" } if empty(n.C) && empty(n.ST) && empty(n.L) && empty(n.O) && empty(n.OU) { return true } return false }
[ "func", "IsNameEmpty", "(", "n", "Name", ")", "bool", "{", "empty", ":=", "func", "(", "s", "string", ")", "bool", "{", "return", "strings", ".", "TrimSpace", "(", "s", ")", "==", "\"", "\"", "}", "\n\n", "if", "empty", "(", "n", ".", "C", ")", "&&", "empty", "(", "n", ".", "ST", ")", "&&", "empty", "(", "n", ".", "L", ")", "&&", "empty", "(", "n", ".", "O", ")", "&&", "empty", "(", "n", ".", "OU", ")", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsNameEmpty returns true if the name has no identifying information in it.
[ "IsNameEmpty", "returns", "true", "if", "the", "name", "has", "no", "identifying", "information", "in", "it", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L346-L353
train
cloudflare/cfssl
csr/csr.go
Regenerate
func Regenerate(priv crypto.Signer, csr []byte) ([]byte, error) { req, extra, err := helpers.ParseCSR(csr) if err != nil { return nil, err } else if len(extra) > 0 { return nil, errors.New("csr: trailing data in certificate request") } return x509.CreateCertificateRequest(rand.Reader, req, priv) }
go
func Regenerate(priv crypto.Signer, csr []byte) ([]byte, error) { req, extra, err := helpers.ParseCSR(csr) if err != nil { return nil, err } else if len(extra) > 0 { return nil, errors.New("csr: trailing data in certificate request") } return x509.CreateCertificateRequest(rand.Reader, req, priv) }
[ "func", "Regenerate", "(", "priv", "crypto", ".", "Signer", ",", "csr", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "req", ",", "extra", ",", "err", ":=", "helpers", ".", "ParseCSR", "(", "csr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "len", "(", "extra", ")", ">", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "x509", ".", "CreateCertificateRequest", "(", "rand", ".", "Reader", ",", "req", ",", "priv", ")", "\n", "}" ]
// Regenerate uses the provided CSR as a template for signing a new // CSR using priv.
[ "Regenerate", "uses", "the", "provided", "CSR", "as", "a", "template", "for", "signing", "a", "new", "CSR", "using", "priv", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L357-L366
train
cloudflare/cfssl
csr/csr.go
Generate
func Generate(priv crypto.Signer, req *CertificateRequest) (csr []byte, err error) { sigAlgo := helpers.SignerAlgo(priv) if sigAlgo == x509.UnknownSignatureAlgorithm { return nil, cferr.New(cferr.PrivateKeyError, cferr.Unavailable) } var tpl = x509.CertificateRequest{ Subject: req.Name(), SignatureAlgorithm: sigAlgo, } for i := range req.Hosts { if ip := net.ParseIP(req.Hosts[i]); ip != nil { tpl.IPAddresses = append(tpl.IPAddresses, ip) } else if email, err := mail.ParseAddress(req.Hosts[i]); err == nil && email != nil { tpl.EmailAddresses = append(tpl.EmailAddresses, email.Address) } else if uri, err := url.ParseRequestURI(req.Hosts[i]); err == nil && uri != nil { tpl.URIs = append(tpl.URIs, uri) } else { tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i]) } } if req.CA != nil { err = appendCAInfoToCSR(req.CA, &tpl) if err != nil { err = cferr.Wrap(cferr.CSRError, cferr.GenerationFailed, err) return } } csr, err = x509.CreateCertificateRequest(rand.Reader, &tpl, priv) if err != nil { log.Errorf("failed to generate a CSR: %v", err) err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err) return } block := pem.Block{ Type: "CERTIFICATE REQUEST", Bytes: csr, } log.Info("encoded CSR") csr = pem.EncodeToMemory(&block) return }
go
func Generate(priv crypto.Signer, req *CertificateRequest) (csr []byte, err error) { sigAlgo := helpers.SignerAlgo(priv) if sigAlgo == x509.UnknownSignatureAlgorithm { return nil, cferr.New(cferr.PrivateKeyError, cferr.Unavailable) } var tpl = x509.CertificateRequest{ Subject: req.Name(), SignatureAlgorithm: sigAlgo, } for i := range req.Hosts { if ip := net.ParseIP(req.Hosts[i]); ip != nil { tpl.IPAddresses = append(tpl.IPAddresses, ip) } else if email, err := mail.ParseAddress(req.Hosts[i]); err == nil && email != nil { tpl.EmailAddresses = append(tpl.EmailAddresses, email.Address) } else if uri, err := url.ParseRequestURI(req.Hosts[i]); err == nil && uri != nil { tpl.URIs = append(tpl.URIs, uri) } else { tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i]) } } if req.CA != nil { err = appendCAInfoToCSR(req.CA, &tpl) if err != nil { err = cferr.Wrap(cferr.CSRError, cferr.GenerationFailed, err) return } } csr, err = x509.CreateCertificateRequest(rand.Reader, &tpl, priv) if err != nil { log.Errorf("failed to generate a CSR: %v", err) err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err) return } block := pem.Block{ Type: "CERTIFICATE REQUEST", Bytes: csr, } log.Info("encoded CSR") csr = pem.EncodeToMemory(&block) return }
[ "func", "Generate", "(", "priv", "crypto", ".", "Signer", ",", "req", "*", "CertificateRequest", ")", "(", "csr", "[", "]", "byte", ",", "err", "error", ")", "{", "sigAlgo", ":=", "helpers", ".", "SignerAlgo", "(", "priv", ")", "\n", "if", "sigAlgo", "==", "x509", ".", "UnknownSignatureAlgorithm", "{", "return", "nil", ",", "cferr", ".", "New", "(", "cferr", ".", "PrivateKeyError", ",", "cferr", ".", "Unavailable", ")", "\n", "}", "\n\n", "var", "tpl", "=", "x509", ".", "CertificateRequest", "{", "Subject", ":", "req", ".", "Name", "(", ")", ",", "SignatureAlgorithm", ":", "sigAlgo", ",", "}", "\n\n", "for", "i", ":=", "range", "req", ".", "Hosts", "{", "if", "ip", ":=", "net", ".", "ParseIP", "(", "req", ".", "Hosts", "[", "i", "]", ")", ";", "ip", "!=", "nil", "{", "tpl", ".", "IPAddresses", "=", "append", "(", "tpl", ".", "IPAddresses", ",", "ip", ")", "\n", "}", "else", "if", "email", ",", "err", ":=", "mail", ".", "ParseAddress", "(", "req", ".", "Hosts", "[", "i", "]", ")", ";", "err", "==", "nil", "&&", "email", "!=", "nil", "{", "tpl", ".", "EmailAddresses", "=", "append", "(", "tpl", ".", "EmailAddresses", ",", "email", ".", "Address", ")", "\n", "}", "else", "if", "uri", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "req", ".", "Hosts", "[", "i", "]", ")", ";", "err", "==", "nil", "&&", "uri", "!=", "nil", "{", "tpl", ".", "URIs", "=", "append", "(", "tpl", ".", "URIs", ",", "uri", ")", "\n", "}", "else", "{", "tpl", ".", "DNSNames", "=", "append", "(", "tpl", ".", "DNSNames", ",", "req", ".", "Hosts", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n\n", "if", "req", ".", "CA", "!=", "nil", "{", "err", "=", "appendCAInfoToCSR", "(", "req", ".", "CA", ",", "&", "tpl", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "cferr", ".", "Wrap", "(", "cferr", ".", "CSRError", ",", "cferr", ".", "GenerationFailed", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "csr", ",", "err", "=", "x509", ".", "CreateCertificateRequest", "(", "rand", ".", "Reader", ",", "&", "tpl", ",", "priv", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "err", "=", "cferr", ".", "Wrap", "(", "cferr", ".", "CSRError", ",", "cferr", ".", "BadRequest", ",", "err", ")", "\n", "return", "\n", "}", "\n", "block", ":=", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "csr", ",", "}", "\n\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "csr", "=", "pem", ".", "EncodeToMemory", "(", "&", "block", ")", "\n", "return", "\n", "}" ]
// Generate creates a new CSR from a CertificateRequest structure and // an existing key. The KeyRequest field is ignored.
[ "Generate", "creates", "a", "new", "CSR", "from", "a", "CertificateRequest", "structure", "and", "an", "existing", "key", ".", "The", "KeyRequest", "field", "is", "ignored", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L370-L415
train
cloudflare/cfssl
csr/csr.go
appendCAInfoToCSR
func appendCAInfoToCSR(reqConf *CAConfig, csr *x509.CertificateRequest) error { pathlen := reqConf.PathLength if pathlen == 0 && !reqConf.PathLenZero { pathlen = -1 } val, err := asn1.Marshal(BasicConstraints{true, pathlen}) if err != nil { return err } csr.ExtraExtensions = []pkix.Extension{ { Id: asn1.ObjectIdentifier{2, 5, 29, 19}, Value: val, Critical: true, }, } return nil }
go
func appendCAInfoToCSR(reqConf *CAConfig, csr *x509.CertificateRequest) error { pathlen := reqConf.PathLength if pathlen == 0 && !reqConf.PathLenZero { pathlen = -1 } val, err := asn1.Marshal(BasicConstraints{true, pathlen}) if err != nil { return err } csr.ExtraExtensions = []pkix.Extension{ { Id: asn1.ObjectIdentifier{2, 5, 29, 19}, Value: val, Critical: true, }, } return nil }
[ "func", "appendCAInfoToCSR", "(", "reqConf", "*", "CAConfig", ",", "csr", "*", "x509", ".", "CertificateRequest", ")", "error", "{", "pathlen", ":=", "reqConf", ".", "PathLength", "\n", "if", "pathlen", "==", "0", "&&", "!", "reqConf", ".", "PathLenZero", "{", "pathlen", "=", "-", "1", "\n", "}", "\n", "val", ",", "err", ":=", "asn1", ".", "Marshal", "(", "BasicConstraints", "{", "true", ",", "pathlen", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "csr", ".", "ExtraExtensions", "=", "[", "]", "pkix", ".", "Extension", "{", "{", "Id", ":", "asn1", ".", "ObjectIdentifier", "{", "2", ",", "5", ",", "29", ",", "19", "}", ",", "Value", ":", "val", ",", "Critical", ":", "true", ",", "}", ",", "}", "\n\n", "return", "nil", "\n", "}" ]
// appendCAInfoToCSR appends CAConfig BasicConstraint extension to a CSR
[ "appendCAInfoToCSR", "appends", "CAConfig", "BasicConstraint", "extension", "to", "a", "CSR" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/csr/csr.go#L418-L438
train
cloudflare/cfssl
signer/signer.go
Profile
func Profile(s Signer, profile string) (*config.SigningProfile, error) { var p *config.SigningProfile policy := s.Policy() if policy != nil && policy.Profiles != nil && profile != "" { p = policy.Profiles[profile] } if p == nil && policy != nil { p = policy.Default } if p == nil { return nil, cferr.Wrap(cferr.APIClientError, cferr.ClientHTTPError, errors.New("profile must not be nil")) } return p, nil }
go
func Profile(s Signer, profile string) (*config.SigningProfile, error) { var p *config.SigningProfile policy := s.Policy() if policy != nil && policy.Profiles != nil && profile != "" { p = policy.Profiles[profile] } if p == nil && policy != nil { p = policy.Default } if p == nil { return nil, cferr.Wrap(cferr.APIClientError, cferr.ClientHTTPError, errors.New("profile must not be nil")) } return p, nil }
[ "func", "Profile", "(", "s", "Signer", ",", "profile", "string", ")", "(", "*", "config", ".", "SigningProfile", ",", "error", ")", "{", "var", "p", "*", "config", ".", "SigningProfile", "\n", "policy", ":=", "s", ".", "Policy", "(", ")", "\n", "if", "policy", "!=", "nil", "&&", "policy", ".", "Profiles", "!=", "nil", "&&", "profile", "!=", "\"", "\"", "{", "p", "=", "policy", ".", "Profiles", "[", "profile", "]", "\n", "}", "\n\n", "if", "p", "==", "nil", "&&", "policy", "!=", "nil", "{", "p", "=", "policy", ".", "Default", "\n", "}", "\n\n", "if", "p", "==", "nil", "{", "return", "nil", ",", "cferr", ".", "Wrap", "(", "cferr", ".", "APIClientError", ",", "cferr", ".", "ClientHTTPError", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "p", ",", "nil", "\n", "}" ]
// Profile gets the specific profile from the signer
[ "Profile", "gets", "the", "specific", "profile", "from", "the", "signer" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/signer/signer.go#L122-L137
train
cloudflare/cfssl
signer/signer.go
DefaultSigAlgo
func DefaultSigAlgo(priv crypto.Signer) x509.SignatureAlgorithm { pub := priv.Public() switch pub := pub.(type) { case *rsa.PublicKey: keySize := pub.N.BitLen() switch { case keySize >= 4096: return x509.SHA512WithRSA case keySize >= 3072: return x509.SHA384WithRSA case keySize >= 2048: return x509.SHA256WithRSA default: return x509.SHA1WithRSA } case *ecdsa.PublicKey: switch pub.Curve { case elliptic.P256(): return x509.ECDSAWithSHA256 case elliptic.P384(): return x509.ECDSAWithSHA384 case elliptic.P521(): return x509.ECDSAWithSHA512 default: return x509.ECDSAWithSHA1 } default: return x509.UnknownSignatureAlgorithm } }
go
func DefaultSigAlgo(priv crypto.Signer) x509.SignatureAlgorithm { pub := priv.Public() switch pub := pub.(type) { case *rsa.PublicKey: keySize := pub.N.BitLen() switch { case keySize >= 4096: return x509.SHA512WithRSA case keySize >= 3072: return x509.SHA384WithRSA case keySize >= 2048: return x509.SHA256WithRSA default: return x509.SHA1WithRSA } case *ecdsa.PublicKey: switch pub.Curve { case elliptic.P256(): return x509.ECDSAWithSHA256 case elliptic.P384(): return x509.ECDSAWithSHA384 case elliptic.P521(): return x509.ECDSAWithSHA512 default: return x509.ECDSAWithSHA1 } default: return x509.UnknownSignatureAlgorithm } }
[ "func", "DefaultSigAlgo", "(", "priv", "crypto", ".", "Signer", ")", "x509", ".", "SignatureAlgorithm", "{", "pub", ":=", "priv", ".", "Public", "(", ")", "\n", "switch", "pub", ":=", "pub", ".", "(", "type", ")", "{", "case", "*", "rsa", ".", "PublicKey", ":", "keySize", ":=", "pub", ".", "N", ".", "BitLen", "(", ")", "\n", "switch", "{", "case", "keySize", ">=", "4096", ":", "return", "x509", ".", "SHA512WithRSA", "\n", "case", "keySize", ">=", "3072", ":", "return", "x509", ".", "SHA384WithRSA", "\n", "case", "keySize", ">=", "2048", ":", "return", "x509", ".", "SHA256WithRSA", "\n", "default", ":", "return", "x509", ".", "SHA1WithRSA", "\n", "}", "\n", "case", "*", "ecdsa", ".", "PublicKey", ":", "switch", "pub", ".", "Curve", "{", "case", "elliptic", ".", "P256", "(", ")", ":", "return", "x509", ".", "ECDSAWithSHA256", "\n", "case", "elliptic", ".", "P384", "(", ")", ":", "return", "x509", ".", "ECDSAWithSHA384", "\n", "case", "elliptic", ".", "P521", "(", ")", ":", "return", "x509", ".", "ECDSAWithSHA512", "\n", "default", ":", "return", "x509", ".", "ECDSAWithSHA1", "\n", "}", "\n", "default", ":", "return", "x509", ".", "UnknownSignatureAlgorithm", "\n", "}", "\n", "}" ]
// DefaultSigAlgo returns an appropriate X.509 signature algorithm given // the CA's private key.
[ "DefaultSigAlgo", "returns", "an", "appropriate", "X", ".", "509", "signature", "algorithm", "given", "the", "CA", "s", "private", "key", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/signer/signer.go#L141-L170
train
cloudflare/cfssl
signer/signer.go
ParseCertificateRequest
func ParseCertificateRequest(s Signer, csrBytes []byte) (template *x509.Certificate, err error) { csrv, err := x509.ParseCertificateRequest(csrBytes) if err != nil { err = cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err) return } err = csrv.CheckSignature() if err != nil { err = cferr.Wrap(cferr.CSRError, cferr.KeyMismatch, err) return } template = &x509.Certificate{ Subject: csrv.Subject, PublicKeyAlgorithm: csrv.PublicKeyAlgorithm, PublicKey: csrv.PublicKey, SignatureAlgorithm: s.SigAlgo(), DNSNames: csrv.DNSNames, IPAddresses: csrv.IPAddresses, EmailAddresses: csrv.EmailAddresses, URIs: csrv.URIs, } for _, val := range csrv.Extensions { // Check the CSR for the X.509 BasicConstraints (RFC 5280, 4.2.1.9) // extension and append to template if necessary if val.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 19}) { var constraints csr.BasicConstraints var rest []byte if rest, err = asn1.Unmarshal(val.Value, &constraints); err != nil { return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err) } else if len(rest) != 0 { return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, errors.New("x509: trailing data after X.509 BasicConstraints")) } template.BasicConstraintsValid = true template.IsCA = constraints.IsCA template.MaxPathLen = constraints.MaxPathLen template.MaxPathLenZero = template.MaxPathLen == 0 } } return }
go
func ParseCertificateRequest(s Signer, csrBytes []byte) (template *x509.Certificate, err error) { csrv, err := x509.ParseCertificateRequest(csrBytes) if err != nil { err = cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err) return } err = csrv.CheckSignature() if err != nil { err = cferr.Wrap(cferr.CSRError, cferr.KeyMismatch, err) return } template = &x509.Certificate{ Subject: csrv.Subject, PublicKeyAlgorithm: csrv.PublicKeyAlgorithm, PublicKey: csrv.PublicKey, SignatureAlgorithm: s.SigAlgo(), DNSNames: csrv.DNSNames, IPAddresses: csrv.IPAddresses, EmailAddresses: csrv.EmailAddresses, URIs: csrv.URIs, } for _, val := range csrv.Extensions { // Check the CSR for the X.509 BasicConstraints (RFC 5280, 4.2.1.9) // extension and append to template if necessary if val.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 19}) { var constraints csr.BasicConstraints var rest []byte if rest, err = asn1.Unmarshal(val.Value, &constraints); err != nil { return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err) } else if len(rest) != 0 { return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, errors.New("x509: trailing data after X.509 BasicConstraints")) } template.BasicConstraintsValid = true template.IsCA = constraints.IsCA template.MaxPathLen = constraints.MaxPathLen template.MaxPathLenZero = template.MaxPathLen == 0 } } return }
[ "func", "ParseCertificateRequest", "(", "s", "Signer", ",", "csrBytes", "[", "]", "byte", ")", "(", "template", "*", "x509", ".", "Certificate", ",", "err", "error", ")", "{", "csrv", ",", "err", ":=", "x509", ".", "ParseCertificateRequest", "(", "csrBytes", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "cferr", ".", "Wrap", "(", "cferr", ".", "CSRError", ",", "cferr", ".", "ParseFailed", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "err", "=", "csrv", ".", "CheckSignature", "(", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "cferr", ".", "Wrap", "(", "cferr", ".", "CSRError", ",", "cferr", ".", "KeyMismatch", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "template", "=", "&", "x509", ".", "Certificate", "{", "Subject", ":", "csrv", ".", "Subject", ",", "PublicKeyAlgorithm", ":", "csrv", ".", "PublicKeyAlgorithm", ",", "PublicKey", ":", "csrv", ".", "PublicKey", ",", "SignatureAlgorithm", ":", "s", ".", "SigAlgo", "(", ")", ",", "DNSNames", ":", "csrv", ".", "DNSNames", ",", "IPAddresses", ":", "csrv", ".", "IPAddresses", ",", "EmailAddresses", ":", "csrv", ".", "EmailAddresses", ",", "URIs", ":", "csrv", ".", "URIs", ",", "}", "\n\n", "for", "_", ",", "val", ":=", "range", "csrv", ".", "Extensions", "{", "// Check the CSR for the X.509 BasicConstraints (RFC 5280, 4.2.1.9)", "// extension and append to template if necessary", "if", "val", ".", "Id", ".", "Equal", "(", "asn1", ".", "ObjectIdentifier", "{", "2", ",", "5", ",", "29", ",", "19", "}", ")", "{", "var", "constraints", "csr", ".", "BasicConstraints", "\n", "var", "rest", "[", "]", "byte", "\n\n", "if", "rest", ",", "err", "=", "asn1", ".", "Unmarshal", "(", "val", ".", "Value", ",", "&", "constraints", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "cferr", ".", "Wrap", "(", "cferr", ".", "CSRError", ",", "cferr", ".", "ParseFailed", ",", "err", ")", "\n", "}", "else", "if", "len", "(", "rest", ")", "!=", "0", "{", "return", "nil", ",", "cferr", ".", "Wrap", "(", "cferr", ".", "CSRError", ",", "cferr", ".", "ParseFailed", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "template", ".", "BasicConstraintsValid", "=", "true", "\n", "template", ".", "IsCA", "=", "constraints", ".", "IsCA", "\n", "template", ".", "MaxPathLen", "=", "constraints", ".", "MaxPathLen", "\n", "template", ".", "MaxPathLenZero", "=", "template", ".", "MaxPathLen", "==", "0", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// ParseCertificateRequest takes an incoming certificate request and // builds a certificate template from it.
[ "ParseCertificateRequest", "takes", "an", "incoming", "certificate", "request", "and", "builds", "a", "certificate", "template", "from", "it", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/signer/signer.go#L174-L219
train
cloudflare/cfssl
signer/signer.go
ComputeSKI
func ComputeSKI(template *x509.Certificate) ([]byte, error) { pub := template.PublicKey encodedPub, err := x509.MarshalPKIXPublicKey(pub) if err != nil { return nil, err } var subPKI subjectPublicKeyInfo _, err = asn1.Unmarshal(encodedPub, &subPKI) if err != nil { return nil, err } pubHash := sha1.Sum(subPKI.SubjectPublicKey.Bytes) return pubHash[:], nil }
go
func ComputeSKI(template *x509.Certificate) ([]byte, error) { pub := template.PublicKey encodedPub, err := x509.MarshalPKIXPublicKey(pub) if err != nil { return nil, err } var subPKI subjectPublicKeyInfo _, err = asn1.Unmarshal(encodedPub, &subPKI) if err != nil { return nil, err } pubHash := sha1.Sum(subPKI.SubjectPublicKey.Bytes) return pubHash[:], nil }
[ "func", "ComputeSKI", "(", "template", "*", "x509", ".", "Certificate", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "pub", ":=", "template", ".", "PublicKey", "\n", "encodedPub", ",", "err", ":=", "x509", ".", "MarshalPKIXPublicKey", "(", "pub", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "subPKI", "subjectPublicKeyInfo", "\n", "_", ",", "err", "=", "asn1", ".", "Unmarshal", "(", "encodedPub", ",", "&", "subPKI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pubHash", ":=", "sha1", ".", "Sum", "(", "subPKI", ".", "SubjectPublicKey", ".", "Bytes", ")", "\n", "return", "pubHash", "[", ":", "]", ",", "nil", "\n", "}" ]
// ComputeSKI derives an SKI from the certificate's public key in a // standard manner. This is done by computing the SHA-1 digest of the // SubjectPublicKeyInfo component of the certificate.
[ "ComputeSKI", "derives", "an", "SKI", "from", "the", "certificate", "s", "public", "key", "in", "a", "standard", "manner", ".", "This", "is", "done", "by", "computing", "the", "SHA", "-", "1", "digest", "of", "the", "SubjectPublicKeyInfo", "component", "of", "the", "certificate", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/signer/signer.go#L229-L244
train
cloudflare/cfssl
signer/signer.go
addPolicies
func addPolicies(template *x509.Certificate, policies []config.CertificatePolicy) error { asn1PolicyList := []policyInformation{} for _, policy := range policies { pi := policyInformation{ // The PolicyIdentifier is an OID assigned to a given issuer. PolicyIdentifier: asn1.ObjectIdentifier(policy.ID), } for _, qualifier := range policy.Qualifiers { switch qualifier.Type { case "id-qt-unotice": pi.Qualifiers = append(pi.Qualifiers, userNoticePolicyQualifier{ PolicyQualifierID: iDQTUserNotice, Qualifier: userNotice{ ExplicitText: qualifier.Value, }, }) case "id-qt-cps": pi.Qualifiers = append(pi.Qualifiers, cpsPolicyQualifier{ PolicyQualifierID: iDQTCertificationPracticeStatement, Qualifier: qualifier.Value, }) default: return errors.New("Invalid qualifier type in Policies " + qualifier.Type) } } asn1PolicyList = append(asn1PolicyList, pi) } asn1Bytes, err := asn1.Marshal(asn1PolicyList) if err != nil { return err } template.ExtraExtensions = append(template.ExtraExtensions, pkix.Extension{ Id: asn1.ObjectIdentifier{2, 5, 29, 32}, Critical: false, Value: asn1Bytes, }) return nil }
go
func addPolicies(template *x509.Certificate, policies []config.CertificatePolicy) error { asn1PolicyList := []policyInformation{} for _, policy := range policies { pi := policyInformation{ // The PolicyIdentifier is an OID assigned to a given issuer. PolicyIdentifier: asn1.ObjectIdentifier(policy.ID), } for _, qualifier := range policy.Qualifiers { switch qualifier.Type { case "id-qt-unotice": pi.Qualifiers = append(pi.Qualifiers, userNoticePolicyQualifier{ PolicyQualifierID: iDQTUserNotice, Qualifier: userNotice{ ExplicitText: qualifier.Value, }, }) case "id-qt-cps": pi.Qualifiers = append(pi.Qualifiers, cpsPolicyQualifier{ PolicyQualifierID: iDQTCertificationPracticeStatement, Qualifier: qualifier.Value, }) default: return errors.New("Invalid qualifier type in Policies " + qualifier.Type) } } asn1PolicyList = append(asn1PolicyList, pi) } asn1Bytes, err := asn1.Marshal(asn1PolicyList) if err != nil { return err } template.ExtraExtensions = append(template.ExtraExtensions, pkix.Extension{ Id: asn1.ObjectIdentifier{2, 5, 29, 32}, Critical: false, Value: asn1Bytes, }) return nil }
[ "func", "addPolicies", "(", "template", "*", "x509", ".", "Certificate", ",", "policies", "[", "]", "config", ".", "CertificatePolicy", ")", "error", "{", "asn1PolicyList", ":=", "[", "]", "policyInformation", "{", "}", "\n\n", "for", "_", ",", "policy", ":=", "range", "policies", "{", "pi", ":=", "policyInformation", "{", "// The PolicyIdentifier is an OID assigned to a given issuer.", "PolicyIdentifier", ":", "asn1", ".", "ObjectIdentifier", "(", "policy", ".", "ID", ")", ",", "}", "\n", "for", "_", ",", "qualifier", ":=", "range", "policy", ".", "Qualifiers", "{", "switch", "qualifier", ".", "Type", "{", "case", "\"", "\"", ":", "pi", ".", "Qualifiers", "=", "append", "(", "pi", ".", "Qualifiers", ",", "userNoticePolicyQualifier", "{", "PolicyQualifierID", ":", "iDQTUserNotice", ",", "Qualifier", ":", "userNotice", "{", "ExplicitText", ":", "qualifier", ".", "Value", ",", "}", ",", "}", ")", "\n", "case", "\"", "\"", ":", "pi", ".", "Qualifiers", "=", "append", "(", "pi", ".", "Qualifiers", ",", "cpsPolicyQualifier", "{", "PolicyQualifierID", ":", "iDQTCertificationPracticeStatement", ",", "Qualifier", ":", "qualifier", ".", "Value", ",", "}", ")", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"", "\"", "+", "qualifier", ".", "Type", ")", "\n", "}", "\n", "}", "\n", "asn1PolicyList", "=", "append", "(", "asn1PolicyList", ",", "pi", ")", "\n", "}", "\n\n", "asn1Bytes", ",", "err", ":=", "asn1", ".", "Marshal", "(", "asn1PolicyList", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "template", ".", "ExtraExtensions", "=", "append", "(", "template", ".", "ExtraExtensions", ",", "pkix", ".", "Extension", "{", "Id", ":", "asn1", ".", "ObjectIdentifier", "{", "2", ",", "5", ",", "29", ",", "32", "}", ",", "Critical", ":", "false", ",", "Value", ":", "asn1Bytes", ",", "}", ")", "\n", "return", "nil", "\n", "}" ]
// addPolicies adds Certificate Policies and optional Policy Qualifiers to a // certificate, based on the input config. Go's x509 library allows setting // Certificate Policies easily, but does not support nested Policy Qualifiers // under those policies. So we need to construct the ASN.1 structure ourselves.
[ "addPolicies", "adds", "Certificate", "Policies", "and", "optional", "Policy", "Qualifiers", "to", "a", "certificate", "based", "on", "the", "input", "config", ".", "Go", "s", "x509", "library", "allows", "setting", "Certificate", "Policies", "easily", "but", "does", "not", "support", "nested", "Policy", "Qualifiers", "under", "those", "policies", ".", "So", "we", "need", "to", "construct", "the", "ASN", ".", "1", "structure", "ourselves", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/signer/signer.go#L396-L438
train
cloudflare/cfssl
cli/ocspserve/ocspserve.go
ocspServerMain
func ocspServerMain(args []string, c cli.Config) error { var src ocsp.Source // serve doesn't support arguments. if len(args) > 0 { return errors.New("argument is provided but not defined; please refer to the usage by flag -h") } if c.Responses != "" { s, err := ocsp.NewSourceFromFile(c.Responses) if err != nil { return errors.New("unable to read response file") } src = s } else if c.DBConfigFile != "" { s, err := ocsp.NewSourceFromDB(c.DBConfigFile) if err != nil { return errors.New("unable to read configuration file") } src = s } else { return errors.New( "no response file or db-config provided, please set the one of these using either -responses or -db-config flags", ) } log.Info("Registering OCSP responder handler") http.Handle(c.Path, ocsp.NewResponder(src, nil)) addr := fmt.Sprintf("%s:%d", c.Address, c.Port) log.Info("Now listening on ", addr) return http.ListenAndServe(addr, nil) }
go
func ocspServerMain(args []string, c cli.Config) error { var src ocsp.Source // serve doesn't support arguments. if len(args) > 0 { return errors.New("argument is provided but not defined; please refer to the usage by flag -h") } if c.Responses != "" { s, err := ocsp.NewSourceFromFile(c.Responses) if err != nil { return errors.New("unable to read response file") } src = s } else if c.DBConfigFile != "" { s, err := ocsp.NewSourceFromDB(c.DBConfigFile) if err != nil { return errors.New("unable to read configuration file") } src = s } else { return errors.New( "no response file or db-config provided, please set the one of these using either -responses or -db-config flags", ) } log.Info("Registering OCSP responder handler") http.Handle(c.Path, ocsp.NewResponder(src, nil)) addr := fmt.Sprintf("%s:%d", c.Address, c.Port) log.Info("Now listening on ", addr) return http.ListenAndServe(addr, nil) }
[ "func", "ocspServerMain", "(", "args", "[", "]", "string", ",", "c", "cli", ".", "Config", ")", "error", "{", "var", "src", "ocsp", ".", "Source", "\n", "// serve doesn't support arguments.", "if", "len", "(", "args", ")", ">", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "c", ".", "Responses", "!=", "\"", "\"", "{", "s", ",", "err", ":=", "ocsp", ".", "NewSourceFromFile", "(", "c", ".", "Responses", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "src", "=", "s", "\n", "}", "else", "if", "c", ".", "DBConfigFile", "!=", "\"", "\"", "{", "s", ",", "err", ":=", "ocsp", ".", "NewSourceFromDB", "(", "c", ".", "DBConfigFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "src", "=", "s", "\n", "}", "else", "{", "return", "errors", ".", "New", "(", "\"", "\"", ",", ")", "\n", "}", "\n\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "http", ".", "Handle", "(", "c", ".", "Path", ",", "ocsp", ".", "NewResponder", "(", "src", ",", "nil", ")", ")", "\n\n", "addr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "Address", ",", "c", ".", "Port", ")", "\n", "log", ".", "Info", "(", "\"", "\"", ",", "addr", ")", "\n", "return", "http", ".", "ListenAndServe", "(", "addr", ",", "nil", ")", "\n", "}" ]
// ocspServerMain is the command line entry point to the OCSP responder. // It sets up a new HTTP server that responds to OCSP requests.
[ "ocspServerMain", "is", "the", "command", "line", "entry", "point", "to", "the", "OCSP", "responder", ".", "It", "sets", "up", "a", "new", "HTTP", "server", "that", "responds", "to", "OCSP", "requests", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cli/ocspserve/ocspserve.go#L28-L59
train
cloudflare/cfssl
scan/crypto/tls/key_agreement.go
sha1Hash
func sha1Hash(slices [][]byte) []byte { hsha1 := sha1.New() for _, slice := range slices { hsha1.Write(slice) } return hsha1.Sum(nil) }
go
func sha1Hash(slices [][]byte) []byte { hsha1 := sha1.New() for _, slice := range slices { hsha1.Write(slice) } return hsha1.Sum(nil) }
[ "func", "sha1Hash", "(", "slices", "[", "]", "[", "]", "byte", ")", "[", "]", "byte", "{", "hsha1", ":=", "sha1", ".", "New", "(", ")", "\n", "for", "_", ",", "slice", ":=", "range", "slices", "{", "hsha1", ".", "Write", "(", "slice", ")", "\n", "}", "\n", "return", "hsha1", ".", "Sum", "(", "nil", ")", "\n", "}" ]
// sha1Hash calculates a SHA1 hash over the given byte slices.
[ "sha1Hash", "calculates", "a", "SHA1", "hash", "over", "the", "given", "byte", "slices", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/key_agreement.go#L89-L95
train
cloudflare/cfssl
scan/crypto/tls/key_agreement.go
md5SHA1Hash
func md5SHA1Hash(slices [][]byte) []byte { md5sha1 := make([]byte, md5.Size+sha1.Size) hmd5 := md5.New() for _, slice := range slices { hmd5.Write(slice) } copy(md5sha1, hmd5.Sum(nil)) copy(md5sha1[md5.Size:], sha1Hash(slices)) return md5sha1 }
go
func md5SHA1Hash(slices [][]byte) []byte { md5sha1 := make([]byte, md5.Size+sha1.Size) hmd5 := md5.New() for _, slice := range slices { hmd5.Write(slice) } copy(md5sha1, hmd5.Sum(nil)) copy(md5sha1[md5.Size:], sha1Hash(slices)) return md5sha1 }
[ "func", "md5SHA1Hash", "(", "slices", "[", "]", "[", "]", "byte", ")", "[", "]", "byte", "{", "md5sha1", ":=", "make", "(", "[", "]", "byte", ",", "md5", ".", "Size", "+", "sha1", ".", "Size", ")", "\n", "hmd5", ":=", "md5", ".", "New", "(", ")", "\n", "for", "_", ",", "slice", ":=", "range", "slices", "{", "hmd5", ".", "Write", "(", "slice", ")", "\n", "}", "\n", "copy", "(", "md5sha1", ",", "hmd5", ".", "Sum", "(", "nil", ")", ")", "\n", "copy", "(", "md5sha1", "[", "md5", ".", "Size", ":", "]", ",", "sha1Hash", "(", "slices", ")", ")", "\n", "return", "md5sha1", "\n", "}" ]
// md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the // concatenation of an MD5 and SHA1 hash.
[ "md5SHA1Hash", "implements", "TLS", "1", ".", "0", "s", "hybrid", "hash", "function", "which", "consists", "of", "the", "concatenation", "of", "an", "MD5", "and", "SHA1", "hash", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/key_agreement.go#L99-L108
train
cloudflare/cfssl
scan/crypto/tls/key_agreement.go
hashForServerKeyExchange
func hashForServerKeyExchange(sigAndHash signatureAndHash, version uint16, slices ...[]byte) ([]byte, crypto.Hash, error) { if version >= VersionTLS12 { if !isSupportedSignatureAndHash(sigAndHash, supportedSignatureAlgorithms) { return nil, crypto.Hash(0), errors.New("tls: unsupported hash function used by peer") } hashFunc, err := lookupTLSHash(sigAndHash.hash) if err != nil { return nil, crypto.Hash(0), err } h := hashFunc.New() for _, slice := range slices { h.Write(slice) } digest := h.Sum(nil) return digest, hashFunc, nil } if sigAndHash.signature == signatureECDSA { return sha1Hash(slices), crypto.SHA1, nil } return md5SHA1Hash(slices), crypto.MD5SHA1, nil }
go
func hashForServerKeyExchange(sigAndHash signatureAndHash, version uint16, slices ...[]byte) ([]byte, crypto.Hash, error) { if version >= VersionTLS12 { if !isSupportedSignatureAndHash(sigAndHash, supportedSignatureAlgorithms) { return nil, crypto.Hash(0), errors.New("tls: unsupported hash function used by peer") } hashFunc, err := lookupTLSHash(sigAndHash.hash) if err != nil { return nil, crypto.Hash(0), err } h := hashFunc.New() for _, slice := range slices { h.Write(slice) } digest := h.Sum(nil) return digest, hashFunc, nil } if sigAndHash.signature == signatureECDSA { return sha1Hash(slices), crypto.SHA1, nil } return md5SHA1Hash(slices), crypto.MD5SHA1, nil }
[ "func", "hashForServerKeyExchange", "(", "sigAndHash", "signatureAndHash", ",", "version", "uint16", ",", "slices", "...", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "crypto", ".", "Hash", ",", "error", ")", "{", "if", "version", ">=", "VersionTLS12", "{", "if", "!", "isSupportedSignatureAndHash", "(", "sigAndHash", ",", "supportedSignatureAlgorithms", ")", "{", "return", "nil", ",", "crypto", ".", "Hash", "(", "0", ")", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "hashFunc", ",", "err", ":=", "lookupTLSHash", "(", "sigAndHash", ".", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "crypto", ".", "Hash", "(", "0", ")", ",", "err", "\n", "}", "\n", "h", ":=", "hashFunc", ".", "New", "(", ")", "\n", "for", "_", ",", "slice", ":=", "range", "slices", "{", "h", ".", "Write", "(", "slice", ")", "\n", "}", "\n", "digest", ":=", "h", ".", "Sum", "(", "nil", ")", "\n", "return", "digest", ",", "hashFunc", ",", "nil", "\n", "}", "\n", "if", "sigAndHash", ".", "signature", "==", "signatureECDSA", "{", "return", "sha1Hash", "(", "slices", ")", ",", "crypto", ".", "SHA1", ",", "nil", "\n", "}", "\n", "return", "md5SHA1Hash", "(", "slices", ")", ",", "crypto", ".", "MD5SHA1", ",", "nil", "\n", "}" ]
// hashForServerKeyExchange hashes the given slices and returns their digest // and the identifier of the hash function used. The sigAndHash argument is // only used for >= TLS 1.2 and precisely identifies the hash function to use.
[ "hashForServerKeyExchange", "hashes", "the", "given", "slices", "and", "returns", "their", "digest", "and", "the", "identifier", "of", "the", "hash", "function", "used", ".", "The", "sigAndHash", "argument", "is", "only", "used", "for", ">", "=", "TLS", "1", ".", "2", "and", "precisely", "identifies", "the", "hash", "function", "to", "use", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/key_agreement.go#L113-L133
train
cloudflare/cfssl
scan/crypto/tls/key_agreement.go
pickTLS12HashForSignature
func pickTLS12HashForSignature(sigType uint8, clientList []signatureAndHash) (uint8, error) { if len(clientList) == 0 { // If the client didn't specify any signature_algorithms // extension then we can assume that it supports SHA1. See // http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 return hashSHA1, nil } for _, sigAndHash := range clientList { if sigAndHash.signature != sigType { continue } if isSupportedSignatureAndHash(sigAndHash, supportedSignatureAlgorithms) { return sigAndHash.hash, nil } } return 0, errors.New("tls: client doesn't support any common hash functions") }
go
func pickTLS12HashForSignature(sigType uint8, clientList []signatureAndHash) (uint8, error) { if len(clientList) == 0 { // If the client didn't specify any signature_algorithms // extension then we can assume that it supports SHA1. See // http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 return hashSHA1, nil } for _, sigAndHash := range clientList { if sigAndHash.signature != sigType { continue } if isSupportedSignatureAndHash(sigAndHash, supportedSignatureAlgorithms) { return sigAndHash.hash, nil } } return 0, errors.New("tls: client doesn't support any common hash functions") }
[ "func", "pickTLS12HashForSignature", "(", "sigType", "uint8", ",", "clientList", "[", "]", "signatureAndHash", ")", "(", "uint8", ",", "error", ")", "{", "if", "len", "(", "clientList", ")", "==", "0", "{", "// If the client didn't specify any signature_algorithms", "// extension then we can assume that it supports SHA1. See", "// http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1", "return", "hashSHA1", ",", "nil", "\n", "}", "\n\n", "for", "_", ",", "sigAndHash", ":=", "range", "clientList", "{", "if", "sigAndHash", ".", "signature", "!=", "sigType", "{", "continue", "\n", "}", "\n", "if", "isSupportedSignatureAndHash", "(", "sigAndHash", ",", "supportedSignatureAlgorithms", ")", "{", "return", "sigAndHash", ".", "hash", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// pickTLS12HashForSignature returns a TLS 1.2 hash identifier for signing a // ServerKeyExchange given the signature type being used and the client's // advertised list of supported signature and hash combinations.
[ "pickTLS12HashForSignature", "returns", "a", "TLS", "1", ".", "2", "hash", "identifier", "for", "signing", "a", "ServerKeyExchange", "given", "the", "signature", "type", "being", "used", "and", "the", "client", "s", "advertised", "list", "of", "supported", "signature", "and", "hash", "combinations", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/key_agreement.go#L138-L156
train
cloudflare/cfssl
api/sign/sign.go
NewHandler
func NewHandler(caFile, caKeyFile string, policy *config.Signing) (http.Handler, error) { root := universal.Root{ Config: map[string]string{ "cert-file": caFile, "key-file": caKeyFile, }, } s, err := universal.NewSigner(root, policy) if err != nil { log.Errorf("setting up signer failed: %v", err) return nil, err } return signhandler.NewHandlerFromSigner(s) }
go
func NewHandler(caFile, caKeyFile string, policy *config.Signing) (http.Handler, error) { root := universal.Root{ Config: map[string]string{ "cert-file": caFile, "key-file": caKeyFile, }, } s, err := universal.NewSigner(root, policy) if err != nil { log.Errorf("setting up signer failed: %v", err) return nil, err } return signhandler.NewHandlerFromSigner(s) }
[ "func", "NewHandler", "(", "caFile", ",", "caKeyFile", "string", ",", "policy", "*", "config", ".", "Signing", ")", "(", "http", ".", "Handler", ",", "error", ")", "{", "root", ":=", "universal", ".", "Root", "{", "Config", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "caFile", ",", "\"", "\"", ":", "caKeyFile", ",", "}", ",", "}", "\n", "s", ",", "err", ":=", "universal", ".", "NewSigner", "(", "root", ",", "policy", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "signhandler", ".", "NewHandlerFromSigner", "(", "s", ")", "\n", "}" ]
// NewHandler generates a new Handler using the certificate // authority private key and certficate to sign certificates. If remote // is not an empty string, the handler will send signature requests to // the CFSSL instance contained in remote by default.
[ "NewHandler", "generates", "a", "new", "Handler", "using", "the", "certificate", "authority", "private", "key", "and", "certficate", "to", "sign", "certificates", ".", "If", "remote", "is", "not", "an", "empty", "string", "the", "handler", "will", "send", "signature", "requests", "to", "the", "CFSSL", "instance", "contained", "in", "remote", "by", "default", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/api/sign/sign.go#L17-L31
train
cloudflare/cfssl
scan/crypto/tls/conn.go
prepareCipherSpec
func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) { hc.version = version hc.nextCipher = cipher hc.nextMac = mac }
go
func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) { hc.version = version hc.nextCipher = cipher hc.nextMac = mac }
[ "func", "(", "hc", "*", "halfConn", ")", "prepareCipherSpec", "(", "version", "uint16", ",", "cipher", "interface", "{", "}", ",", "mac", "macFunction", ")", "{", "hc", ".", "version", "=", "version", "\n", "hc", ".", "nextCipher", "=", "cipher", "\n", "hc", ".", "nextMac", "=", "mac", "\n", "}" ]
// prepareCipherSpec sets the encryption and MAC states // that a subsequent changeCipherSpec will use.
[ "prepareCipherSpec", "sets", "the", "encryption", "and", "MAC", "states", "that", "a", "subsequent", "changeCipherSpec", "will", "use", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L136-L140
train
cloudflare/cfssl
scan/crypto/tls/conn.go
changeCipherSpec
func (hc *halfConn) changeCipherSpec() error { if hc.nextCipher == nil { return alertInternalError } hc.cipher = hc.nextCipher hc.mac = hc.nextMac hc.nextCipher = nil hc.nextMac = nil for i := range hc.seq { hc.seq[i] = 0 } return nil }
go
func (hc *halfConn) changeCipherSpec() error { if hc.nextCipher == nil { return alertInternalError } hc.cipher = hc.nextCipher hc.mac = hc.nextMac hc.nextCipher = nil hc.nextMac = nil for i := range hc.seq { hc.seq[i] = 0 } return nil }
[ "func", "(", "hc", "*", "halfConn", ")", "changeCipherSpec", "(", ")", "error", "{", "if", "hc", ".", "nextCipher", "==", "nil", "{", "return", "alertInternalError", "\n", "}", "\n", "hc", ".", "cipher", "=", "hc", ".", "nextCipher", "\n", "hc", ".", "mac", "=", "hc", ".", "nextMac", "\n", "hc", ".", "nextCipher", "=", "nil", "\n", "hc", ".", "nextMac", "=", "nil", "\n", "for", "i", ":=", "range", "hc", ".", "seq", "{", "hc", ".", "seq", "[", "i", "]", "=", "0", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// changeCipherSpec changes the encryption and MAC states // to the ones previously passed to prepareCipherSpec.
[ "changeCipherSpec", "changes", "the", "encryption", "and", "MAC", "states", "to", "the", "ones", "previously", "passed", "to", "prepareCipherSpec", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L144-L156
train
cloudflare/cfssl
scan/crypto/tls/conn.go
incSeq
func (hc *halfConn) incSeq() { for i := 7; i >= 0; i-- { hc.seq[i]++ if hc.seq[i] != 0 { return } } // Not allowed to let sequence number wrap. // Instead, must renegotiate before it does. // Not likely enough to bother. panic("TLS: sequence number wraparound") }
go
func (hc *halfConn) incSeq() { for i := 7; i >= 0; i-- { hc.seq[i]++ if hc.seq[i] != 0 { return } } // Not allowed to let sequence number wrap. // Instead, must renegotiate before it does. // Not likely enough to bother. panic("TLS: sequence number wraparound") }
[ "func", "(", "hc", "*", "halfConn", ")", "incSeq", "(", ")", "{", "for", "i", ":=", "7", ";", "i", ">=", "0", ";", "i", "--", "{", "hc", ".", "seq", "[", "i", "]", "++", "\n", "if", "hc", ".", "seq", "[", "i", "]", "!=", "0", "{", "return", "\n", "}", "\n", "}", "\n\n", "// Not allowed to let sequence number wrap.", "// Instead, must renegotiate before it does.", "// Not likely enough to bother.", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// incSeq increments the sequence number.
[ "incSeq", "increments", "the", "sequence", "number", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L159-L171
train
cloudflare/cfssl
scan/crypto/tls/conn.go
removePadding
func removePadding(payload []byte) ([]byte, byte) { if len(payload) < 1 { return payload, 0 } paddingLen := payload[len(payload)-1] t := uint(len(payload)-1) - uint(paddingLen) // if len(payload) >= (paddingLen - 1) then the MSB of t is zero good := byte(int32(^t) >> 31) toCheck := 255 // the maximum possible padding length // The length of the padded data is public, so we can use an if here if toCheck+1 > len(payload) { toCheck = len(payload) - 1 } for i := 0; i < toCheck; i++ { t := uint(paddingLen) - uint(i) // if i <= paddingLen then the MSB of t is zero mask := byte(int32(^t) >> 31) b := payload[len(payload)-1-i] good &^= mask&paddingLen ^ mask&b } // We AND together the bits of good and replicate the result across // all the bits. good &= good << 4 good &= good << 2 good &= good << 1 good = uint8(int8(good) >> 7) toRemove := good&paddingLen + 1 return payload[:len(payload)-int(toRemove)], good }
go
func removePadding(payload []byte) ([]byte, byte) { if len(payload) < 1 { return payload, 0 } paddingLen := payload[len(payload)-1] t := uint(len(payload)-1) - uint(paddingLen) // if len(payload) >= (paddingLen - 1) then the MSB of t is zero good := byte(int32(^t) >> 31) toCheck := 255 // the maximum possible padding length // The length of the padded data is public, so we can use an if here if toCheck+1 > len(payload) { toCheck = len(payload) - 1 } for i := 0; i < toCheck; i++ { t := uint(paddingLen) - uint(i) // if i <= paddingLen then the MSB of t is zero mask := byte(int32(^t) >> 31) b := payload[len(payload)-1-i] good &^= mask&paddingLen ^ mask&b } // We AND together the bits of good and replicate the result across // all the bits. good &= good << 4 good &= good << 2 good &= good << 1 good = uint8(int8(good) >> 7) toRemove := good&paddingLen + 1 return payload[:len(payload)-int(toRemove)], good }
[ "func", "removePadding", "(", "payload", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "byte", ")", "{", "if", "len", "(", "payload", ")", "<", "1", "{", "return", "payload", ",", "0", "\n", "}", "\n\n", "paddingLen", ":=", "payload", "[", "len", "(", "payload", ")", "-", "1", "]", "\n", "t", ":=", "uint", "(", "len", "(", "payload", ")", "-", "1", ")", "-", "uint", "(", "paddingLen", ")", "\n", "// if len(payload) >= (paddingLen - 1) then the MSB of t is zero", "good", ":=", "byte", "(", "int32", "(", "^", "t", ")", ">>", "31", ")", "\n\n", "toCheck", ":=", "255", "// the maximum possible padding length", "\n", "// The length of the padded data is public, so we can use an if here", "if", "toCheck", "+", "1", ">", "len", "(", "payload", ")", "{", "toCheck", "=", "len", "(", "payload", ")", "-", "1", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "toCheck", ";", "i", "++", "{", "t", ":=", "uint", "(", "paddingLen", ")", "-", "uint", "(", "i", ")", "\n", "// if i <= paddingLen then the MSB of t is zero", "mask", ":=", "byte", "(", "int32", "(", "^", "t", ")", ">>", "31", ")", "\n", "b", ":=", "payload", "[", "len", "(", "payload", ")", "-", "1", "-", "i", "]", "\n", "good", "&^=", "mask", "&", "paddingLen", "^", "mask", "&", "b", "\n", "}", "\n\n", "// We AND together the bits of good and replicate the result across", "// all the bits.", "good", "&=", "good", "<<", "4", "\n", "good", "&=", "good", "<<", "2", "\n", "good", "&=", "good", "<<", "1", "\n", "good", "=", "uint8", "(", "int8", "(", "good", ")", ">>", "7", ")", "\n\n", "toRemove", ":=", "good", "&", "paddingLen", "+", "1", "\n", "return", "payload", "[", ":", "len", "(", "payload", ")", "-", "int", "(", "toRemove", ")", "]", ",", "good", "\n", "}" ]
// removePadding returns an unpadded slice, in constant time, which is a prefix // of the input. It also returns a byte which is equal to 255 if the padding // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
[ "removePadding", "returns", "an", "unpadded", "slice", "in", "constant", "time", "which", "is", "a", "prefix", "of", "the", "input", ".", "It", "also", "returns", "a", "byte", "which", "is", "equal", "to", "255", "if", "the", "padding", "was", "valid", "and", "0", "otherwise", ".", "See", "RFC", "2246", "section", "6", ".", "2", ".", "3", ".", "2" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L183-L216
train
cloudflare/cfssl
scan/crypto/tls/conn.go
removePaddingSSL30
func removePaddingSSL30(payload []byte) ([]byte, byte) { if len(payload) < 1 { return payload, 0 } paddingLen := int(payload[len(payload)-1]) + 1 if paddingLen > len(payload) { return payload, 0 } return payload[:len(payload)-paddingLen], 255 }
go
func removePaddingSSL30(payload []byte) ([]byte, byte) { if len(payload) < 1 { return payload, 0 } paddingLen := int(payload[len(payload)-1]) + 1 if paddingLen > len(payload) { return payload, 0 } return payload[:len(payload)-paddingLen], 255 }
[ "func", "removePaddingSSL30", "(", "payload", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "byte", ")", "{", "if", "len", "(", "payload", ")", "<", "1", "{", "return", "payload", ",", "0", "\n", "}", "\n\n", "paddingLen", ":=", "int", "(", "payload", "[", "len", "(", "payload", ")", "-", "1", "]", ")", "+", "1", "\n", "if", "paddingLen", ">", "len", "(", "payload", ")", "{", "return", "payload", ",", "0", "\n", "}", "\n\n", "return", "payload", "[", ":", "len", "(", "payload", ")", "-", "paddingLen", "]", ",", "255", "\n", "}" ]
// removePaddingSSL30 is a replacement for removePadding in the case that the // protocol version is SSLv3. In this version, the contents of the padding // are random and cannot be checked.
[ "removePaddingSSL30", "is", "a", "replacement", "for", "removePadding", "in", "the", "case", "that", "the", "protocol", "version", "is", "SSLv3", ".", "In", "this", "version", "the", "contents", "of", "the", "padding", "are", "random", "and", "cannot", "be", "checked", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L221-L232
train
cloudflare/cfssl
scan/crypto/tls/conn.go
padToBlockSize
func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) { overrun := len(payload) % blockSize paddingLen := blockSize - overrun prefix = payload[:len(payload)-overrun] finalBlock = make([]byte, blockSize) copy(finalBlock, payload[len(payload)-overrun:]) for i := overrun; i < blockSize; i++ { finalBlock[i] = byte(paddingLen - 1) } return }
go
func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) { overrun := len(payload) % blockSize paddingLen := blockSize - overrun prefix = payload[:len(payload)-overrun] finalBlock = make([]byte, blockSize) copy(finalBlock, payload[len(payload)-overrun:]) for i := overrun; i < blockSize; i++ { finalBlock[i] = byte(paddingLen - 1) } return }
[ "func", "padToBlockSize", "(", "payload", "[", "]", "byte", ",", "blockSize", "int", ")", "(", "prefix", ",", "finalBlock", "[", "]", "byte", ")", "{", "overrun", ":=", "len", "(", "payload", ")", "%", "blockSize", "\n", "paddingLen", ":=", "blockSize", "-", "overrun", "\n", "prefix", "=", "payload", "[", ":", "len", "(", "payload", ")", "-", "overrun", "]", "\n", "finalBlock", "=", "make", "(", "[", "]", "byte", ",", "blockSize", ")", "\n", "copy", "(", "finalBlock", ",", "payload", "[", "len", "(", "payload", ")", "-", "overrun", ":", "]", ")", "\n", "for", "i", ":=", "overrun", ";", "i", "<", "blockSize", ";", "i", "++", "{", "finalBlock", "[", "i", "]", "=", "byte", "(", "paddingLen", "-", "1", ")", "\n", "}", "\n", "return", "\n", "}" ]
// padToBlockSize calculates the needed padding block, if any, for a payload. // On exit, prefix aliases payload and extends to the end of the last full // block of payload. finalBlock is a fresh slice which contains the contents of // any suffix of payload as well as the needed padding to make finalBlock a // full block.
[ "padToBlockSize", "calculates", "the", "needed", "padding", "block", "if", "any", "for", "a", "payload", ".", "On", "exit", "prefix", "aliases", "payload", "and", "extends", "to", "the", "end", "of", "the", "last", "full", "block", "of", "payload", ".", "finalBlock", "is", "a", "fresh", "slice", "which", "contains", "the", "contents", "of", "any", "suffix", "of", "payload", "as", "well", "as", "the", "needed", "padding", "to", "make", "finalBlock", "a", "full", "block", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L349-L359
train
cloudflare/cfssl
scan/crypto/tls/conn.go
encrypt
func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) { // mac if hc.mac != nil { mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:]) n := len(b.data) b.resize(n + len(mac)) copy(b.data[n:], mac) hc.outDigestBuf = mac } payload := b.data[recordHeaderLen:] // encrypt if hc.cipher != nil { switch c := hc.cipher.(type) { case cipher.Stream: c.XORKeyStream(payload, payload) case cipher.AEAD: payloadLen := len(b.data) - recordHeaderLen - explicitIVLen b.resize(len(b.data) + c.Overhead()) nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] payload := b.data[recordHeaderLen+explicitIVLen:] payload = payload[:payloadLen] copy(hc.additionalData[:], hc.seq[:]) copy(hc.additionalData[8:], b.data[:3]) hc.additionalData[11] = byte(payloadLen >> 8) hc.additionalData[12] = byte(payloadLen) c.Seal(payload[:0], nonce, payload, hc.additionalData[:]) case cbcMode: blockSize := c.BlockSize() if explicitIVLen > 0 { c.SetIV(payload[:explicitIVLen]) payload = payload[explicitIVLen:] } prefix, finalBlock := padToBlockSize(payload, blockSize) b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock)) c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix) c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock) default: panic("unknown cipher type") } } // update length to include MAC and any block padding needed. n := len(b.data) - recordHeaderLen b.data[3] = byte(n >> 8) b.data[4] = byte(n) hc.incSeq() return true, 0 }
go
func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) { // mac if hc.mac != nil { mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:]) n := len(b.data) b.resize(n + len(mac)) copy(b.data[n:], mac) hc.outDigestBuf = mac } payload := b.data[recordHeaderLen:] // encrypt if hc.cipher != nil { switch c := hc.cipher.(type) { case cipher.Stream: c.XORKeyStream(payload, payload) case cipher.AEAD: payloadLen := len(b.data) - recordHeaderLen - explicitIVLen b.resize(len(b.data) + c.Overhead()) nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] payload := b.data[recordHeaderLen+explicitIVLen:] payload = payload[:payloadLen] copy(hc.additionalData[:], hc.seq[:]) copy(hc.additionalData[8:], b.data[:3]) hc.additionalData[11] = byte(payloadLen >> 8) hc.additionalData[12] = byte(payloadLen) c.Seal(payload[:0], nonce, payload, hc.additionalData[:]) case cbcMode: blockSize := c.BlockSize() if explicitIVLen > 0 { c.SetIV(payload[:explicitIVLen]) payload = payload[explicitIVLen:] } prefix, finalBlock := padToBlockSize(payload, blockSize) b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock)) c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix) c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock) default: panic("unknown cipher type") } } // update length to include MAC and any block padding needed. n := len(b.data) - recordHeaderLen b.data[3] = byte(n >> 8) b.data[4] = byte(n) hc.incSeq() return true, 0 }
[ "func", "(", "hc", "*", "halfConn", ")", "encrypt", "(", "b", "*", "block", ",", "explicitIVLen", "int", ")", "(", "bool", ",", "alert", ")", "{", "// mac", "if", "hc", ".", "mac", "!=", "nil", "{", "mac", ":=", "hc", ".", "mac", ".", "MAC", "(", "hc", ".", "outDigestBuf", ",", "hc", ".", "seq", "[", "0", ":", "]", ",", "b", ".", "data", "[", ":", "recordHeaderLen", "]", ",", "b", ".", "data", "[", "recordHeaderLen", "+", "explicitIVLen", ":", "]", ")", "\n\n", "n", ":=", "len", "(", "b", ".", "data", ")", "\n", "b", ".", "resize", "(", "n", "+", "len", "(", "mac", ")", ")", "\n", "copy", "(", "b", ".", "data", "[", "n", ":", "]", ",", "mac", ")", "\n", "hc", ".", "outDigestBuf", "=", "mac", "\n", "}", "\n\n", "payload", ":=", "b", ".", "data", "[", "recordHeaderLen", ":", "]", "\n\n", "// encrypt", "if", "hc", ".", "cipher", "!=", "nil", "{", "switch", "c", ":=", "hc", ".", "cipher", ".", "(", "type", ")", "{", "case", "cipher", ".", "Stream", ":", "c", ".", "XORKeyStream", "(", "payload", ",", "payload", ")", "\n", "case", "cipher", ".", "AEAD", ":", "payloadLen", ":=", "len", "(", "b", ".", "data", ")", "-", "recordHeaderLen", "-", "explicitIVLen", "\n", "b", ".", "resize", "(", "len", "(", "b", ".", "data", ")", "+", "c", ".", "Overhead", "(", ")", ")", "\n", "nonce", ":=", "b", ".", "data", "[", "recordHeaderLen", ":", "recordHeaderLen", "+", "explicitIVLen", "]", "\n", "payload", ":=", "b", ".", "data", "[", "recordHeaderLen", "+", "explicitIVLen", ":", "]", "\n", "payload", "=", "payload", "[", ":", "payloadLen", "]", "\n\n", "copy", "(", "hc", ".", "additionalData", "[", ":", "]", ",", "hc", ".", "seq", "[", ":", "]", ")", "\n", "copy", "(", "hc", ".", "additionalData", "[", "8", ":", "]", ",", "b", ".", "data", "[", ":", "3", "]", ")", "\n", "hc", ".", "additionalData", "[", "11", "]", "=", "byte", "(", "payloadLen", ">>", "8", ")", "\n", "hc", ".", "additionalData", "[", "12", "]", "=", "byte", "(", "payloadLen", ")", "\n\n", "c", ".", "Seal", "(", "payload", "[", ":", "0", "]", ",", "nonce", ",", "payload", ",", "hc", ".", "additionalData", "[", ":", "]", ")", "\n", "case", "cbcMode", ":", "blockSize", ":=", "c", ".", "BlockSize", "(", ")", "\n", "if", "explicitIVLen", ">", "0", "{", "c", ".", "SetIV", "(", "payload", "[", ":", "explicitIVLen", "]", ")", "\n", "payload", "=", "payload", "[", "explicitIVLen", ":", "]", "\n", "}", "\n", "prefix", ",", "finalBlock", ":=", "padToBlockSize", "(", "payload", ",", "blockSize", ")", "\n", "b", ".", "resize", "(", "recordHeaderLen", "+", "explicitIVLen", "+", "len", "(", "prefix", ")", "+", "len", "(", "finalBlock", ")", ")", "\n", "c", ".", "CryptBlocks", "(", "b", ".", "data", "[", "recordHeaderLen", "+", "explicitIVLen", ":", "]", ",", "prefix", ")", "\n", "c", ".", "CryptBlocks", "(", "b", ".", "data", "[", "recordHeaderLen", "+", "explicitIVLen", "+", "len", "(", "prefix", ")", ":", "]", ",", "finalBlock", ")", "\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "// update length to include MAC and any block padding needed.", "n", ":=", "len", "(", "b", ".", "data", ")", "-", "recordHeaderLen", "\n", "b", ".", "data", "[", "3", "]", "=", "byte", "(", "n", ">>", "8", ")", "\n", "b", ".", "data", "[", "4", "]", "=", "byte", "(", "n", ")", "\n", "hc", ".", "incSeq", "(", ")", "\n\n", "return", "true", ",", "0", "\n", "}" ]
// encrypt encrypts and macs the data in b.
[ "encrypt", "encrypts", "and", "macs", "the", "data", "in", "b", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L362-L415
train
cloudflare/cfssl
scan/crypto/tls/conn.go
resize
func (b *block) resize(n int) { if n > cap(b.data) { b.reserve(n) } b.data = b.data[0:n] }
go
func (b *block) resize(n int) { if n > cap(b.data) { b.reserve(n) } b.data = b.data[0:n] }
[ "func", "(", "b", "*", "block", ")", "resize", "(", "n", "int", ")", "{", "if", "n", ">", "cap", "(", "b", ".", "data", ")", "{", "b", ".", "reserve", "(", "n", ")", "\n", "}", "\n", "b", ".", "data", "=", "b", ".", "data", "[", "0", ":", "n", "]", "\n", "}" ]
// resize resizes block to be n bytes, growing if necessary.
[ "resize", "resizes", "block", "to", "be", "n", "bytes", "growing", "if", "necessary", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L425-L430
train
cloudflare/cfssl
scan/crypto/tls/conn.go
reserve
func (b *block) reserve(n int) { if cap(b.data) >= n { return } m := cap(b.data) if m == 0 { m = 1024 } for m < n { m *= 2 } data := make([]byte, len(b.data), m) copy(data, b.data) b.data = data }
go
func (b *block) reserve(n int) { if cap(b.data) >= n { return } m := cap(b.data) if m == 0 { m = 1024 } for m < n { m *= 2 } data := make([]byte, len(b.data), m) copy(data, b.data) b.data = data }
[ "func", "(", "b", "*", "block", ")", "reserve", "(", "n", "int", ")", "{", "if", "cap", "(", "b", ".", "data", ")", ">=", "n", "{", "return", "\n", "}", "\n", "m", ":=", "cap", "(", "b", ".", "data", ")", "\n", "if", "m", "==", "0", "{", "m", "=", "1024", "\n", "}", "\n", "for", "m", "<", "n", "{", "m", "*=", "2", "\n", "}", "\n", "data", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "b", ".", "data", ")", ",", "m", ")", "\n", "copy", "(", "data", ",", "b", ".", "data", ")", "\n", "b", ".", "data", "=", "data", "\n", "}" ]
// reserve makes sure that block contains a capacity of at least n bytes.
[ "reserve", "makes", "sure", "that", "block", "contains", "a", "capacity", "of", "at", "least", "n", "bytes", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L433-L447
train
cloudflare/cfssl
scan/crypto/tls/conn.go
readFromUntil
func (b *block) readFromUntil(r io.Reader, n int) error { // quick case if len(b.data) >= n { return nil } // read until have enough. b.reserve(n) for { m, err := r.Read(b.data[len(b.data):cap(b.data)]) b.data = b.data[0 : len(b.data)+m] if len(b.data) >= n { // TODO(bradfitz,agl): slightly suspicious // that we're throwing away r.Read's err here. break } if err != nil { return err } } return nil }
go
func (b *block) readFromUntil(r io.Reader, n int) error { // quick case if len(b.data) >= n { return nil } // read until have enough. b.reserve(n) for { m, err := r.Read(b.data[len(b.data):cap(b.data)]) b.data = b.data[0 : len(b.data)+m] if len(b.data) >= n { // TODO(bradfitz,agl): slightly suspicious // that we're throwing away r.Read's err here. break } if err != nil { return err } } return nil }
[ "func", "(", "b", "*", "block", ")", "readFromUntil", "(", "r", "io", ".", "Reader", ",", "n", "int", ")", "error", "{", "// quick case", "if", "len", "(", "b", ".", "data", ")", ">=", "n", "{", "return", "nil", "\n", "}", "\n\n", "// read until have enough.", "b", ".", "reserve", "(", "n", ")", "\n", "for", "{", "m", ",", "err", ":=", "r", ".", "Read", "(", "b", ".", "data", "[", "len", "(", "b", ".", "data", ")", ":", "cap", "(", "b", ".", "data", ")", "]", ")", "\n", "b", ".", "data", "=", "b", ".", "data", "[", "0", ":", "len", "(", "b", ".", "data", ")", "+", "m", "]", "\n", "if", "len", "(", "b", ".", "data", ")", ">=", "n", "{", "// TODO(bradfitz,agl): slightly suspicious", "// that we're throwing away r.Read's err here.", "break", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// readFromUntil reads from r into b until b contains at least n bytes // or else returns an error.
[ "readFromUntil", "reads", "from", "r", "into", "b", "until", "b", "contains", "at", "least", "n", "bytes", "or", "else", "returns", "an", "error", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L451-L472
train
cloudflare/cfssl
scan/crypto/tls/conn.go
newBlock
func (hc *halfConn) newBlock() *block { b := hc.bfree if b == nil { return new(block) } hc.bfree = b.link b.link = nil b.resize(0) return b }
go
func (hc *halfConn) newBlock() *block { b := hc.bfree if b == nil { return new(block) } hc.bfree = b.link b.link = nil b.resize(0) return b }
[ "func", "(", "hc", "*", "halfConn", ")", "newBlock", "(", ")", "*", "block", "{", "b", ":=", "hc", ".", "bfree", "\n", "if", "b", "==", "nil", "{", "return", "new", "(", "block", ")", "\n", "}", "\n", "hc", ".", "bfree", "=", "b", ".", "link", "\n", "b", ".", "link", "=", "nil", "\n", "b", ".", "resize", "(", "0", ")", "\n", "return", "b", "\n", "}" ]
// newBlock allocates a new block, from hc's free list if possible.
[ "newBlock", "allocates", "a", "new", "block", "from", "hc", "s", "free", "list", "if", "possible", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L481-L490
train
cloudflare/cfssl
scan/crypto/tls/conn.go
freeBlock
func (hc *halfConn) freeBlock(b *block) { b.link = hc.bfree hc.bfree = b }
go
func (hc *halfConn) freeBlock(b *block) { b.link = hc.bfree hc.bfree = b }
[ "func", "(", "hc", "*", "halfConn", ")", "freeBlock", "(", "b", "*", "block", ")", "{", "b", ".", "link", "=", "hc", ".", "bfree", "\n", "hc", ".", "bfree", "=", "b", "\n", "}" ]
// freeBlock returns a block to hc's free list. // The protocol is such that each side only has a block or two on // its free list at a time, so there's no need to worry about // trimming the list, etc.
[ "freeBlock", "returns", "a", "block", "to", "hc", "s", "free", "list", ".", "The", "protocol", "is", "such", "that", "each", "side", "only", "has", "a", "block", "or", "two", "on", "its", "free", "list", "at", "a", "time", "so", "there", "s", "no", "need", "to", "worry", "about", "trimming", "the", "list", "etc", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L496-L499
train
cloudflare/cfssl
scan/crypto/tls/conn.go
splitBlock
func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) { if len(b.data) <= n { return b, nil } bb := hc.newBlock() bb.resize(len(b.data) - n) copy(bb.data, b.data[n:]) b.data = b.data[0:n] return b, bb }
go
func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) { if len(b.data) <= n { return b, nil } bb := hc.newBlock() bb.resize(len(b.data) - n) copy(bb.data, b.data[n:]) b.data = b.data[0:n] return b, bb }
[ "func", "(", "hc", "*", "halfConn", ")", "splitBlock", "(", "b", "*", "block", ",", "n", "int", ")", "(", "*", "block", ",", "*", "block", ")", "{", "if", "len", "(", "b", ".", "data", ")", "<=", "n", "{", "return", "b", ",", "nil", "\n", "}", "\n", "bb", ":=", "hc", ".", "newBlock", "(", ")", "\n", "bb", ".", "resize", "(", "len", "(", "b", ".", "data", ")", "-", "n", ")", "\n", "copy", "(", "bb", ".", "data", ",", "b", ".", "data", "[", "n", ":", "]", ")", "\n", "b", ".", "data", "=", "b", ".", "data", "[", "0", ":", "n", "]", "\n", "return", "b", ",", "bb", "\n", "}" ]
// splitBlock splits a block after the first n bytes, // returning a block with those n bytes and a // block with the remainder. the latter may be nil.
[ "splitBlock", "splits", "a", "block", "after", "the", "first", "n", "bytes", "returning", "a", "block", "with", "those", "n", "bytes", "and", "a", "block", "with", "the", "remainder", ".", "the", "latter", "may", "be", "nil", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L504-L513
train
cloudflare/cfssl
scan/crypto/tls/conn.go
sendAlert
func (c *Conn) sendAlert(err alert) error { c.out.Lock() defer c.out.Unlock() return c.sendAlertLocked(err) }
go
func (c *Conn) sendAlert(err alert) error { c.out.Lock() defer c.out.Unlock() return c.sendAlertLocked(err) }
[ "func", "(", "c", "*", "Conn", ")", "sendAlert", "(", "err", "alert", ")", "error", "{", "c", ".", "out", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "out", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "sendAlertLocked", "(", "err", ")", "\n", "}" ]
// sendAlert sends a TLS alert message. // L < c.out.Mutex.
[ "sendAlert", "sends", "a", "TLS", "alert", "message", ".", "L", "<", "c", ".", "out", ".", "Mutex", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L707-L711
train
cloudflare/cfssl
scan/crypto/tls/conn.go
writeRecord
func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) { b := c.out.newBlock() for len(data) > 0 { m := len(data) if m > maxPlaintext { m = maxPlaintext } explicitIVLen := 0 explicitIVIsSeq := false var cbc cbcMode if c.out.version >= VersionTLS11 { var ok bool if cbc, ok = c.out.cipher.(cbcMode); ok { explicitIVLen = cbc.BlockSize() } } if explicitIVLen == 0 { if _, ok := c.out.cipher.(cipher.AEAD); ok { explicitIVLen = 8 // The AES-GCM construction in TLS has an // explicit nonce so that the nonce can be // random. However, the nonce is only 8 bytes // which is too small for a secure, random // nonce. Therefore we use the sequence number // as the nonce. explicitIVIsSeq = true } } b.resize(recordHeaderLen + explicitIVLen + m) b.data[0] = byte(typ) vers := c.vers if vers == 0 { // Some TLS servers fail if the record version is // greater than TLS 1.0 for the initial ClientHello. vers = VersionTLS10 } b.data[1] = byte(vers >> 8) b.data[2] = byte(vers) b.data[3] = byte(m >> 8) b.data[4] = byte(m) if explicitIVLen > 0 { explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] if explicitIVIsSeq { copy(explicitIV, c.out.seq[:]) } else { if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil { break } } } copy(b.data[recordHeaderLen+explicitIVLen:], data) c.out.encrypt(b, explicitIVLen) _, err = c.conn.Write(b.data) if err != nil { break } n += m data = data[m:] } c.out.freeBlock(b) if typ == recordTypeChangeCipherSpec { err = c.out.changeCipherSpec() if err != nil { // Cannot call sendAlert directly, // because we already hold c.out.Mutex. c.tmp[0] = alertLevelError c.tmp[1] = byte(err.(alert)) c.writeRecord(recordTypeAlert, c.tmp[0:2]) return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) } } return }
go
func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) { b := c.out.newBlock() for len(data) > 0 { m := len(data) if m > maxPlaintext { m = maxPlaintext } explicitIVLen := 0 explicitIVIsSeq := false var cbc cbcMode if c.out.version >= VersionTLS11 { var ok bool if cbc, ok = c.out.cipher.(cbcMode); ok { explicitIVLen = cbc.BlockSize() } } if explicitIVLen == 0 { if _, ok := c.out.cipher.(cipher.AEAD); ok { explicitIVLen = 8 // The AES-GCM construction in TLS has an // explicit nonce so that the nonce can be // random. However, the nonce is only 8 bytes // which is too small for a secure, random // nonce. Therefore we use the sequence number // as the nonce. explicitIVIsSeq = true } } b.resize(recordHeaderLen + explicitIVLen + m) b.data[0] = byte(typ) vers := c.vers if vers == 0 { // Some TLS servers fail if the record version is // greater than TLS 1.0 for the initial ClientHello. vers = VersionTLS10 } b.data[1] = byte(vers >> 8) b.data[2] = byte(vers) b.data[3] = byte(m >> 8) b.data[4] = byte(m) if explicitIVLen > 0 { explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] if explicitIVIsSeq { copy(explicitIV, c.out.seq[:]) } else { if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil { break } } } copy(b.data[recordHeaderLen+explicitIVLen:], data) c.out.encrypt(b, explicitIVLen) _, err = c.conn.Write(b.data) if err != nil { break } n += m data = data[m:] } c.out.freeBlock(b) if typ == recordTypeChangeCipherSpec { err = c.out.changeCipherSpec() if err != nil { // Cannot call sendAlert directly, // because we already hold c.out.Mutex. c.tmp[0] = alertLevelError c.tmp[1] = byte(err.(alert)) c.writeRecord(recordTypeAlert, c.tmp[0:2]) return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) } } return }
[ "func", "(", "c", "*", "Conn", ")", "writeRecord", "(", "typ", "recordType", ",", "data", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "b", ":=", "c", ".", "out", ".", "newBlock", "(", ")", "\n", "for", "len", "(", "data", ")", ">", "0", "{", "m", ":=", "len", "(", "data", ")", "\n", "if", "m", ">", "maxPlaintext", "{", "m", "=", "maxPlaintext", "\n", "}", "\n", "explicitIVLen", ":=", "0", "\n", "explicitIVIsSeq", ":=", "false", "\n\n", "var", "cbc", "cbcMode", "\n", "if", "c", ".", "out", ".", "version", ">=", "VersionTLS11", "{", "var", "ok", "bool", "\n", "if", "cbc", ",", "ok", "=", "c", ".", "out", ".", "cipher", ".", "(", "cbcMode", ")", ";", "ok", "{", "explicitIVLen", "=", "cbc", ".", "BlockSize", "(", ")", "\n", "}", "\n", "}", "\n", "if", "explicitIVLen", "==", "0", "{", "if", "_", ",", "ok", ":=", "c", ".", "out", ".", "cipher", ".", "(", "cipher", ".", "AEAD", ")", ";", "ok", "{", "explicitIVLen", "=", "8", "\n", "// The AES-GCM construction in TLS has an", "// explicit nonce so that the nonce can be", "// random. However, the nonce is only 8 bytes", "// which is too small for a secure, random", "// nonce. Therefore we use the sequence number", "// as the nonce.", "explicitIVIsSeq", "=", "true", "\n", "}", "\n", "}", "\n", "b", ".", "resize", "(", "recordHeaderLen", "+", "explicitIVLen", "+", "m", ")", "\n", "b", ".", "data", "[", "0", "]", "=", "byte", "(", "typ", ")", "\n", "vers", ":=", "c", ".", "vers", "\n", "if", "vers", "==", "0", "{", "// Some TLS servers fail if the record version is", "// greater than TLS 1.0 for the initial ClientHello.", "vers", "=", "VersionTLS10", "\n", "}", "\n", "b", ".", "data", "[", "1", "]", "=", "byte", "(", "vers", ">>", "8", ")", "\n", "b", ".", "data", "[", "2", "]", "=", "byte", "(", "vers", ")", "\n", "b", ".", "data", "[", "3", "]", "=", "byte", "(", "m", ">>", "8", ")", "\n", "b", ".", "data", "[", "4", "]", "=", "byte", "(", "m", ")", "\n", "if", "explicitIVLen", ">", "0", "{", "explicitIV", ":=", "b", ".", "data", "[", "recordHeaderLen", ":", "recordHeaderLen", "+", "explicitIVLen", "]", "\n", "if", "explicitIVIsSeq", "{", "copy", "(", "explicitIV", ",", "c", ".", "out", ".", "seq", "[", ":", "]", ")", "\n", "}", "else", "{", "if", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "c", ".", "config", ".", "rand", "(", ")", ",", "explicitIV", ")", ";", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "copy", "(", "b", ".", "data", "[", "recordHeaderLen", "+", "explicitIVLen", ":", "]", ",", "data", ")", "\n", "c", ".", "out", ".", "encrypt", "(", "b", ",", "explicitIVLen", ")", "\n", "_", ",", "err", "=", "c", ".", "conn", ".", "Write", "(", "b", ".", "data", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "n", "+=", "m", "\n", "data", "=", "data", "[", "m", ":", "]", "\n", "}", "\n", "c", ".", "out", ".", "freeBlock", "(", "b", ")", "\n\n", "if", "typ", "==", "recordTypeChangeCipherSpec", "{", "err", "=", "c", ".", "out", ".", "changeCipherSpec", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// Cannot call sendAlert directly,", "// because we already hold c.out.Mutex.", "c", ".", "tmp", "[", "0", "]", "=", "alertLevelError", "\n", "c", ".", "tmp", "[", "1", "]", "=", "byte", "(", "err", ".", "(", "alert", ")", ")", "\n", "c", ".", "writeRecord", "(", "recordTypeAlert", ",", "c", ".", "tmp", "[", "0", ":", "2", "]", ")", "\n", "return", "n", ",", "c", ".", "out", ".", "setErrorLocked", "(", "&", "net", ".", "OpError", "{", "Op", ":", "\"", "\"", ",", "Err", ":", "err", "}", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// writeRecord writes a TLS record with the given type and payload // to the connection and updates the record layer state. // c.out.Mutex <= L.
[ "writeRecord", "writes", "a", "TLS", "record", "with", "the", "given", "type", "and", "payload", "to", "the", "connection", "and", "updates", "the", "record", "layer", "state", ".", "c", ".", "out", ".", "Mutex", "<", "=", "L", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L716-L790
train
cloudflare/cfssl
scan/crypto/tls/conn.go
readHandshake
func (c *Conn) readHandshake() (interface{}, error) { for c.hand.Len() < 4 { if err := c.in.err; err != nil { return nil, err } if err := c.readRecord(recordTypeHandshake); err != nil { return nil, err } } data := c.hand.Bytes() n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) if n > maxHandshake { return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError)) } for c.hand.Len() < 4+n { if err := c.in.err; err != nil { return nil, err } if err := c.readRecord(recordTypeHandshake); err != nil { return nil, err } } data = c.hand.Next(4 + n) var m handshakeMessage switch data[0] { case typeClientHello: m = new(clientHelloMsg) case typeServerHello: m = new(serverHelloMsg) case typeNewSessionTicket: m = new(newSessionTicketMsg) case typeCertificate: m = new(certificateMsg) case typeCertificateRequest: m = &certificateRequestMsg{ hasSignatureAndHash: c.vers >= VersionTLS12, } case typeCertificateStatus: m = new(certificateStatusMsg) case typeServerKeyExchange: m = new(serverKeyExchangeMsg) case typeServerHelloDone: m = new(serverHelloDoneMsg) case typeClientKeyExchange: m = new(clientKeyExchangeMsg) case typeCertificateVerify: m = &certificateVerifyMsg{ hasSignatureAndHash: c.vers >= VersionTLS12, } case typeNextProtocol: m = new(nextProtoMsg) case typeFinished: m = new(finishedMsg) default: return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) } // The handshake message unmarshallers // expect to be able to keep references to data, // so pass in a fresh copy that won't be overwritten. data = append([]byte(nil), data...) if !m.unmarshal(data) { return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) } return m, nil }
go
func (c *Conn) readHandshake() (interface{}, error) { for c.hand.Len() < 4 { if err := c.in.err; err != nil { return nil, err } if err := c.readRecord(recordTypeHandshake); err != nil { return nil, err } } data := c.hand.Bytes() n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) if n > maxHandshake { return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError)) } for c.hand.Len() < 4+n { if err := c.in.err; err != nil { return nil, err } if err := c.readRecord(recordTypeHandshake); err != nil { return nil, err } } data = c.hand.Next(4 + n) var m handshakeMessage switch data[0] { case typeClientHello: m = new(clientHelloMsg) case typeServerHello: m = new(serverHelloMsg) case typeNewSessionTicket: m = new(newSessionTicketMsg) case typeCertificate: m = new(certificateMsg) case typeCertificateRequest: m = &certificateRequestMsg{ hasSignatureAndHash: c.vers >= VersionTLS12, } case typeCertificateStatus: m = new(certificateStatusMsg) case typeServerKeyExchange: m = new(serverKeyExchangeMsg) case typeServerHelloDone: m = new(serverHelloDoneMsg) case typeClientKeyExchange: m = new(clientKeyExchangeMsg) case typeCertificateVerify: m = &certificateVerifyMsg{ hasSignatureAndHash: c.vers >= VersionTLS12, } case typeNextProtocol: m = new(nextProtoMsg) case typeFinished: m = new(finishedMsg) default: return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) } // The handshake message unmarshallers // expect to be able to keep references to data, // so pass in a fresh copy that won't be overwritten. data = append([]byte(nil), data...) if !m.unmarshal(data) { return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) } return m, nil }
[ "func", "(", "c", "*", "Conn", ")", "readHandshake", "(", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "for", "c", ".", "hand", ".", "Len", "(", ")", "<", "4", "{", "if", "err", ":=", "c", ".", "in", ".", "err", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "readRecord", "(", "recordTypeHandshake", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "data", ":=", "c", ".", "hand", ".", "Bytes", "(", ")", "\n", "n", ":=", "int", "(", "data", "[", "1", "]", ")", "<<", "16", "|", "int", "(", "data", "[", "2", "]", ")", "<<", "8", "|", "int", "(", "data", "[", "3", "]", ")", "\n", "if", "n", ">", "maxHandshake", "{", "return", "nil", ",", "c", ".", "in", ".", "setErrorLocked", "(", "c", ".", "sendAlert", "(", "alertInternalError", ")", ")", "\n", "}", "\n", "for", "c", ".", "hand", ".", "Len", "(", ")", "<", "4", "+", "n", "{", "if", "err", ":=", "c", ".", "in", ".", "err", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "readRecord", "(", "recordTypeHandshake", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "data", "=", "c", ".", "hand", ".", "Next", "(", "4", "+", "n", ")", "\n", "var", "m", "handshakeMessage", "\n", "switch", "data", "[", "0", "]", "{", "case", "typeClientHello", ":", "m", "=", "new", "(", "clientHelloMsg", ")", "\n", "case", "typeServerHello", ":", "m", "=", "new", "(", "serverHelloMsg", ")", "\n", "case", "typeNewSessionTicket", ":", "m", "=", "new", "(", "newSessionTicketMsg", ")", "\n", "case", "typeCertificate", ":", "m", "=", "new", "(", "certificateMsg", ")", "\n", "case", "typeCertificateRequest", ":", "m", "=", "&", "certificateRequestMsg", "{", "hasSignatureAndHash", ":", "c", ".", "vers", ">=", "VersionTLS12", ",", "}", "\n", "case", "typeCertificateStatus", ":", "m", "=", "new", "(", "certificateStatusMsg", ")", "\n", "case", "typeServerKeyExchange", ":", "m", "=", "new", "(", "serverKeyExchangeMsg", ")", "\n", "case", "typeServerHelloDone", ":", "m", "=", "new", "(", "serverHelloDoneMsg", ")", "\n", "case", "typeClientKeyExchange", ":", "m", "=", "new", "(", "clientKeyExchangeMsg", ")", "\n", "case", "typeCertificateVerify", ":", "m", "=", "&", "certificateVerifyMsg", "{", "hasSignatureAndHash", ":", "c", ".", "vers", ">=", "VersionTLS12", ",", "}", "\n", "case", "typeNextProtocol", ":", "m", "=", "new", "(", "nextProtoMsg", ")", "\n", "case", "typeFinished", ":", "m", "=", "new", "(", "finishedMsg", ")", "\n", "default", ":", "return", "nil", ",", "c", ".", "in", ".", "setErrorLocked", "(", "c", ".", "sendAlert", "(", "alertUnexpectedMessage", ")", ")", "\n", "}", "\n\n", "// The handshake message unmarshallers", "// expect to be able to keep references to data,", "// so pass in a fresh copy that won't be overwritten.", "data", "=", "append", "(", "[", "]", "byte", "(", "nil", ")", ",", "data", "...", ")", "\n\n", "if", "!", "m", ".", "unmarshal", "(", "data", ")", "{", "return", "nil", ",", "c", ".", "in", ".", "setErrorLocked", "(", "c", ".", "sendAlert", "(", "alertUnexpectedMessage", ")", ")", "\n", "}", "\n", "return", "m", ",", "nil", "\n", "}" ]
// readHandshake reads the next handshake message from // the record layer. // c.in.Mutex < L; c.out.Mutex < L.
[ "readHandshake", "reads", "the", "next", "handshake", "message", "from", "the", "record", "layer", ".", "c", ".", "in", ".", "Mutex", "<", "L", ";", "c", ".", "out", ".", "Mutex", "<", "L", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L795-L862
train
cloudflare/cfssl
scan/crypto/tls/conn.go
ConnectionState
func (c *Conn) ConnectionState() ConnectionState { c.handshakeMutex.Lock() defer c.handshakeMutex.Unlock() var state ConnectionState state.HandshakeComplete = c.handshakeComplete if c.handshakeComplete { state.Version = c.vers state.NegotiatedProtocol = c.clientProtocol state.DidResume = c.didResume state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback state.CipherSuite = c.cipherSuite state.PeerCertificates = c.peerCertificates state.VerifiedChains = c.verifiedChains state.ServerName = c.serverName state.SignedCertificateTimestamps = c.scts state.OCSPResponse = c.ocspResponse if !c.didResume { state.TLSUnique = c.firstFinished[:] } } return state }
go
func (c *Conn) ConnectionState() ConnectionState { c.handshakeMutex.Lock() defer c.handshakeMutex.Unlock() var state ConnectionState state.HandshakeComplete = c.handshakeComplete if c.handshakeComplete { state.Version = c.vers state.NegotiatedProtocol = c.clientProtocol state.DidResume = c.didResume state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback state.CipherSuite = c.cipherSuite state.PeerCertificates = c.peerCertificates state.VerifiedChains = c.verifiedChains state.ServerName = c.serverName state.SignedCertificateTimestamps = c.scts state.OCSPResponse = c.ocspResponse if !c.didResume { state.TLSUnique = c.firstFinished[:] } } return state }
[ "func", "(", "c", "*", "Conn", ")", "ConnectionState", "(", ")", "ConnectionState", "{", "c", ".", "handshakeMutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "handshakeMutex", ".", "Unlock", "(", ")", "\n\n", "var", "state", "ConnectionState", "\n", "state", ".", "HandshakeComplete", "=", "c", ".", "handshakeComplete", "\n", "if", "c", ".", "handshakeComplete", "{", "state", ".", "Version", "=", "c", ".", "vers", "\n", "state", ".", "NegotiatedProtocol", "=", "c", ".", "clientProtocol", "\n", "state", ".", "DidResume", "=", "c", ".", "didResume", "\n", "state", ".", "NegotiatedProtocolIsMutual", "=", "!", "c", ".", "clientProtocolFallback", "\n", "state", ".", "CipherSuite", "=", "c", ".", "cipherSuite", "\n", "state", ".", "PeerCertificates", "=", "c", ".", "peerCertificates", "\n", "state", ".", "VerifiedChains", "=", "c", ".", "verifiedChains", "\n", "state", ".", "ServerName", "=", "c", ".", "serverName", "\n", "state", ".", "SignedCertificateTimestamps", "=", "c", ".", "scts", "\n", "state", ".", "OCSPResponse", "=", "c", ".", "ocspResponse", "\n", "if", "!", "c", ".", "didResume", "{", "state", ".", "TLSUnique", "=", "c", ".", "firstFinished", "[", ":", "]", "\n", "}", "\n", "}", "\n\n", "return", "state", "\n", "}" ]
// ConnectionState returns basic TLS details about the connection.
[ "ConnectionState", "returns", "basic", "TLS", "details", "about", "the", "connection", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L1041-L1064
train
cloudflare/cfssl
scan/crypto/tls/conn.go
VerifyHostname
func (c *Conn) VerifyHostname(host string) error { c.handshakeMutex.Lock() defer c.handshakeMutex.Unlock() if !c.isClient { return errors.New("tls: VerifyHostname called on TLS server connection") } if !c.handshakeComplete { return errors.New("tls: handshake has not yet been performed") } if len(c.verifiedChains) == 0 { return errors.New("tls: handshake did not verify certificate chain") } return c.peerCertificates[0].VerifyHostname(host) }
go
func (c *Conn) VerifyHostname(host string) error { c.handshakeMutex.Lock() defer c.handshakeMutex.Unlock() if !c.isClient { return errors.New("tls: VerifyHostname called on TLS server connection") } if !c.handshakeComplete { return errors.New("tls: handshake has not yet been performed") } if len(c.verifiedChains) == 0 { return errors.New("tls: handshake did not verify certificate chain") } return c.peerCertificates[0].VerifyHostname(host) }
[ "func", "(", "c", "*", "Conn", ")", "VerifyHostname", "(", "host", "string", ")", "error", "{", "c", ".", "handshakeMutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "handshakeMutex", ".", "Unlock", "(", ")", "\n", "if", "!", "c", ".", "isClient", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "c", ".", "handshakeComplete", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "c", ".", "verifiedChains", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ".", "peerCertificates", "[", "0", "]", ".", "VerifyHostname", "(", "host", ")", "\n", "}" ]
// VerifyHostname checks that the peer certificate chain is valid for // connecting to host. If so, it returns nil; if not, it returns an error // describing the problem.
[ "VerifyHostname", "checks", "that", "the", "peer", "certificate", "chain", "is", "valid", "for", "connecting", "to", "host", ".", "If", "so", "it", "returns", "nil", ";", "if", "not", "it", "returns", "an", "error", "describing", "the", "problem", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/conn.go#L1078-L1091
train
cloudflare/cfssl
cli/sign/sign.go
SignerFromConfigAndDB
func SignerFromConfigAndDB(c cli.Config, db *sqlx.DB) (signer.Signer, error) { // If there is a config, use its signing policy. Otherwise create a default policy. var policy *config.Signing if c.CFG != nil { policy = c.CFG.Signing } else { policy = &config.Signing{ Profiles: map[string]*config.SigningProfile{}, Default: config.DefaultConfig(), } } // Make sure the policy reflects the new remote if c.Remote != "" { err := policy.OverrideRemotes(c.Remote) if err != nil { log.Infof("Invalid remote %v, reverting to configuration default", c.Remote) return nil, err } } if c.MutualTLSCertFile != "" && c.MutualTLSKeyFile != "" { err := policy.SetClientCertKeyPairFromFile(c.MutualTLSCertFile, c.MutualTLSKeyFile) if err != nil { log.Infof("Invalid mutual-tls-cert: %s or mutual-tls-key: %s, defaulting to no client auth", c.MutualTLSCertFile, c.MutualTLSKeyFile) return nil, err } log.Infof("Using client auth with mutual-tls-cert: %s and mutual-tls-key: %s", c.MutualTLSCertFile, c.MutualTLSKeyFile) } if c.TLSRemoteCAs != "" { err := policy.SetRemoteCAsFromFile(c.TLSRemoteCAs) if err != nil { log.Infof("Invalid tls-remote-ca: %s, defaulting to system trust store", c.TLSRemoteCAs) return nil, err } log.Infof("Using trusted CA from tls-remote-ca: %s", c.TLSRemoteCAs) } s, err := universal.NewSigner(cli.RootFromConfig(&c), policy) if err != nil { return nil, err } if db != nil { dbAccessor := certsql.NewAccessor(db) s.SetDBAccessor(dbAccessor) } return s, nil }
go
func SignerFromConfigAndDB(c cli.Config, db *sqlx.DB) (signer.Signer, error) { // If there is a config, use its signing policy. Otherwise create a default policy. var policy *config.Signing if c.CFG != nil { policy = c.CFG.Signing } else { policy = &config.Signing{ Profiles: map[string]*config.SigningProfile{}, Default: config.DefaultConfig(), } } // Make sure the policy reflects the new remote if c.Remote != "" { err := policy.OverrideRemotes(c.Remote) if err != nil { log.Infof("Invalid remote %v, reverting to configuration default", c.Remote) return nil, err } } if c.MutualTLSCertFile != "" && c.MutualTLSKeyFile != "" { err := policy.SetClientCertKeyPairFromFile(c.MutualTLSCertFile, c.MutualTLSKeyFile) if err != nil { log.Infof("Invalid mutual-tls-cert: %s or mutual-tls-key: %s, defaulting to no client auth", c.MutualTLSCertFile, c.MutualTLSKeyFile) return nil, err } log.Infof("Using client auth with mutual-tls-cert: %s and mutual-tls-key: %s", c.MutualTLSCertFile, c.MutualTLSKeyFile) } if c.TLSRemoteCAs != "" { err := policy.SetRemoteCAsFromFile(c.TLSRemoteCAs) if err != nil { log.Infof("Invalid tls-remote-ca: %s, defaulting to system trust store", c.TLSRemoteCAs) return nil, err } log.Infof("Using trusted CA from tls-remote-ca: %s", c.TLSRemoteCAs) } s, err := universal.NewSigner(cli.RootFromConfig(&c), policy) if err != nil { return nil, err } if db != nil { dbAccessor := certsql.NewAccessor(db) s.SetDBAccessor(dbAccessor) } return s, nil }
[ "func", "SignerFromConfigAndDB", "(", "c", "cli", ".", "Config", ",", "db", "*", "sqlx", ".", "DB", ")", "(", "signer", ".", "Signer", ",", "error", ")", "{", "// If there is a config, use its signing policy. Otherwise create a default policy.", "var", "policy", "*", "config", ".", "Signing", "\n", "if", "c", ".", "CFG", "!=", "nil", "{", "policy", "=", "c", ".", "CFG", ".", "Signing", "\n", "}", "else", "{", "policy", "=", "&", "config", ".", "Signing", "{", "Profiles", ":", "map", "[", "string", "]", "*", "config", ".", "SigningProfile", "{", "}", ",", "Default", ":", "config", ".", "DefaultConfig", "(", ")", ",", "}", "\n", "}", "\n\n", "// Make sure the policy reflects the new remote", "if", "c", ".", "Remote", "!=", "\"", "\"", "{", "err", ":=", "policy", ".", "OverrideRemotes", "(", "c", ".", "Remote", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "c", ".", "Remote", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "c", ".", "MutualTLSCertFile", "!=", "\"", "\"", "&&", "c", ".", "MutualTLSKeyFile", "!=", "\"", "\"", "{", "err", ":=", "policy", ".", "SetClientCertKeyPairFromFile", "(", "c", ".", "MutualTLSCertFile", ",", "c", ".", "MutualTLSKeyFile", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "c", ".", "MutualTLSCertFile", ",", "c", ".", "MutualTLSKeyFile", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "c", ".", "MutualTLSCertFile", ",", "c", ".", "MutualTLSKeyFile", ")", "\n", "}", "\n\n", "if", "c", ".", "TLSRemoteCAs", "!=", "\"", "\"", "{", "err", ":=", "policy", ".", "SetRemoteCAsFromFile", "(", "c", ".", "TLSRemoteCAs", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "c", ".", "TLSRemoteCAs", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "c", ".", "TLSRemoteCAs", ")", "\n", "}", "\n\n", "s", ",", "err", ":=", "universal", ".", "NewSigner", "(", "cli", ".", "RootFromConfig", "(", "&", "c", ")", ",", "policy", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "db", "!=", "nil", "{", "dbAccessor", ":=", "certsql", ".", "NewAccessor", "(", "db", ")", "\n", "s", ".", "SetDBAccessor", "(", "dbAccessor", ")", "\n", "}", "\n\n", "return", "s", ",", "nil", "\n", "}" ]
// SignerFromConfigAndDB takes the Config and creates the appropriate // signer.Signer object with a specified db
[ "SignerFromConfigAndDB", "takes", "the", "Config", "and", "creates", "the", "appropriate", "signer", ".", "Signer", "object", "with", "a", "specified", "db" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cli/sign/sign.go#L43-L93
train
cloudflare/cfssl
cli/sign/sign.go
SignerFromConfig
func SignerFromConfig(c cli.Config) (s signer.Signer, err error) { var db *sqlx.DB if c.DBConfigFile != "" { db, err = dbconf.DBFromConfig(c.DBConfigFile) if err != nil { return nil, err } } return SignerFromConfigAndDB(c, db) }
go
func SignerFromConfig(c cli.Config) (s signer.Signer, err error) { var db *sqlx.DB if c.DBConfigFile != "" { db, err = dbconf.DBFromConfig(c.DBConfigFile) if err != nil { return nil, err } } return SignerFromConfigAndDB(c, db) }
[ "func", "SignerFromConfig", "(", "c", "cli", ".", "Config", ")", "(", "s", "signer", ".", "Signer", ",", "err", "error", ")", "{", "var", "db", "*", "sqlx", ".", "DB", "\n", "if", "c", ".", "DBConfigFile", "!=", "\"", "\"", "{", "db", ",", "err", "=", "dbconf", ".", "DBFromConfig", "(", "c", ".", "DBConfigFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "SignerFromConfigAndDB", "(", "c", ",", "db", ")", "\n", "}" ]
// SignerFromConfig takes the Config and creates the appropriate // signer.Signer object
[ "SignerFromConfig", "takes", "the", "Config", "and", "creates", "the", "appropriate", "signer", ".", "Signer", "object" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cli/sign/sign.go#L97-L106
train
cloudflare/cfssl
scan/crypto/rsa/pss.go
VerifyPSS
func VerifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, opts *PSSOptions) error { return verifyPSS(pub, hash, hashed, sig, opts.saltLength()) }
go
func VerifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, opts *PSSOptions) error { return verifyPSS(pub, hash, hashed, sig, opts.saltLength()) }
[ "func", "VerifyPSS", "(", "pub", "*", "PublicKey", ",", "hash", "crypto", ".", "Hash", ",", "hashed", "[", "]", "byte", ",", "sig", "[", "]", "byte", ",", "opts", "*", "PSSOptions", ")", "error", "{", "return", "verifyPSS", "(", "pub", ",", "hash", ",", "hashed", ",", "sig", ",", "opts", ".", "saltLength", "(", ")", ")", "\n", "}" ]
// VerifyPSS verifies a PSS signature. // hashed is the result of hashing the input message using the given hash // function and sig is the signature. A valid signature is indicated by // returning a nil error. The opts argument may be nil, in which case sensible // defaults are used.
[ "VerifyPSS", "verifies", "a", "PSS", "signature", ".", "hashed", "is", "the", "result", "of", "hashing", "the", "input", "message", "using", "the", "given", "hash", "function", "and", "sig", "is", "the", "signature", ".", "A", "valid", "signature", "is", "indicated", "by", "returning", "a", "nil", "error", ".", "The", "opts", "argument", "may", "be", "nil", "in", "which", "case", "sensible", "defaults", "are", "used", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/rsa/pss.go#L274-L276
train
cloudflare/cfssl
scan/crypto/rsa/pss.go
verifyPSS
func verifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, saltLen int) error { nBits := pub.N.BitLen() if len(sig) != (nBits+7)/8 { return ErrVerification } s := new(big.Int).SetBytes(sig) m := encrypt(new(big.Int), pub, s) emBits := nBits - 1 emLen := (emBits + 7) / 8 if emLen < len(m.Bytes()) { return ErrVerification } em := make([]byte, emLen) copyWithLeftPad(em, m.Bytes()) if saltLen == PSSSaltLengthEqualsHash { saltLen = hash.Size() } return emsaPSSVerify(hashed, em, emBits, saltLen, hash.New()) }
go
func verifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, saltLen int) error { nBits := pub.N.BitLen() if len(sig) != (nBits+7)/8 { return ErrVerification } s := new(big.Int).SetBytes(sig) m := encrypt(new(big.Int), pub, s) emBits := nBits - 1 emLen := (emBits + 7) / 8 if emLen < len(m.Bytes()) { return ErrVerification } em := make([]byte, emLen) copyWithLeftPad(em, m.Bytes()) if saltLen == PSSSaltLengthEqualsHash { saltLen = hash.Size() } return emsaPSSVerify(hashed, em, emBits, saltLen, hash.New()) }
[ "func", "verifyPSS", "(", "pub", "*", "PublicKey", ",", "hash", "crypto", ".", "Hash", ",", "hashed", "[", "]", "byte", ",", "sig", "[", "]", "byte", ",", "saltLen", "int", ")", "error", "{", "nBits", ":=", "pub", ".", "N", ".", "BitLen", "(", ")", "\n", "if", "len", "(", "sig", ")", "!=", "(", "nBits", "+", "7", ")", "/", "8", "{", "return", "ErrVerification", "\n", "}", "\n", "s", ":=", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "sig", ")", "\n", "m", ":=", "encrypt", "(", "new", "(", "big", ".", "Int", ")", ",", "pub", ",", "s", ")", "\n", "emBits", ":=", "nBits", "-", "1", "\n", "emLen", ":=", "(", "emBits", "+", "7", ")", "/", "8", "\n", "if", "emLen", "<", "len", "(", "m", ".", "Bytes", "(", ")", ")", "{", "return", "ErrVerification", "\n", "}", "\n", "em", ":=", "make", "(", "[", "]", "byte", ",", "emLen", ")", "\n", "copyWithLeftPad", "(", "em", ",", "m", ".", "Bytes", "(", ")", ")", "\n", "if", "saltLen", "==", "PSSSaltLengthEqualsHash", "{", "saltLen", "=", "hash", ".", "Size", "(", ")", "\n", "}", "\n", "return", "emsaPSSVerify", "(", "hashed", ",", "em", ",", "emBits", ",", "saltLen", ",", "hash", ".", "New", "(", ")", ")", "\n", "}" ]
// verifyPSS verifies a PSS signature with the given salt length.
[ "verifyPSS", "verifies", "a", "PSS", "signature", "with", "the", "given", "salt", "length", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/rsa/pss.go#L279-L297
train
cloudflare/cfssl
cli/ocspdump/ocspdump.go
ocspdumpMain
func ocspdumpMain(args []string, c cli.Config) error { if c.DBConfigFile == "" { return errors.New("need DB config file (provide with -db-config)") } db, err := dbconf.DBFromConfig(c.DBConfigFile) if err != nil { return err } dbAccessor := sql.NewAccessor(db) records, err := dbAccessor.GetUnexpiredOCSPs() if err != nil { return err } for _, certRecord := range records { fmt.Printf("%s\n", base64.StdEncoding.EncodeToString([]byte(certRecord.Body))) } return nil }
go
func ocspdumpMain(args []string, c cli.Config) error { if c.DBConfigFile == "" { return errors.New("need DB config file (provide with -db-config)") } db, err := dbconf.DBFromConfig(c.DBConfigFile) if err != nil { return err } dbAccessor := sql.NewAccessor(db) records, err := dbAccessor.GetUnexpiredOCSPs() if err != nil { return err } for _, certRecord := range records { fmt.Printf("%s\n", base64.StdEncoding.EncodeToString([]byte(certRecord.Body))) } return nil }
[ "func", "ocspdumpMain", "(", "args", "[", "]", "string", ",", "c", "cli", ".", "Config", ")", "error", "{", "if", "c", ".", "DBConfigFile", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "db", ",", "err", ":=", "dbconf", ".", "DBFromConfig", "(", "c", ".", "DBConfigFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "dbAccessor", ":=", "sql", ".", "NewAccessor", "(", "db", ")", "\n", "records", ",", "err", ":=", "dbAccessor", ".", "GetUnexpiredOCSPs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "certRecord", ":=", "range", "records", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "[", "]", "byte", "(", "certRecord", ".", "Body", ")", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ocspdumpMain is the main CLI of OCSP dump functionality.
[ "ocspdumpMain", "is", "the", "main", "CLI", "of", "OCSP", "dump", "functionality", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cli/ocspdump/ocspdump.go#L28-L47
train
cloudflare/cfssl
certdb/sql/database_accessor.go
InsertCertificate
func (d *Accessor) InsertCertificate(cr certdb.CertificateRecord) error { err := d.checkDB() if err != nil { return err } res, err := d.db.NamedExec(insertSQL, &certdb.CertificateRecord{ Serial: cr.Serial, AKI: cr.AKI, CALabel: cr.CALabel, Status: cr.Status, Reason: cr.Reason, Expiry: cr.Expiry.UTC(), RevokedAt: cr.RevokedAt.UTC(), PEM: cr.PEM, }) if err != nil { return wrapSQLError(err) } numRowsAffected, err := res.RowsAffected() if numRowsAffected == 0 { return cferr.Wrap(cferr.CertStoreError, cferr.InsertionFailed, fmt.Errorf("failed to insert the certificate record")) } if numRowsAffected != 1 { return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected)) } return err }
go
func (d *Accessor) InsertCertificate(cr certdb.CertificateRecord) error { err := d.checkDB() if err != nil { return err } res, err := d.db.NamedExec(insertSQL, &certdb.CertificateRecord{ Serial: cr.Serial, AKI: cr.AKI, CALabel: cr.CALabel, Status: cr.Status, Reason: cr.Reason, Expiry: cr.Expiry.UTC(), RevokedAt: cr.RevokedAt.UTC(), PEM: cr.PEM, }) if err != nil { return wrapSQLError(err) } numRowsAffected, err := res.RowsAffected() if numRowsAffected == 0 { return cferr.Wrap(cferr.CertStoreError, cferr.InsertionFailed, fmt.Errorf("failed to insert the certificate record")) } if numRowsAffected != 1 { return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected)) } return err }
[ "func", "(", "d", "*", "Accessor", ")", "InsertCertificate", "(", "cr", "certdb", ".", "CertificateRecord", ")", "error", "{", "err", ":=", "d", ".", "checkDB", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "res", ",", "err", ":=", "d", ".", "db", ".", "NamedExec", "(", "insertSQL", ",", "&", "certdb", ".", "CertificateRecord", "{", "Serial", ":", "cr", ".", "Serial", ",", "AKI", ":", "cr", ".", "AKI", ",", "CALabel", ":", "cr", ".", "CALabel", ",", "Status", ":", "cr", ".", "Status", ",", "Reason", ":", "cr", ".", "Reason", ",", "Expiry", ":", "cr", ".", "Expiry", ".", "UTC", "(", ")", ",", "RevokedAt", ":", "cr", ".", "RevokedAt", ".", "UTC", "(", ")", ",", "PEM", ":", "cr", ".", "PEM", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapSQLError", "(", "err", ")", "\n", "}", "\n\n", "numRowsAffected", ",", "err", ":=", "res", ".", "RowsAffected", "(", ")", "\n\n", "if", "numRowsAffected", "==", "0", "{", "return", "cferr", ".", "Wrap", "(", "cferr", ".", "CertStoreError", ",", "cferr", ".", "InsertionFailed", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "if", "numRowsAffected", "!=", "1", "{", "return", "wrapSQLError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "numRowsAffected", ")", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// InsertCertificate puts a certdb.CertificateRecord into db.
[ "InsertCertificate", "puts", "a", "certdb", ".", "CertificateRecord", "into", "db", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/certdb/sql/database_accessor.go#L96-L127
train
cloudflare/cfssl
certdb/sql/database_accessor.go
GetCertificate
func (d *Accessor) GetCertificate(serial, aki string) (crs []certdb.CertificateRecord, err error) { err = d.checkDB() if err != nil { return nil, err } err = d.db.Select(&crs, fmt.Sprintf(d.db.Rebind(selectSQL), sqlstruct.Columns(certdb.CertificateRecord{})), serial, aki) if err != nil { return nil, wrapSQLError(err) } return crs, nil }
go
func (d *Accessor) GetCertificate(serial, aki string) (crs []certdb.CertificateRecord, err error) { err = d.checkDB() if err != nil { return nil, err } err = d.db.Select(&crs, fmt.Sprintf(d.db.Rebind(selectSQL), sqlstruct.Columns(certdb.CertificateRecord{})), serial, aki) if err != nil { return nil, wrapSQLError(err) } return crs, nil }
[ "func", "(", "d", "*", "Accessor", ")", "GetCertificate", "(", "serial", ",", "aki", "string", ")", "(", "crs", "[", "]", "certdb", ".", "CertificateRecord", ",", "err", "error", ")", "{", "err", "=", "d", ".", "checkDB", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "d", ".", "db", ".", "Select", "(", "&", "crs", ",", "fmt", ".", "Sprintf", "(", "d", ".", "db", ".", "Rebind", "(", "selectSQL", ")", ",", "sqlstruct", ".", "Columns", "(", "certdb", ".", "CertificateRecord", "{", "}", ")", ")", ",", "serial", ",", "aki", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "wrapSQLError", "(", "err", ")", "\n", "}", "\n\n", "return", "crs", ",", "nil", "\n", "}" ]
// GetCertificate gets a certdb.CertificateRecord indexed by serial.
[ "GetCertificate", "gets", "a", "certdb", ".", "CertificateRecord", "indexed", "by", "serial", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/certdb/sql/database_accessor.go#L130-L142
train
cloudflare/cfssl
certdb/sql/database_accessor.go
GetUnexpiredCertificates
func (d *Accessor) GetUnexpiredCertificates() (crs []certdb.CertificateRecord, err error) { err = d.checkDB() if err != nil { return nil, err } err = d.db.Select(&crs, fmt.Sprintf(d.db.Rebind(selectAllUnexpiredSQL), sqlstruct.Columns(certdb.CertificateRecord{}))) if err != nil { return nil, wrapSQLError(err) } return crs, nil }
go
func (d *Accessor) GetUnexpiredCertificates() (crs []certdb.CertificateRecord, err error) { err = d.checkDB() if err != nil { return nil, err } err = d.db.Select(&crs, fmt.Sprintf(d.db.Rebind(selectAllUnexpiredSQL), sqlstruct.Columns(certdb.CertificateRecord{}))) if err != nil { return nil, wrapSQLError(err) } return crs, nil }
[ "func", "(", "d", "*", "Accessor", ")", "GetUnexpiredCertificates", "(", ")", "(", "crs", "[", "]", "certdb", ".", "CertificateRecord", ",", "err", "error", ")", "{", "err", "=", "d", ".", "checkDB", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "d", ".", "db", ".", "Select", "(", "&", "crs", ",", "fmt", ".", "Sprintf", "(", "d", ".", "db", ".", "Rebind", "(", "selectAllUnexpiredSQL", ")", ",", "sqlstruct", ".", "Columns", "(", "certdb", ".", "CertificateRecord", "{", "}", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "wrapSQLError", "(", "err", ")", "\n", "}", "\n\n", "return", "crs", ",", "nil", "\n", "}" ]
// GetUnexpiredCertificates gets all unexpired certificate from db.
[ "GetUnexpiredCertificates", "gets", "all", "unexpired", "certificate", "from", "db", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/certdb/sql/database_accessor.go#L145-L157
train
cloudflare/cfssl
certdb/sql/database_accessor.go
RevokeCertificate
func (d *Accessor) RevokeCertificate(serial, aki string, reasonCode int) error { err := d.checkDB() if err != nil { return err } result, err := d.db.NamedExec(updateRevokeSQL, &certdb.CertificateRecord{ AKI: aki, Reason: reasonCode, Serial: serial, }) if err != nil { return wrapSQLError(err) } numRowsAffected, err := result.RowsAffected() if numRowsAffected == 0 { return cferr.Wrap(cferr.CertStoreError, cferr.RecordNotFound, fmt.Errorf("failed to revoke the certificate: certificate not found")) } if numRowsAffected != 1 { return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected)) } return err }
go
func (d *Accessor) RevokeCertificate(serial, aki string, reasonCode int) error { err := d.checkDB() if err != nil { return err } result, err := d.db.NamedExec(updateRevokeSQL, &certdb.CertificateRecord{ AKI: aki, Reason: reasonCode, Serial: serial, }) if err != nil { return wrapSQLError(err) } numRowsAffected, err := result.RowsAffected() if numRowsAffected == 0 { return cferr.Wrap(cferr.CertStoreError, cferr.RecordNotFound, fmt.Errorf("failed to revoke the certificate: certificate not found")) } if numRowsAffected != 1 { return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected)) } return err }
[ "func", "(", "d", "*", "Accessor", ")", "RevokeCertificate", "(", "serial", ",", "aki", "string", ",", "reasonCode", "int", ")", "error", "{", "err", ":=", "d", ".", "checkDB", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "result", ",", "err", ":=", "d", ".", "db", ".", "NamedExec", "(", "updateRevokeSQL", ",", "&", "certdb", ".", "CertificateRecord", "{", "AKI", ":", "aki", ",", "Reason", ":", "reasonCode", ",", "Serial", ":", "serial", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapSQLError", "(", "err", ")", "\n", "}", "\n\n", "numRowsAffected", ",", "err", ":=", "result", ".", "RowsAffected", "(", ")", "\n\n", "if", "numRowsAffected", "==", "0", "{", "return", "cferr", ".", "Wrap", "(", "cferr", ".", "CertStoreError", ",", "cferr", ".", "RecordNotFound", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "if", "numRowsAffected", "!=", "1", "{", "return", "wrapSQLError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "numRowsAffected", ")", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// RevokeCertificate updates a certificate with a given serial number and marks it revoked.
[ "RevokeCertificate", "updates", "a", "certificate", "with", "a", "given", "serial", "number", "and", "marks", "it", "revoked", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/certdb/sql/database_accessor.go#L190-L216
train
cloudflare/cfssl
certdb/sql/database_accessor.go
InsertOCSP
func (d *Accessor) InsertOCSP(rr certdb.OCSPRecord) error { err := d.checkDB() if err != nil { return err } result, err := d.db.NamedExec(insertOCSPSQL, &certdb.OCSPRecord{ AKI: rr.AKI, Body: rr.Body, Expiry: rr.Expiry.UTC(), Serial: rr.Serial, }) if err != nil { return wrapSQLError(err) } numRowsAffected, err := result.RowsAffected() if numRowsAffected == 0 { return cferr.Wrap(cferr.CertStoreError, cferr.InsertionFailed, fmt.Errorf("failed to insert the OCSP record")) } if numRowsAffected != 1 { return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected)) } return err }
go
func (d *Accessor) InsertOCSP(rr certdb.OCSPRecord) error { err := d.checkDB() if err != nil { return err } result, err := d.db.NamedExec(insertOCSPSQL, &certdb.OCSPRecord{ AKI: rr.AKI, Body: rr.Body, Expiry: rr.Expiry.UTC(), Serial: rr.Serial, }) if err != nil { return wrapSQLError(err) } numRowsAffected, err := result.RowsAffected() if numRowsAffected == 0 { return cferr.Wrap(cferr.CertStoreError, cferr.InsertionFailed, fmt.Errorf("failed to insert the OCSP record")) } if numRowsAffected != 1 { return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected)) } return err }
[ "func", "(", "d", "*", "Accessor", ")", "InsertOCSP", "(", "rr", "certdb", ".", "OCSPRecord", ")", "error", "{", "err", ":=", "d", ".", "checkDB", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "result", ",", "err", ":=", "d", ".", "db", ".", "NamedExec", "(", "insertOCSPSQL", ",", "&", "certdb", ".", "OCSPRecord", "{", "AKI", ":", "rr", ".", "AKI", ",", "Body", ":", "rr", ".", "Body", ",", "Expiry", ":", "rr", ".", "Expiry", ".", "UTC", "(", ")", ",", "Serial", ":", "rr", ".", "Serial", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapSQLError", "(", "err", ")", "\n", "}", "\n\n", "numRowsAffected", ",", "err", ":=", "result", ".", "RowsAffected", "(", ")", "\n\n", "if", "numRowsAffected", "==", "0", "{", "return", "cferr", ".", "Wrap", "(", "cferr", ".", "CertStoreError", ",", "cferr", ".", "InsertionFailed", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "if", "numRowsAffected", "!=", "1", "{", "return", "wrapSQLError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "numRowsAffected", ")", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// InsertOCSP puts a new certdb.OCSPRecord into the db.
[ "InsertOCSP", "puts", "a", "new", "certdb", ".", "OCSPRecord", "into", "the", "db", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/certdb/sql/database_accessor.go#L219-L246
train
cloudflare/cfssl
certdb/sql/database_accessor.go
GetOCSP
func (d *Accessor) GetOCSP(serial, aki string) (ors []certdb.OCSPRecord, err error) { err = d.checkDB() if err != nil { return nil, err } err = d.db.Select(&ors, fmt.Sprintf(d.db.Rebind(selectOCSPSQL), sqlstruct.Columns(certdb.OCSPRecord{})), serial, aki) if err != nil { return nil, wrapSQLError(err) } return ors, nil }
go
func (d *Accessor) GetOCSP(serial, aki string) (ors []certdb.OCSPRecord, err error) { err = d.checkDB() if err != nil { return nil, err } err = d.db.Select(&ors, fmt.Sprintf(d.db.Rebind(selectOCSPSQL), sqlstruct.Columns(certdb.OCSPRecord{})), serial, aki) if err != nil { return nil, wrapSQLError(err) } return ors, nil }
[ "func", "(", "d", "*", "Accessor", ")", "GetOCSP", "(", "serial", ",", "aki", "string", ")", "(", "ors", "[", "]", "certdb", ".", "OCSPRecord", ",", "err", "error", ")", "{", "err", "=", "d", ".", "checkDB", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "d", ".", "db", ".", "Select", "(", "&", "ors", ",", "fmt", ".", "Sprintf", "(", "d", ".", "db", ".", "Rebind", "(", "selectOCSPSQL", ")", ",", "sqlstruct", ".", "Columns", "(", "certdb", ".", "OCSPRecord", "{", "}", ")", ")", ",", "serial", ",", "aki", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "wrapSQLError", "(", "err", ")", "\n", "}", "\n\n", "return", "ors", ",", "nil", "\n", "}" ]
// GetOCSP retrieves a certdb.OCSPRecord from db by serial.
[ "GetOCSP", "retrieves", "a", "certdb", ".", "OCSPRecord", "from", "db", "by", "serial", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/certdb/sql/database_accessor.go#L249-L261
train
cloudflare/cfssl
certdb/sql/database_accessor.go
GetUnexpiredOCSPs
func (d *Accessor) GetUnexpiredOCSPs() (ors []certdb.OCSPRecord, err error) { err = d.checkDB() if err != nil { return nil, err } err = d.db.Select(&ors, fmt.Sprintf(d.db.Rebind(selectAllUnexpiredOCSPSQL), sqlstruct.Columns(certdb.OCSPRecord{}))) if err != nil { return nil, wrapSQLError(err) } return ors, nil }
go
func (d *Accessor) GetUnexpiredOCSPs() (ors []certdb.OCSPRecord, err error) { err = d.checkDB() if err != nil { return nil, err } err = d.db.Select(&ors, fmt.Sprintf(d.db.Rebind(selectAllUnexpiredOCSPSQL), sqlstruct.Columns(certdb.OCSPRecord{}))) if err != nil { return nil, wrapSQLError(err) } return ors, nil }
[ "func", "(", "d", "*", "Accessor", ")", "GetUnexpiredOCSPs", "(", ")", "(", "ors", "[", "]", "certdb", ".", "OCSPRecord", ",", "err", "error", ")", "{", "err", "=", "d", ".", "checkDB", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "d", ".", "db", ".", "Select", "(", "&", "ors", ",", "fmt", ".", "Sprintf", "(", "d", ".", "db", ".", "Rebind", "(", "selectAllUnexpiredOCSPSQL", ")", ",", "sqlstruct", ".", "Columns", "(", "certdb", ".", "OCSPRecord", "{", "}", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "wrapSQLError", "(", "err", ")", "\n", "}", "\n\n", "return", "ors", ",", "nil", "\n", "}" ]
// GetUnexpiredOCSPs retrieves all unexpired certdb.OCSPRecord from db.
[ "GetUnexpiredOCSPs", "retrieves", "all", "unexpired", "certdb", ".", "OCSPRecord", "from", "db", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/certdb/sql/database_accessor.go#L264-L276
train
cloudflare/cfssl
certdb/sql/database_accessor.go
UpdateOCSP
func (d *Accessor) UpdateOCSP(serial, aki, body string, expiry time.Time) error { err := d.checkDB() if err != nil { return err } result, err := d.db.NamedExec(updateOCSPSQL, &certdb.OCSPRecord{ AKI: aki, Body: body, Expiry: expiry.UTC(), Serial: serial, }) if err != nil { return wrapSQLError(err) } numRowsAffected, err := result.RowsAffected() if numRowsAffected == 0 { return cferr.Wrap(cferr.CertStoreError, cferr.RecordNotFound, fmt.Errorf("failed to update the OCSP record")) } if numRowsAffected != 1 { return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected)) } return err }
go
func (d *Accessor) UpdateOCSP(serial, aki, body string, expiry time.Time) error { err := d.checkDB() if err != nil { return err } result, err := d.db.NamedExec(updateOCSPSQL, &certdb.OCSPRecord{ AKI: aki, Body: body, Expiry: expiry.UTC(), Serial: serial, }) if err != nil { return wrapSQLError(err) } numRowsAffected, err := result.RowsAffected() if numRowsAffected == 0 { return cferr.Wrap(cferr.CertStoreError, cferr.RecordNotFound, fmt.Errorf("failed to update the OCSP record")) } if numRowsAffected != 1 { return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected)) } return err }
[ "func", "(", "d", "*", "Accessor", ")", "UpdateOCSP", "(", "serial", ",", "aki", ",", "body", "string", ",", "expiry", "time", ".", "Time", ")", "error", "{", "err", ":=", "d", ".", "checkDB", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "result", ",", "err", ":=", "d", ".", "db", ".", "NamedExec", "(", "updateOCSPSQL", ",", "&", "certdb", ".", "OCSPRecord", "{", "AKI", ":", "aki", ",", "Body", ":", "body", ",", "Expiry", ":", "expiry", ".", "UTC", "(", ")", ",", "Serial", ":", "serial", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapSQLError", "(", "err", ")", "\n", "}", "\n\n", "numRowsAffected", ",", "err", ":=", "result", ".", "RowsAffected", "(", ")", "\n\n", "if", "numRowsAffected", "==", "0", "{", "return", "cferr", ".", "Wrap", "(", "cferr", ".", "CertStoreError", ",", "cferr", ".", "RecordNotFound", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "if", "numRowsAffected", "!=", "1", "{", "return", "wrapSQLError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "numRowsAffected", ")", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// UpdateOCSP updates a ocsp response record with a given serial number.
[ "UpdateOCSP", "updates", "a", "ocsp", "response", "record", "with", "a", "given", "serial", "number", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/certdb/sql/database_accessor.go#L279-L306
train
cloudflare/cfssl
cli/certinfo/certinfo.go
certinfoMain
func certinfoMain(args []string, c cli.Config) (err error) { var cert *certinfo.Certificate var csr *x509.CertificateRequest if c.CertFile != "" { if c.CertFile == "-" { var certPEM []byte if certPEM, err = cli.ReadStdin(c.CertFile); err != nil { return } if cert, err = certinfo.ParseCertificatePEM(certPEM); err != nil { return } } else { if cert, err = certinfo.ParseCertificateFile(c.CertFile); err != nil { return } } } else if c.CSRFile != "" { if c.CSRFile == "-" { var csrPEM []byte if csrPEM, err = cli.ReadStdin(c.CSRFile); err != nil { return } if csr, err = certinfo.ParseCSRPEM(csrPEM); err != nil { return } } else { if csr, err = certinfo.ParseCSRFile(c.CSRFile); err != nil { return } } } else if c.Domain != "" { if cert, err = certinfo.ParseCertificateDomain(c.Domain); err != nil { return } } else if c.Serial != "" && c.AKI != "" { if c.DBConfigFile == "" { return errors.New("need DB config file (provide with -db-config)") } var db *sqlx.DB db, err = dbconf.DBFromConfig(c.DBConfigFile) if err != nil { return } dbAccessor := sql.NewAccessor(db) if cert, err = certinfo.ParseSerialNumber(c.Serial, c.AKI, dbAccessor); err != nil { return } } else { return errors.New("Must specify certinfo target through -cert, -csr, -domain or -serial + -aki") } var b []byte if cert != nil { b, err = json.MarshalIndent(cert, "", " ") } else if csr != nil { b, err = json.MarshalIndent(csr, "", " ") } if err != nil { return } fmt.Println(string(b)) return }
go
func certinfoMain(args []string, c cli.Config) (err error) { var cert *certinfo.Certificate var csr *x509.CertificateRequest if c.CertFile != "" { if c.CertFile == "-" { var certPEM []byte if certPEM, err = cli.ReadStdin(c.CertFile); err != nil { return } if cert, err = certinfo.ParseCertificatePEM(certPEM); err != nil { return } } else { if cert, err = certinfo.ParseCertificateFile(c.CertFile); err != nil { return } } } else if c.CSRFile != "" { if c.CSRFile == "-" { var csrPEM []byte if csrPEM, err = cli.ReadStdin(c.CSRFile); err != nil { return } if csr, err = certinfo.ParseCSRPEM(csrPEM); err != nil { return } } else { if csr, err = certinfo.ParseCSRFile(c.CSRFile); err != nil { return } } } else if c.Domain != "" { if cert, err = certinfo.ParseCertificateDomain(c.Domain); err != nil { return } } else if c.Serial != "" && c.AKI != "" { if c.DBConfigFile == "" { return errors.New("need DB config file (provide with -db-config)") } var db *sqlx.DB db, err = dbconf.DBFromConfig(c.DBConfigFile) if err != nil { return } dbAccessor := sql.NewAccessor(db) if cert, err = certinfo.ParseSerialNumber(c.Serial, c.AKI, dbAccessor); err != nil { return } } else { return errors.New("Must specify certinfo target through -cert, -csr, -domain or -serial + -aki") } var b []byte if cert != nil { b, err = json.MarshalIndent(cert, "", " ") } else if csr != nil { b, err = json.MarshalIndent(csr, "", " ") } if err != nil { return } fmt.Println(string(b)) return }
[ "func", "certinfoMain", "(", "args", "[", "]", "string", ",", "c", "cli", ".", "Config", ")", "(", "err", "error", ")", "{", "var", "cert", "*", "certinfo", ".", "Certificate", "\n", "var", "csr", "*", "x509", ".", "CertificateRequest", "\n\n", "if", "c", ".", "CertFile", "!=", "\"", "\"", "{", "if", "c", ".", "CertFile", "==", "\"", "\"", "{", "var", "certPEM", "[", "]", "byte", "\n", "if", "certPEM", ",", "err", "=", "cli", ".", "ReadStdin", "(", "c", ".", "CertFile", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "cert", ",", "err", "=", "certinfo", ".", "ParseCertificatePEM", "(", "certPEM", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "else", "{", "if", "cert", ",", "err", "=", "certinfo", ".", "ParseCertificateFile", "(", "c", ".", "CertFile", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}", "else", "if", "c", ".", "CSRFile", "!=", "\"", "\"", "{", "if", "c", ".", "CSRFile", "==", "\"", "\"", "{", "var", "csrPEM", "[", "]", "byte", "\n", "if", "csrPEM", ",", "err", "=", "cli", ".", "ReadStdin", "(", "c", ".", "CSRFile", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "csr", ",", "err", "=", "certinfo", ".", "ParseCSRPEM", "(", "csrPEM", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "else", "{", "if", "csr", ",", "err", "=", "certinfo", ".", "ParseCSRFile", "(", "c", ".", "CSRFile", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}", "else", "if", "c", ".", "Domain", "!=", "\"", "\"", "{", "if", "cert", ",", "err", "=", "certinfo", ".", "ParseCertificateDomain", "(", "c", ".", "Domain", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "else", "if", "c", ".", "Serial", "!=", "\"", "\"", "&&", "c", ".", "AKI", "!=", "\"", "\"", "{", "if", "c", ".", "DBConfigFile", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "db", "*", "sqlx", ".", "DB", "\n\n", "db", ",", "err", "=", "dbconf", ".", "DBFromConfig", "(", "c", ".", "DBConfigFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "dbAccessor", ":=", "sql", ".", "NewAccessor", "(", "db", ")", "\n\n", "if", "cert", ",", "err", "=", "certinfo", ".", "ParseSerialNumber", "(", "c", ".", "Serial", ",", "c", ".", "AKI", ",", "dbAccessor", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "else", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "b", "[", "]", "byte", "\n", "if", "cert", "!=", "nil", "{", "b", ",", "err", "=", "json", ".", "MarshalIndent", "(", "cert", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "else", "if", "csr", "!=", "nil", "{", "b", ",", "err", "=", "json", ".", "MarshalIndent", "(", "csr", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "fmt", ".", "Println", "(", "string", "(", "b", ")", ")", "\n", "return", "\n", "}" ]
// certinfoMain is the main CLI of certinfo functionality
[ "certinfoMain", "is", "the", "main", "CLI", "of", "certinfo", "functionality" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cli/certinfo/certinfo.go#L37-L108
train
cloudflare/cfssl
config/config.go
UnmarshalJSON
func (oid *OID) UnmarshalJSON(data []byte) (err error) { if data[0] != '"' || data[len(data)-1] != '"' { return errors.New("OID JSON string not wrapped in quotes." + string(data)) } data = data[1 : len(data)-1] parsedOid, err := parseObjectIdentifier(string(data)) if err != nil { return err } *oid = OID(parsedOid) return }
go
func (oid *OID) UnmarshalJSON(data []byte) (err error) { if data[0] != '"' || data[len(data)-1] != '"' { return errors.New("OID JSON string not wrapped in quotes." + string(data)) } data = data[1 : len(data)-1] parsedOid, err := parseObjectIdentifier(string(data)) if err != nil { return err } *oid = OID(parsedOid) return }
[ "func", "(", "oid", "*", "OID", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "if", "data", "[", "0", "]", "!=", "'\"'", "||", "data", "[", "len", "(", "data", ")", "-", "1", "]", "!=", "'\"'", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "string", "(", "data", ")", ")", "\n", "}", "\n", "data", "=", "data", "[", "1", ":", "len", "(", "data", ")", "-", "1", "]", "\n", "parsedOid", ",", "err", ":=", "parseObjectIdentifier", "(", "string", "(", "data", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "*", "oid", "=", "OID", "(", "parsedOid", ")", "\n", "return", "\n", "}" ]
// UnmarshalJSON unmarshals a JSON string into an OID.
[ "UnmarshalJSON", "unmarshals", "a", "JSON", "string", "into", "an", "OID", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L108-L119
train
cloudflare/cfssl
config/config.go
MarshalJSON
func (oid OID) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf(`"%v"`, asn1.ObjectIdentifier(oid))), nil }
go
func (oid OID) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf(`"%v"`, asn1.ObjectIdentifier(oid))), nil }
[ "func", "(", "oid", "OID", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "`\"%v\"`", ",", "asn1", ".", "ObjectIdentifier", "(", "oid", ")", ")", ")", ",", "nil", "\n", "}" ]
// MarshalJSON marshals an oid into a JSON string.
[ "MarshalJSON", "marshals", "an", "oid", "into", "a", "JSON", "string", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L122-L124
train
cloudflare/cfssl
config/config.go
SetClientCertKeyPairFromFile
func (p *Signing) SetClientCertKeyPairFromFile(certFile string, keyFile string) error { if certFile != "" && keyFile != "" { cert, err := helpers.LoadClientCertificate(certFile, keyFile) if err != nil { return err } for _, profile := range p.Profiles { profile.ClientCert = cert } p.Default.ClientCert = cert } return nil }
go
func (p *Signing) SetClientCertKeyPairFromFile(certFile string, keyFile string) error { if certFile != "" && keyFile != "" { cert, err := helpers.LoadClientCertificate(certFile, keyFile) if err != nil { return err } for _, profile := range p.Profiles { profile.ClientCert = cert } p.Default.ClientCert = cert } return nil }
[ "func", "(", "p", "*", "Signing", ")", "SetClientCertKeyPairFromFile", "(", "certFile", "string", ",", "keyFile", "string", ")", "error", "{", "if", "certFile", "!=", "\"", "\"", "&&", "keyFile", "!=", "\"", "\"", "{", "cert", ",", "err", ":=", "helpers", ".", "LoadClientCertificate", "(", "certFile", ",", "keyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "profile", ":=", "range", "p", ".", "Profiles", "{", "profile", ".", "ClientCert", "=", "cert", "\n", "}", "\n", "p", ".", "Default", ".", "ClientCert", "=", "cert", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetClientCertKeyPairFromFile updates the properties to set client certificates for mutual // authenticated TLS remote requests
[ "SetClientCertKeyPairFromFile", "updates", "the", "properties", "to", "set", "client", "certificates", "for", "mutual", "authenticated", "TLS", "remote", "requests" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L320-L332
train
cloudflare/cfssl
config/config.go
SetRemoteCAsFromFile
func (p *Signing) SetRemoteCAsFromFile(caFile string) error { if caFile != "" { remoteCAs, err := helpers.LoadPEMCertPool(caFile) if err != nil { return err } p.SetRemoteCAs(remoteCAs) } return nil }
go
func (p *Signing) SetRemoteCAsFromFile(caFile string) error { if caFile != "" { remoteCAs, err := helpers.LoadPEMCertPool(caFile) if err != nil { return err } p.SetRemoteCAs(remoteCAs) } return nil }
[ "func", "(", "p", "*", "Signing", ")", "SetRemoteCAsFromFile", "(", "caFile", "string", ")", "error", "{", "if", "caFile", "!=", "\"", "\"", "{", "remoteCAs", ",", "err", ":=", "helpers", ".", "LoadPEMCertPool", "(", "caFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "SetRemoteCAs", "(", "remoteCAs", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetRemoteCAsFromFile reads root CAs from file and updates the properties to set remote CAs for TLS // remote requests
[ "SetRemoteCAsFromFile", "reads", "root", "CAs", "from", "file", "and", "updates", "the", "properties", "to", "set", "remote", "CAs", "for", "TLS", "remote", "requests" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L336-L345
train
cloudflare/cfssl
config/config.go
SetRemoteCAs
func (p *Signing) SetRemoteCAs(remoteCAs *x509.CertPool) { for _, profile := range p.Profiles { profile.RemoteCAs = remoteCAs } p.Default.RemoteCAs = remoteCAs }
go
func (p *Signing) SetRemoteCAs(remoteCAs *x509.CertPool) { for _, profile := range p.Profiles { profile.RemoteCAs = remoteCAs } p.Default.RemoteCAs = remoteCAs }
[ "func", "(", "p", "*", "Signing", ")", "SetRemoteCAs", "(", "remoteCAs", "*", "x509", ".", "CertPool", ")", "{", "for", "_", ",", "profile", ":=", "range", "p", ".", "Profiles", "{", "profile", ".", "RemoteCAs", "=", "remoteCAs", "\n", "}", "\n", "p", ".", "Default", ".", "RemoteCAs", "=", "remoteCAs", "\n", "}" ]
// SetRemoteCAs updates the properties to set remote CAs for TLS // remote requests
[ "SetRemoteCAs", "updates", "the", "properties", "to", "set", "remote", "CAs", "for", "TLS", "remote", "requests" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L349-L354
train
cloudflare/cfssl
config/config.go
NeedsRemoteSigner
func (p *Signing) NeedsRemoteSigner() bool { for _, profile := range p.Profiles { if profile.RemoteServer != "" { return true } } if p.Default.RemoteServer != "" { return true } return false }
go
func (p *Signing) NeedsRemoteSigner() bool { for _, profile := range p.Profiles { if profile.RemoteServer != "" { return true } } if p.Default.RemoteServer != "" { return true } return false }
[ "func", "(", "p", "*", "Signing", ")", "NeedsRemoteSigner", "(", ")", "bool", "{", "for", "_", ",", "profile", ":=", "range", "p", ".", "Profiles", "{", "if", "profile", ".", "RemoteServer", "!=", "\"", "\"", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "if", "p", ".", "Default", ".", "RemoteServer", "!=", "\"", "\"", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// NeedsRemoteSigner returns true if one of the profiles has a remote set
[ "NeedsRemoteSigner", "returns", "true", "if", "one", "of", "the", "profiles", "has", "a", "remote", "set" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L357-L369
train
cloudflare/cfssl
config/config.go
Usages
func (p *SigningProfile) Usages() (ku x509.KeyUsage, eku []x509.ExtKeyUsage, unk []string) { for _, keyUse := range p.Usage { if kuse, ok := KeyUsage[keyUse]; ok { ku |= kuse } else if ekuse, ok := ExtKeyUsage[keyUse]; ok { eku = append(eku, ekuse) } else { unk = append(unk, keyUse) } } return }
go
func (p *SigningProfile) Usages() (ku x509.KeyUsage, eku []x509.ExtKeyUsage, unk []string) { for _, keyUse := range p.Usage { if kuse, ok := KeyUsage[keyUse]; ok { ku |= kuse } else if ekuse, ok := ExtKeyUsage[keyUse]; ok { eku = append(eku, ekuse) } else { unk = append(unk, keyUse) } } return }
[ "func", "(", "p", "*", "SigningProfile", ")", "Usages", "(", ")", "(", "ku", "x509", ".", "KeyUsage", ",", "eku", "[", "]", "x509", ".", "ExtKeyUsage", ",", "unk", "[", "]", "string", ")", "{", "for", "_", ",", "keyUse", ":=", "range", "p", ".", "Usage", "{", "if", "kuse", ",", "ok", ":=", "KeyUsage", "[", "keyUse", "]", ";", "ok", "{", "ku", "|=", "kuse", "\n", "}", "else", "if", "ekuse", ",", "ok", ":=", "ExtKeyUsage", "[", "keyUse", "]", ";", "ok", "{", "eku", "=", "append", "(", "eku", ",", "ekuse", ")", "\n", "}", "else", "{", "unk", "=", "append", "(", "unk", ",", "keyUse", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Usages parses the list of key uses in the profile, translating them // to a list of X.509 key usages and extended key usages. The unknown // uses are collected into a slice that is also returned.
[ "Usages", "parses", "the", "list", "of", "key", "uses", "in", "the", "profile", "translating", "them", "to", "a", "list", "of", "X", ".", "509", "key", "usages", "and", "extended", "key", "usages", ".", "The", "unknown", "uses", "are", "collected", "into", "a", "slice", "that", "is", "also", "returned", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L389-L400
train
cloudflare/cfssl
config/config.go
hasLocalConfig
func (p *SigningProfile) hasLocalConfig() bool { if p.Usage != nil || p.IssuerURL != nil || p.OCSP != "" || p.ExpiryString != "" || p.BackdateString != "" || p.CAConstraint.IsCA != false || !p.NotBefore.IsZero() || !p.NotAfter.IsZero() || p.NameWhitelistString != "" || len(p.CTLogServers) != 0 { return true } return false }
go
func (p *SigningProfile) hasLocalConfig() bool { if p.Usage != nil || p.IssuerURL != nil || p.OCSP != "" || p.ExpiryString != "" || p.BackdateString != "" || p.CAConstraint.IsCA != false || !p.NotBefore.IsZero() || !p.NotAfter.IsZero() || p.NameWhitelistString != "" || len(p.CTLogServers) != 0 { return true } return false }
[ "func", "(", "p", "*", "SigningProfile", ")", "hasLocalConfig", "(", ")", "bool", "{", "if", "p", ".", "Usage", "!=", "nil", "||", "p", ".", "IssuerURL", "!=", "nil", "||", "p", ".", "OCSP", "!=", "\"", "\"", "||", "p", ".", "ExpiryString", "!=", "\"", "\"", "||", "p", ".", "BackdateString", "!=", "\"", "\"", "||", "p", ".", "CAConstraint", ".", "IsCA", "!=", "false", "||", "!", "p", ".", "NotBefore", ".", "IsZero", "(", ")", "||", "!", "p", ".", "NotAfter", ".", "IsZero", "(", ")", "||", "p", ".", "NameWhitelistString", "!=", "\"", "\"", "||", "len", "(", "p", ".", "CTLogServers", ")", "!=", "0", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// This checks if the SigningProfile object contains configurations that are only effective with a local signer // which has access to CA private key.
[ "This", "checks", "if", "the", "SigningProfile", "object", "contains", "configurations", "that", "are", "only", "effective", "with", "a", "local", "signer", "which", "has", "access", "to", "CA", "private", "key", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L470-L484
train
cloudflare/cfssl
config/config.go
warnSkippedSettings
func (p *Signing) warnSkippedSettings() { const warningMessage = `The configuration value by "usages", "issuer_urls", "ocsp_url", "crl_url", "ca_constraint", "expiry", "backdate", "not_before", "not_after", "cert_store" and "ct_log_servers" are skipped` if p == nil { return } if (p.Default.RemoteName != "" || p.Default.AuthRemote.RemoteName != "") && p.Default.hasLocalConfig() { log.Warning("default profile points to a remote signer: ", warningMessage) } for name, profile := range p.Profiles { if (profile.RemoteName != "" || profile.AuthRemote.RemoteName != "") && profile.hasLocalConfig() { log.Warningf("Profiles[%s] points to a remote signer: %s", name, warningMessage) } } }
go
func (p *Signing) warnSkippedSettings() { const warningMessage = `The configuration value by "usages", "issuer_urls", "ocsp_url", "crl_url", "ca_constraint", "expiry", "backdate", "not_before", "not_after", "cert_store" and "ct_log_servers" are skipped` if p == nil { return } if (p.Default.RemoteName != "" || p.Default.AuthRemote.RemoteName != "") && p.Default.hasLocalConfig() { log.Warning("default profile points to a remote signer: ", warningMessage) } for name, profile := range p.Profiles { if (profile.RemoteName != "" || profile.AuthRemote.RemoteName != "") && profile.hasLocalConfig() { log.Warningf("Profiles[%s] points to a remote signer: %s", name, warningMessage) } } }
[ "func", "(", "p", "*", "Signing", ")", "warnSkippedSettings", "(", ")", "{", "const", "warningMessage", "=", "`The configuration value by \"usages\", \"issuer_urls\", \"ocsp_url\", \"crl_url\", \"ca_constraint\", \"expiry\", \"backdate\", \"not_before\", \"not_after\", \"cert_store\" and \"ct_log_servers\" are skipped`", "\n", "if", "p", "==", "nil", "{", "return", "\n", "}", "\n\n", "if", "(", "p", ".", "Default", ".", "RemoteName", "!=", "\"", "\"", "||", "p", ".", "Default", ".", "AuthRemote", ".", "RemoteName", "!=", "\"", "\"", ")", "&&", "p", ".", "Default", ".", "hasLocalConfig", "(", ")", "{", "log", ".", "Warning", "(", "\"", "\"", ",", "warningMessage", ")", "\n", "}", "\n\n", "for", "name", ",", "profile", ":=", "range", "p", ".", "Profiles", "{", "if", "(", "profile", ".", "RemoteName", "!=", "\"", "\"", "||", "profile", ".", "AuthRemote", ".", "RemoteName", "!=", "\"", "\"", ")", "&&", "profile", ".", "hasLocalConfig", "(", ")", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "name", ",", "warningMessage", ")", "\n", "}", "\n", "}", "\n", "}" ]
// warnSkippedSettings prints a log warning message about skipped settings // in a SigningProfile, usually due to remote signer.
[ "warnSkippedSettings", "prints", "a", "log", "warning", "message", "about", "skipped", "settings", "in", "a", "SigningProfile", "usually", "due", "to", "remote", "signer", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L488-L503
train
cloudflare/cfssl
config/config.go
Valid
func (p *Signing) Valid() bool { if p == nil { return false } log.Debugf("validating configuration") if !p.Default.validProfile(true) { log.Debugf("default profile is invalid") return false } for _, sp := range p.Profiles { if !sp.validProfile(false) { log.Debugf("invalid profile") return false } } p.warnSkippedSettings() return true }
go
func (p *Signing) Valid() bool { if p == nil { return false } log.Debugf("validating configuration") if !p.Default.validProfile(true) { log.Debugf("default profile is invalid") return false } for _, sp := range p.Profiles { if !sp.validProfile(false) { log.Debugf("invalid profile") return false } } p.warnSkippedSettings() return true }
[ "func", "(", "p", "*", "Signing", ")", "Valid", "(", ")", "bool", "{", "if", "p", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "if", "!", "p", ".", "Default", ".", "validProfile", "(", "true", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "false", "\n", "}", "\n\n", "for", "_", ",", "sp", ":=", "range", "p", ".", "Profiles", "{", "if", "!", "sp", ".", "validProfile", "(", "false", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n\n", "p", ".", "warnSkippedSettings", "(", ")", "\n\n", "return", "true", "\n", "}" ]
// Valid checks the signature policies, ensuring they are valid // policies. A policy is valid if it has defined at least key usages // to be used, and a valid default profile has defined at least a // default expiration.
[ "Valid", "checks", "the", "signature", "policies", "ensuring", "they", "are", "valid", "policies", ".", "A", "policy", "is", "valid", "if", "it", "has", "defined", "at", "least", "key", "usages", "to", "be", "used", "and", "a", "valid", "default", "profile", "has", "defined", "at", "least", "a", "default", "expiration", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L529-L550
train
cloudflare/cfssl
config/config.go
DefaultConfig
func DefaultConfig() *SigningProfile { d := helpers.OneYear return &SigningProfile{ Usage: []string{"signing", "key encipherment", "server auth", "client auth"}, Expiry: d, ExpiryString: "8760h", } }
go
func DefaultConfig() *SigningProfile { d := helpers.OneYear return &SigningProfile{ Usage: []string{"signing", "key encipherment", "server auth", "client auth"}, Expiry: d, ExpiryString: "8760h", } }
[ "func", "DefaultConfig", "(", ")", "*", "SigningProfile", "{", "d", ":=", "helpers", ".", "OneYear", "\n", "return", "&", "SigningProfile", "{", "Usage", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "Expiry", ":", "d", ",", "ExpiryString", ":", "\"", "\"", ",", "}", "\n", "}" ]
// DefaultConfig returns a default configuration specifying basic key // usage and a 1 year expiration time. The key usages chosen are // signing, key encipherment, client auth and server auth.
[ "DefaultConfig", "returns", "a", "default", "configuration", "specifying", "basic", "key", "usage", "and", "a", "1", "year", "expiration", "time", ".", "The", "key", "usages", "chosen", "are", "signing", "key", "encipherment", "client", "auth", "and", "server", "auth", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L599-L606
train
cloudflare/cfssl
config/config.go
LoadFile
func LoadFile(path string) (*Config, error) { log.Debugf("loading configuration file from %s", path) if path == "" { return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid path")) } body, err := ioutil.ReadFile(path) if err != nil { return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("could not read configuration file")) } return LoadConfig(body) }
go
func LoadFile(path string) (*Config, error) { log.Debugf("loading configuration file from %s", path) if path == "" { return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid path")) } body, err := ioutil.ReadFile(path) if err != nil { return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("could not read configuration file")) } return LoadConfig(body) }
[ "func", "LoadFile", "(", "path", "string", ")", "(", "*", "Config", ",", "error", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "path", ")", "\n", "if", "path", "==", "\"", "\"", "{", "return", "nil", ",", "cferr", ".", "Wrap", "(", "cferr", ".", "PolicyError", ",", "cferr", ".", "InvalidPolicy", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "body", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "cferr", ".", "Wrap", "(", "cferr", ".", "PolicyError", ",", "cferr", ".", "InvalidPolicy", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "return", "LoadConfig", "(", "body", ")", "\n", "}" ]
// LoadFile attempts to load the configuration file stored at the path // and returns the configuration. On error, it returns nil.
[ "LoadFile", "attempts", "to", "load", "the", "configuration", "file", "stored", "at", "the", "path", "and", "returns", "the", "configuration", ".", "On", "error", "it", "returns", "nil", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L610-L622
train
cloudflare/cfssl
config/config.go
LoadConfig
func LoadConfig(config []byte) (*Config, error) { var cfg = &Config{} err := json.Unmarshal(config, &cfg) if err != nil { return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("failed to unmarshal configuration: "+err.Error())) } if cfg.Signing == nil { return nil, errors.New("No \"signing\" field present") } if cfg.Signing.Default == nil { log.Debugf("no default given: using default config") cfg.Signing.Default = DefaultConfig() } else { if err := cfg.Signing.Default.populate(cfg); err != nil { return nil, err } } for k := range cfg.Signing.Profiles { if err := cfg.Signing.Profiles[k].populate(cfg); err != nil { return nil, err } } if !cfg.Valid() { return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid configuration")) } log.Debugf("configuration ok") return cfg, nil }
go
func LoadConfig(config []byte) (*Config, error) { var cfg = &Config{} err := json.Unmarshal(config, &cfg) if err != nil { return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("failed to unmarshal configuration: "+err.Error())) } if cfg.Signing == nil { return nil, errors.New("No \"signing\" field present") } if cfg.Signing.Default == nil { log.Debugf("no default given: using default config") cfg.Signing.Default = DefaultConfig() } else { if err := cfg.Signing.Default.populate(cfg); err != nil { return nil, err } } for k := range cfg.Signing.Profiles { if err := cfg.Signing.Profiles[k].populate(cfg); err != nil { return nil, err } } if !cfg.Valid() { return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid configuration")) } log.Debugf("configuration ok") return cfg, nil }
[ "func", "LoadConfig", "(", "config", "[", "]", "byte", ")", "(", "*", "Config", ",", "error", ")", "{", "var", "cfg", "=", "&", "Config", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "config", ",", "&", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "cferr", ".", "Wrap", "(", "cferr", ".", "PolicyError", ",", "cferr", ".", "InvalidPolicy", ",", "errors", ".", "New", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n\n", "if", "cfg", ".", "Signing", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "}", "\n\n", "if", "cfg", ".", "Signing", ".", "Default", "==", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "cfg", ".", "Signing", ".", "Default", "=", "DefaultConfig", "(", ")", "\n", "}", "else", "{", "if", "err", ":=", "cfg", ".", "Signing", ".", "Default", ".", "populate", "(", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "for", "k", ":=", "range", "cfg", ".", "Signing", ".", "Profiles", "{", "if", "err", ":=", "cfg", ".", "Signing", ".", "Profiles", "[", "k", "]", ".", "populate", "(", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "!", "cfg", ".", "Valid", "(", ")", "{", "return", "nil", ",", "cferr", ".", "Wrap", "(", "cferr", ".", "PolicyError", ",", "cferr", ".", "InvalidPolicy", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "cfg", ",", "nil", "\n", "}" ]
// LoadConfig attempts to load the configuration from a byte slice. // On error, it returns nil.
[ "LoadConfig", "attempts", "to", "load", "the", "configuration", "from", "a", "byte", "slice", ".", "On", "error", "it", "returns", "nil", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/config/config.go#L626-L659
train
cloudflare/cfssl
transport/client.go
TLSClientAuthClientConfig
func (tr *Transport) TLSClientAuthClientConfig(host string) (*tls.Config, error) { cert, err := tr.getCertificate() if err != nil { return nil, err } return &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: tr.TrustStore.Pool(), ServerName: host, CipherSuites: core.CipherSuites, MinVersion: tls.VersionTLS12, ClientAuth: tls.RequireAndVerifyClientCert, }, nil }
go
func (tr *Transport) TLSClientAuthClientConfig(host string) (*tls.Config, error) { cert, err := tr.getCertificate() if err != nil { return nil, err } return &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: tr.TrustStore.Pool(), ServerName: host, CipherSuites: core.CipherSuites, MinVersion: tls.VersionTLS12, ClientAuth: tls.RequireAndVerifyClientCert, }, nil }
[ "func", "(", "tr", "*", "Transport", ")", "TLSClientAuthClientConfig", "(", "host", "string", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "cert", ",", "err", ":=", "tr", ".", "getCertificate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "tls", ".", "Config", "{", "Certificates", ":", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", ",", "RootCAs", ":", "tr", ".", "TrustStore", ".", "Pool", "(", ")", ",", "ServerName", ":", "host", ",", "CipherSuites", ":", "core", ".", "CipherSuites", ",", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "ClientAuth", ":", "tls", ".", "RequireAndVerifyClientCert", ",", "}", ",", "nil", "\n", "}" ]
// TLSClientAuthClientConfig returns a new client authentication TLS // configuration that can be used for a client using client auth // connecting to the named host.
[ "TLSClientAuthClientConfig", "returns", "a", "new", "client", "authentication", "TLS", "configuration", "that", "can", "be", "used", "for", "a", "client", "using", "client", "auth", "connecting", "to", "the", "named", "host", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/client.go#L85-L99
train
cloudflare/cfssl
transport/client.go
TLSClientAuthServerConfig
func (tr *Transport) TLSClientAuthServerConfig() (*tls.Config, error) { cert, err := tr.getCertificate() if err != nil { return nil, err } return &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: tr.TrustStore.Pool(), ClientCAs: tr.ClientTrustStore.Pool(), ClientAuth: tls.RequireAndVerifyClientCert, CipherSuites: core.CipherSuites, MinVersion: tls.VersionTLS12, }, nil }
go
func (tr *Transport) TLSClientAuthServerConfig() (*tls.Config, error) { cert, err := tr.getCertificate() if err != nil { return nil, err } return &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: tr.TrustStore.Pool(), ClientCAs: tr.ClientTrustStore.Pool(), ClientAuth: tls.RequireAndVerifyClientCert, CipherSuites: core.CipherSuites, MinVersion: tls.VersionTLS12, }, nil }
[ "func", "(", "tr", "*", "Transport", ")", "TLSClientAuthServerConfig", "(", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "cert", ",", "err", ":=", "tr", ".", "getCertificate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "tls", ".", "Config", "{", "Certificates", ":", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", ",", "RootCAs", ":", "tr", ".", "TrustStore", ".", "Pool", "(", ")", ",", "ClientCAs", ":", "tr", ".", "ClientTrustStore", ".", "Pool", "(", ")", ",", "ClientAuth", ":", "tls", ".", "RequireAndVerifyClientCert", ",", "CipherSuites", ":", "core", ".", "CipherSuites", ",", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "}", ",", "nil", "\n", "}" ]
// TLSClientAuthServerConfig returns a new client authentication TLS // configuration for servers expecting mutually authenticated // clients. The clientAuth parameter should contain the root pool used // to authenticate clients.
[ "TLSClientAuthServerConfig", "returns", "a", "new", "client", "authentication", "TLS", "configuration", "for", "servers", "expecting", "mutually", "authenticated", "clients", ".", "The", "clientAuth", "parameter", "should", "contain", "the", "root", "pool", "used", "to", "authenticate", "clients", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/client.go#L105-L119
train
cloudflare/cfssl
transport/client.go
TLSServerConfig
func (tr *Transport) TLSServerConfig() (*tls.Config, error) { cert, err := tr.getCertificate() if err != nil { return nil, err } return &tls.Config{ Certificates: []tls.Certificate{cert}, CipherSuites: core.CipherSuites, MinVersion: tls.VersionTLS12, }, nil }
go
func (tr *Transport) TLSServerConfig() (*tls.Config, error) { cert, err := tr.getCertificate() if err != nil { return nil, err } return &tls.Config{ Certificates: []tls.Certificate{cert}, CipherSuites: core.CipherSuites, MinVersion: tls.VersionTLS12, }, nil }
[ "func", "(", "tr", "*", "Transport", ")", "TLSServerConfig", "(", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "cert", ",", "err", ":=", "tr", ".", "getCertificate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "tls", ".", "Config", "{", "Certificates", ":", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", ",", "CipherSuites", ":", "core", ".", "CipherSuites", ",", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "}", ",", "nil", "\n", "}" ]
// TLSServerConfig is a general server configuration that should be // used for non-client authentication purposes, such as HTTPS.
[ "TLSServerConfig", "is", "a", "general", "server", "configuration", "that", "should", "be", "used", "for", "non", "-", "client", "authentication", "purposes", "such", "as", "HTTPS", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/client.go#L123-L134
train
cloudflare/cfssl
transport/client.go
New
func New(before time.Duration, identity *core.Identity) (*Transport, error) { var tr = &Transport{ Before: before, Identity: identity, Backoff: &backoff.Backoff{}, } store, err := roots.New(identity.Roots) if err != nil { return nil, err } tr.TrustStore = store if len(identity.ClientRoots) > 0 { store, err = roots.New(identity.ClientRoots) if err != nil { return nil, err } tr.ClientTrustStore = store } tr.Provider, err = NewKeyProvider(identity) if err != nil { return nil, err } tr.CA, err = NewCA(identity) if err != nil { return nil, err } return tr, nil }
go
func New(before time.Duration, identity *core.Identity) (*Transport, error) { var tr = &Transport{ Before: before, Identity: identity, Backoff: &backoff.Backoff{}, } store, err := roots.New(identity.Roots) if err != nil { return nil, err } tr.TrustStore = store if len(identity.ClientRoots) > 0 { store, err = roots.New(identity.ClientRoots) if err != nil { return nil, err } tr.ClientTrustStore = store } tr.Provider, err = NewKeyProvider(identity) if err != nil { return nil, err } tr.CA, err = NewCA(identity) if err != nil { return nil, err } return tr, nil }
[ "func", "New", "(", "before", "time", ".", "Duration", ",", "identity", "*", "core", ".", "Identity", ")", "(", "*", "Transport", ",", "error", ")", "{", "var", "tr", "=", "&", "Transport", "{", "Before", ":", "before", ",", "Identity", ":", "identity", ",", "Backoff", ":", "&", "backoff", ".", "Backoff", "{", "}", ",", "}", "\n\n", "store", ",", "err", ":=", "roots", ".", "New", "(", "identity", ".", "Roots", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tr", ".", "TrustStore", "=", "store", "\n\n", "if", "len", "(", "identity", ".", "ClientRoots", ")", ">", "0", "{", "store", ",", "err", "=", "roots", ".", "New", "(", "identity", ".", "ClientRoots", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tr", ".", "ClientTrustStore", "=", "store", "\n", "}", "\n\n", "tr", ".", "Provider", ",", "err", "=", "NewKeyProvider", "(", "identity", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "tr", ".", "CA", ",", "err", "=", "NewCA", "(", "identity", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "tr", ",", "nil", "\n", "}" ]
// New builds a new transport from an identity and a before time. The // before time tells the transport how long before the certificate // expires to start attempting to update when auto-updating. If before // is longer than the certificate's lifetime, every update check will // trigger a new certificate to be generated.
[ "New", "builds", "a", "new", "transport", "from", "an", "identity", "and", "a", "before", "time", ".", "The", "before", "time", "tells", "the", "transport", "how", "long", "before", "the", "certificate", "expires", "to", "start", "attempting", "to", "update", "when", "auto", "-", "updating", ".", "If", "before", "is", "longer", "than", "the", "certificate", "s", "lifetime", "every", "update", "check", "will", "trigger", "a", "new", "certificate", "to", "be", "generated", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/client.go#L141-L173
train
cloudflare/cfssl
transport/client.go
Lifespan
func (tr *Transport) Lifespan() time.Duration { cert := tr.Provider.Certificate() if cert == nil { return 0 } now := time.Now() if now.After(cert.NotAfter) { return 0 } now = now.Add(tr.Before) ls := cert.NotAfter.Sub(now) log.Debugf(" LIFESPAN:\t%s", ls) if ls < 0 { return 0 } return ls }
go
func (tr *Transport) Lifespan() time.Duration { cert := tr.Provider.Certificate() if cert == nil { return 0 } now := time.Now() if now.After(cert.NotAfter) { return 0 } now = now.Add(tr.Before) ls := cert.NotAfter.Sub(now) log.Debugf(" LIFESPAN:\t%s", ls) if ls < 0 { return 0 } return ls }
[ "func", "(", "tr", "*", "Transport", ")", "Lifespan", "(", ")", "time", ".", "Duration", "{", "cert", ":=", "tr", ".", "Provider", ".", "Certificate", "(", ")", "\n", "if", "cert", "==", "nil", "{", "return", "0", "\n", "}", "\n\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "if", "now", ".", "After", "(", "cert", ".", "NotAfter", ")", "{", "return", "0", "\n", "}", "\n\n", "now", "=", "now", ".", "Add", "(", "tr", ".", "Before", ")", "\n", "ls", ":=", "cert", ".", "NotAfter", ".", "Sub", "(", "now", ")", "\n", "log", ".", "Debugf", "(", "\"", "\\t", "\"", ",", "ls", ")", "\n", "if", "ls", "<", "0", "{", "return", "0", "\n", "}", "\n", "return", "ls", "\n", "}" ]
// Lifespan returns how much time is left before the transport's // certificate expires, or 0 if the certificate is not present or // expired.
[ "Lifespan", "returns", "how", "much", "time", "is", "left", "before", "the", "transport", "s", "certificate", "expires", "or", "0", "if", "the", "certificate", "is", "not", "present", "or", "expired", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/client.go#L178-L196
train
cloudflare/cfssl
transport/client.go
Dial
func Dial(address string, tr *Transport) (*tls.Conn, error) { host, _, err := net.SplitHostPort(address) if err != nil { // Assume address is a hostname, and that it should // use the HTTPS port number. host = address address = net.JoinHostPort(address, "443") } cfg, err := tr.TLSClientAuthClientConfig(host) if err != nil { return nil, err } conn, err := tls.Dial("tcp", address, cfg) if err != nil { return nil, err } state := conn.ConnectionState() if len(state.VerifiedChains) == 0 { return nil, errors.New(errors.CertificateError, errors.VerifyFailed) } for _, chain := range state.VerifiedChains { for _, cert := range chain { revoked, ok := revoke.VerifyCertificate(cert) if (!tr.RevokeSoftFail && !ok) || revoked { return nil, errors.New(errors.CertificateError, errors.VerifyFailed) } } } return conn, nil }
go
func Dial(address string, tr *Transport) (*tls.Conn, error) { host, _, err := net.SplitHostPort(address) if err != nil { // Assume address is a hostname, and that it should // use the HTTPS port number. host = address address = net.JoinHostPort(address, "443") } cfg, err := tr.TLSClientAuthClientConfig(host) if err != nil { return nil, err } conn, err := tls.Dial("tcp", address, cfg) if err != nil { return nil, err } state := conn.ConnectionState() if len(state.VerifiedChains) == 0 { return nil, errors.New(errors.CertificateError, errors.VerifyFailed) } for _, chain := range state.VerifiedChains { for _, cert := range chain { revoked, ok := revoke.VerifyCertificate(cert) if (!tr.RevokeSoftFail && !ok) || revoked { return nil, errors.New(errors.CertificateError, errors.VerifyFailed) } } } return conn, nil }
[ "func", "Dial", "(", "address", "string", ",", "tr", "*", "Transport", ")", "(", "*", "tls", ".", "Conn", ",", "error", ")", "{", "host", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "// Assume address is a hostname, and that it should", "// use the HTTPS port number.", "host", "=", "address", "\n", "address", "=", "net", ".", "JoinHostPort", "(", "address", ",", "\"", "\"", ")", "\n", "}", "\n\n", "cfg", ",", "err", ":=", "tr", ".", "TLSClientAuthClientConfig", "(", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "conn", ",", "err", ":=", "tls", ".", "Dial", "(", "\"", "\"", ",", "address", ",", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "state", ":=", "conn", ".", "ConnectionState", "(", ")", "\n", "if", "len", "(", "state", ".", "VerifiedChains", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "errors", ".", "CertificateError", ",", "errors", ".", "VerifyFailed", ")", "\n", "}", "\n\n", "for", "_", ",", "chain", ":=", "range", "state", ".", "VerifiedChains", "{", "for", "_", ",", "cert", ":=", "range", "chain", "{", "revoked", ",", "ok", ":=", "revoke", ".", "VerifyCertificate", "(", "cert", ")", "\n", "if", "(", "!", "tr", ".", "RevokeSoftFail", "&&", "!", "ok", ")", "||", "revoked", "{", "return", "nil", ",", "errors", ".", "New", "(", "errors", ".", "CertificateError", ",", "errors", ".", "VerifyFailed", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "conn", ",", "nil", "\n", "}" ]
// Dial initiates a TLS connection to an outbound server. It returns a // TLS connection to the server.
[ "Dial", "initiates", "a", "TLS", "connection", "to", "an", "outbound", "server", ".", "It", "returns", "a", "TLS", "connection", "to", "the", "server", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/transport/client.go#L289-L323
train
cloudflare/cfssl
scan/tls_session.go
sessionResumeScan
func sessionResumeScan(addr, hostname string) (grade Grade, output Output, err error) { config := defaultTLSConfig(hostname) config.ClientSessionCache = tls.NewLRUClientSessionCache(1) conn, err := tls.DialWithDialer(Dialer, Network, addr, config) if err != nil { return } if err = conn.Close(); err != nil { return } return multiscan(addr, func(addrport string) (g Grade, o Output, e error) { var conn *tls.Conn if conn, e = tls.DialWithDialer(Dialer, Network, addrport, config); e != nil { return } conn.Close() if o = conn.ConnectionState().DidResume; o.(bool) { g = Good } return }) }
go
func sessionResumeScan(addr, hostname string) (grade Grade, output Output, err error) { config := defaultTLSConfig(hostname) config.ClientSessionCache = tls.NewLRUClientSessionCache(1) conn, err := tls.DialWithDialer(Dialer, Network, addr, config) if err != nil { return } if err = conn.Close(); err != nil { return } return multiscan(addr, func(addrport string) (g Grade, o Output, e error) { var conn *tls.Conn if conn, e = tls.DialWithDialer(Dialer, Network, addrport, config); e != nil { return } conn.Close() if o = conn.ConnectionState().DidResume; o.(bool) { g = Good } return }) }
[ "func", "sessionResumeScan", "(", "addr", ",", "hostname", "string", ")", "(", "grade", "Grade", ",", "output", "Output", ",", "err", "error", ")", "{", "config", ":=", "defaultTLSConfig", "(", "hostname", ")", "\n", "config", ".", "ClientSessionCache", "=", "tls", ".", "NewLRUClientSessionCache", "(", "1", ")", "\n\n", "conn", ",", "err", ":=", "tls", ".", "DialWithDialer", "(", "Dialer", ",", "Network", ",", "addr", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "conn", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "return", "multiscan", "(", "addr", ",", "func", "(", "addrport", "string", ")", "(", "g", "Grade", ",", "o", "Output", ",", "e", "error", ")", "{", "var", "conn", "*", "tls", ".", "Conn", "\n", "if", "conn", ",", "e", "=", "tls", ".", "DialWithDialer", "(", "Dialer", ",", "Network", ",", "addrport", ",", "config", ")", ";", "e", "!=", "nil", "{", "return", "\n", "}", "\n", "conn", ".", "Close", "(", ")", "\n\n", "if", "o", "=", "conn", ".", "ConnectionState", "(", ")", ".", "DidResume", ";", "o", ".", "(", "bool", ")", "{", "g", "=", "Good", "\n", "}", "\n", "return", "\n", "}", ")", "\n", "}" ]
// SessionResumeScan tests that host is able to resume sessions across all addresses.
[ "SessionResumeScan", "tests", "that", "host", "is", "able", "to", "resume", "sessions", "across", "all", "addresses", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/tls_session.go#L18-L42
train
cloudflare/cfssl
cli/ocspsign/ocspsign.go
ocspSignerMain
func ocspSignerMain(args []string, c cli.Config) (err error) { // Read the cert to be revoked from file certBytes, err := ioutil.ReadFile(c.CertFile) if err != nil { log.Critical("Unable to read certificate: ", err) return } cert, err := helpers.ParseCertificatePEM(certBytes) if err != nil { log.Critical("Unable to parse certificate: ", err) return } req := ocsp.SignRequest{ Certificate: cert, Status: c.Status, } if c.Status == "revoked" { var reasonCode int reasonCode, err = ocsp.ReasonStringToCode(c.Reason) if err != nil { log.Critical("Invalid reason code: ", err) return } req.Reason = reasonCode req.RevokedAt = time.Now() if c.RevokedAt != "now" { req.RevokedAt, err = time.Parse("2006-01-02", c.RevokedAt) if err != nil { log.Critical("Malformed revocation time: ", c.RevokedAt) return } } } s, err := SignerFromConfig(c) if err != nil { log.Critical("Unable to create OCSP signer: ", err) return } resp, err := s.Sign(req) if err != nil { log.Critical("Unable to sign OCSP response: ", err) return } cli.PrintOCSPResponse(resp) return }
go
func ocspSignerMain(args []string, c cli.Config) (err error) { // Read the cert to be revoked from file certBytes, err := ioutil.ReadFile(c.CertFile) if err != nil { log.Critical("Unable to read certificate: ", err) return } cert, err := helpers.ParseCertificatePEM(certBytes) if err != nil { log.Critical("Unable to parse certificate: ", err) return } req := ocsp.SignRequest{ Certificate: cert, Status: c.Status, } if c.Status == "revoked" { var reasonCode int reasonCode, err = ocsp.ReasonStringToCode(c.Reason) if err != nil { log.Critical("Invalid reason code: ", err) return } req.Reason = reasonCode req.RevokedAt = time.Now() if c.RevokedAt != "now" { req.RevokedAt, err = time.Parse("2006-01-02", c.RevokedAt) if err != nil { log.Critical("Malformed revocation time: ", c.RevokedAt) return } } } s, err := SignerFromConfig(c) if err != nil { log.Critical("Unable to create OCSP signer: ", err) return } resp, err := s.Sign(req) if err != nil { log.Critical("Unable to sign OCSP response: ", err) return } cli.PrintOCSPResponse(resp) return }
[ "func", "ocspSignerMain", "(", "args", "[", "]", "string", ",", "c", "cli", ".", "Config", ")", "(", "err", "error", ")", "{", "// Read the cert to be revoked from file", "certBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "c", ".", "CertFile", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Critical", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "cert", ",", "err", ":=", "helpers", ".", "ParseCertificatePEM", "(", "certBytes", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Critical", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "req", ":=", "ocsp", ".", "SignRequest", "{", "Certificate", ":", "cert", ",", "Status", ":", "c", ".", "Status", ",", "}", "\n\n", "if", "c", ".", "Status", "==", "\"", "\"", "{", "var", "reasonCode", "int", "\n", "reasonCode", ",", "err", "=", "ocsp", ".", "ReasonStringToCode", "(", "c", ".", "Reason", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Critical", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "req", ".", "Reason", "=", "reasonCode", "\n", "req", ".", "RevokedAt", "=", "time", ".", "Now", "(", ")", "\n", "if", "c", ".", "RevokedAt", "!=", "\"", "\"", "{", "req", ".", "RevokedAt", ",", "err", "=", "time", ".", "Parse", "(", "\"", "\"", ",", "c", ".", "RevokedAt", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Critical", "(", "\"", "\"", ",", "c", ".", "RevokedAt", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n\n", "s", ",", "err", ":=", "SignerFromConfig", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Critical", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "resp", ",", "err", ":=", "s", ".", "Sign", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Critical", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "cli", ".", "PrintOCSPResponse", "(", "resp", ")", "\n", "return", "\n", "}" ]
// ocspSignerMain is the main CLI of OCSP signer functionality.
[ "ocspSignerMain", "is", "the", "main", "CLI", "of", "OCSP", "signer", "functionality", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cli/ocspsign/ocspsign.go#L28-L79
train
cloudflare/cfssl
cli/ocspsign/ocspsign.go
SignerFromConfig
func SignerFromConfig(c cli.Config) (ocsp.Signer, error) { //if this is called from serve then we need to use the specific responder key file //fallback to key for backwards-compatibility k := c.ResponderKeyFile if k == "" { k = c.KeyFile } return ocsp.NewSignerFromFile(c.CAFile, c.ResponderFile, k, time.Duration(c.Interval)) }
go
func SignerFromConfig(c cli.Config) (ocsp.Signer, error) { //if this is called from serve then we need to use the specific responder key file //fallback to key for backwards-compatibility k := c.ResponderKeyFile if k == "" { k = c.KeyFile } return ocsp.NewSignerFromFile(c.CAFile, c.ResponderFile, k, time.Duration(c.Interval)) }
[ "func", "SignerFromConfig", "(", "c", "cli", ".", "Config", ")", "(", "ocsp", ".", "Signer", ",", "error", ")", "{", "//if this is called from serve then we need to use the specific responder key file", "//fallback to key for backwards-compatibility", "k", ":=", "c", ".", "ResponderKeyFile", "\n", "if", "k", "==", "\"", "\"", "{", "k", "=", "c", ".", "KeyFile", "\n", "}", "\n", "return", "ocsp", ".", "NewSignerFromFile", "(", "c", ".", "CAFile", ",", "c", ".", "ResponderFile", ",", "k", ",", "time", ".", "Duration", "(", "c", ".", "Interval", ")", ")", "\n", "}" ]
// SignerFromConfig creates a signer from a cli.Config as a helper for cli and serve
[ "SignerFromConfig", "creates", "a", "signer", "from", "a", "cli", ".", "Config", "as", "a", "helper", "for", "cli", "and", "serve" ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/cli/ocspsign/ocspsign.go#L82-L90
train
cloudflare/cfssl
whitelist/lookup.go
NetConnLookup
func NetConnLookup(conn net.Conn) (net.IP, error) { if conn == nil { return nil, errors.New("whitelist: no connection") } netAddr := conn.RemoteAddr() if netAddr == nil { return nil, errors.New("whitelist: no address returned") } addr, _, err := net.SplitHostPort(netAddr.String()) if err != nil { return nil, err } ip := net.ParseIP(addr) return ip, nil }
go
func NetConnLookup(conn net.Conn) (net.IP, error) { if conn == nil { return nil, errors.New("whitelist: no connection") } netAddr := conn.RemoteAddr() if netAddr == nil { return nil, errors.New("whitelist: no address returned") } addr, _, err := net.SplitHostPort(netAddr.String()) if err != nil { return nil, err } ip := net.ParseIP(addr) return ip, nil }
[ "func", "NetConnLookup", "(", "conn", "net", ".", "Conn", ")", "(", "net", ".", "IP", ",", "error", ")", "{", "if", "conn", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "netAddr", ":=", "conn", ".", "RemoteAddr", "(", ")", "\n", "if", "netAddr", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "addr", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "netAddr", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ip", ":=", "net", ".", "ParseIP", "(", "addr", ")", "\n", "return", "ip", ",", "nil", "\n", "}" ]
// NetConnLookup extracts an IP from the remote address in the // net.Conn. A single net.Conn should be passed to Address.
[ "NetConnLookup", "extracts", "an", "IP", "from", "the", "remote", "address", "in", "the", "net", ".", "Conn", ".", "A", "single", "net", ".", "Conn", "should", "be", "passed", "to", "Address", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/lookup.go#L12-L29
train
cloudflare/cfssl
whitelist/lookup.go
NewHandler
func NewHandler(allow, deny http.Handler, acl ACL) (http.Handler, error) { if allow == nil { return nil, errors.New("whitelist: allow cannot be nil") } if acl == nil { return nil, errors.New("whitelist: ACL cannot be nil") } return &Handler{ allowHandler: allow, denyHandler: deny, whitelist: acl, }, nil }
go
func NewHandler(allow, deny http.Handler, acl ACL) (http.Handler, error) { if allow == nil { return nil, errors.New("whitelist: allow cannot be nil") } if acl == nil { return nil, errors.New("whitelist: ACL cannot be nil") } return &Handler{ allowHandler: allow, denyHandler: deny, whitelist: acl, }, nil }
[ "func", "NewHandler", "(", "allow", ",", "deny", "http", ".", "Handler", ",", "acl", "ACL", ")", "(", "http", ".", "Handler", ",", "error", ")", "{", "if", "allow", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "acl", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "Handler", "{", "allowHandler", ":", "allow", ",", "denyHandler", ":", "deny", ",", "whitelist", ":", "acl", ",", "}", ",", "nil", "\n", "}" ]
// NewHandler returns a new whitelisting-wrapped HTTP handler. The // allow handler should contain a handler that will be called if the // request is whitelisted; the deny handler should contain a handler // that will be called in the request is not whitelisted.
[ "NewHandler", "returns", "a", "new", "whitelisting", "-", "wrapped", "HTTP", "handler", ".", "The", "allow", "handler", "should", "contain", "a", "handler", "that", "will", "be", "called", "if", "the", "request", "is", "whitelisted", ";", "the", "deny", "handler", "should", "contain", "a", "handler", "that", "will", "be", "called", "in", "the", "request", "is", "not", "whitelisted", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/lookup.go#L59-L73
train
cloudflare/cfssl
whitelist/lookup.go
ServeHTTP
func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { ip, err := HTTPRequestLookup(req) if err != nil { log.Printf("failed to lookup request address: %v", err) status := http.StatusInternalServerError http.Error(w, http.StatusText(status), status) return } if h.whitelist.Permitted(ip) { h.allowHandler.ServeHTTP(w, req) } else { if h.denyHandler == nil { status := http.StatusUnauthorized http.Error(w, http.StatusText(status), status) } else { h.denyHandler.ServeHTTP(w, req) } } }
go
func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { ip, err := HTTPRequestLookup(req) if err != nil { log.Printf("failed to lookup request address: %v", err) status := http.StatusInternalServerError http.Error(w, http.StatusText(status), status) return } if h.whitelist.Permitted(ip) { h.allowHandler.ServeHTTP(w, req) } else { if h.denyHandler == nil { status := http.StatusUnauthorized http.Error(w, http.StatusText(status), status) } else { h.denyHandler.ServeHTTP(w, req) } } }
[ "func", "(", "h", "*", "Handler", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "ip", ",", "err", ":=", "HTTPRequestLookup", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "status", ":=", "http", ".", "StatusInternalServerError", "\n", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "status", ")", ",", "status", ")", "\n", "return", "\n", "}", "\n\n", "if", "h", ".", "whitelist", ".", "Permitted", "(", "ip", ")", "{", "h", ".", "allowHandler", ".", "ServeHTTP", "(", "w", ",", "req", ")", "\n", "}", "else", "{", "if", "h", ".", "denyHandler", "==", "nil", "{", "status", ":=", "http", ".", "StatusUnauthorized", "\n", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "status", ")", ",", "status", ")", "\n", "}", "else", "{", "h", ".", "denyHandler", ".", "ServeHTTP", "(", "w", ",", "req", ")", "\n", "}", "\n", "}", "\n", "}" ]
// ServeHTTP wraps the request in a whitelist check.
[ "ServeHTTP", "wraps", "the", "request", "in", "a", "whitelist", "check", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/lookup.go#L76-L95
train
cloudflare/cfssl
whitelist/lookup.go
NewHandlerFunc
func NewHandlerFunc(allow, deny func(http.ResponseWriter, *http.Request), acl ACL) (*HandlerFunc, error) { if allow == nil { return nil, errors.New("whitelist: allow cannot be nil") } if acl == nil { return nil, errors.New("whitelist: ACL cannot be nil") } return &HandlerFunc{ allow: allow, deny: deny, whitelist: acl, }, nil }
go
func NewHandlerFunc(allow, deny func(http.ResponseWriter, *http.Request), acl ACL) (*HandlerFunc, error) { if allow == nil { return nil, errors.New("whitelist: allow cannot be nil") } if acl == nil { return nil, errors.New("whitelist: ACL cannot be nil") } return &HandlerFunc{ allow: allow, deny: deny, whitelist: acl, }, nil }
[ "func", "NewHandlerFunc", "(", "allow", ",", "deny", "func", "(", "http", ".", "ResponseWriter", ",", "*", "http", ".", "Request", ")", ",", "acl", "ACL", ")", "(", "*", "HandlerFunc", ",", "error", ")", "{", "if", "allow", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "acl", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "HandlerFunc", "{", "allow", ":", "allow", ",", "deny", ":", "deny", ",", "whitelist", ":", "acl", ",", "}", ",", "nil", "\n", "}" ]
// NewHandlerFunc returns a new basic whitelisting handler.
[ "NewHandlerFunc", "returns", "a", "new", "basic", "whitelisting", "handler", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/lookup.go#L107-L121
train
cloudflare/cfssl
whitelist/lookup.go
ServeHTTP
func (h *HandlerFunc) ServeHTTP(w http.ResponseWriter, req *http.Request) { ip, err := HTTPRequestLookup(req) if err != nil { log.Printf("failed to lookup request address: %v", err) status := http.StatusInternalServerError http.Error(w, http.StatusText(status), status) return } if h.whitelist.Permitted(ip) { h.allow(w, req) } else { if h.deny == nil { status := http.StatusUnauthorized http.Error(w, http.StatusText(status), status) } else { h.deny(w, req) } } }
go
func (h *HandlerFunc) ServeHTTP(w http.ResponseWriter, req *http.Request) { ip, err := HTTPRequestLookup(req) if err != nil { log.Printf("failed to lookup request address: %v", err) status := http.StatusInternalServerError http.Error(w, http.StatusText(status), status) return } if h.whitelist.Permitted(ip) { h.allow(w, req) } else { if h.deny == nil { status := http.StatusUnauthorized http.Error(w, http.StatusText(status), status) } else { h.deny(w, req) } } }
[ "func", "(", "h", "*", "HandlerFunc", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "ip", ",", "err", ":=", "HTTPRequestLookup", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "status", ":=", "http", ".", "StatusInternalServerError", "\n", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "status", ")", ",", "status", ")", "\n", "return", "\n", "}", "\n\n", "if", "h", ".", "whitelist", ".", "Permitted", "(", "ip", ")", "{", "h", ".", "allow", "(", "w", ",", "req", ")", "\n", "}", "else", "{", "if", "h", ".", "deny", "==", "nil", "{", "status", ":=", "http", ".", "StatusUnauthorized", "\n", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "status", ")", ",", "status", ")", "\n", "}", "else", "{", "h", ".", "deny", "(", "w", ",", "req", ")", "\n", "}", "\n", "}", "\n", "}" ]
// ServeHTTP checks the incoming request to see whether it is permitted, // and calls the appropriate handle function.
[ "ServeHTTP", "checks", "the", "incoming", "request", "to", "see", "whether", "it", "is", "permitted", "and", "calls", "the", "appropriate", "handle", "function", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/whitelist/lookup.go#L125-L144
train
cloudflare/cfssl
scan/crypto/tls/common.go
ticketKeyFromBytes
func ticketKeyFromBytes(b [32]byte) (key ticketKey) { hashed := sha512.Sum512(b[:]) copy(key.keyName[:], hashed[:ticketKeyNameLen]) copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16]) copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32]) return key }
go
func ticketKeyFromBytes(b [32]byte) (key ticketKey) { hashed := sha512.Sum512(b[:]) copy(key.keyName[:], hashed[:ticketKeyNameLen]) copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16]) copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32]) return key }
[ "func", "ticketKeyFromBytes", "(", "b", "[", "32", "]", "byte", ")", "(", "key", "ticketKey", ")", "{", "hashed", ":=", "sha512", ".", "Sum512", "(", "b", "[", ":", "]", ")", "\n", "copy", "(", "key", ".", "keyName", "[", ":", "]", ",", "hashed", "[", ":", "ticketKeyNameLen", "]", ")", "\n", "copy", "(", "key", ".", "aesKey", "[", ":", "]", ",", "hashed", "[", "ticketKeyNameLen", ":", "ticketKeyNameLen", "+", "16", "]", ")", "\n", "copy", "(", "key", ".", "hmacKey", "[", ":", "]", ",", "hashed", "[", "ticketKeyNameLen", "+", "16", ":", "ticketKeyNameLen", "+", "32", "]", ")", "\n", "return", "key", "\n", "}" ]
// ticketKeyFromBytes converts from the external representation of a session // ticket key to a ticketKey. Externally, session ticket keys are 32 random // bytes and this function expands that into sufficient name and key material.
[ "ticketKeyFromBytes", "converts", "from", "the", "external", "representation", "of", "a", "session", "ticket", "key", "to", "a", "ticketKey", ".", "Externally", "session", "ticket", "keys", "are", "32", "random", "bytes", "and", "this", "function", "expands", "that", "into", "sufficient", "name", "and", "key", "material", "." ]
768cd563887febaad559b511aaa5964823ccb4ab
https://github.com/cloudflare/cfssl/blob/768cd563887febaad559b511aaa5964823ccb4ab/scan/crypto/tls/common.go#L379-L385
train