Explorar o código

golint issues

Jonathan Turner %!s(int64=9) %!d(string=hai) anos
pai
achega
6652a6db7d

+ 3 - 3
asn1tools/tools.go

@@ -1,11 +1,11 @@
-// Tools for managing ASN1 marshaled data.
+// Package asn1tools - Tools for managing ASN1 marshaled data.
 package asn1tools
 
 import (
 	"github.com/jcmturner/asn1"
 )
 
-// Get the ASN1 encoded bytes for the length 'l'
+// MarshalLengthBytes returns the ASN1 encoded bytes for the length 'l'
 //
 // There are two forms: short (for lengths between 0 and 127), and long definite (for lengths between 0 and 2^1008 -1).
 //
@@ -29,7 +29,7 @@ func MarshalLengthBytes(l int) []byte {
 	return append([]byte{byte(128 + len(b))}, b...)
 }
 
-// Get the length of a slice of ASN1 encoded bytes from the ASN1 length header it contains.
+// GetLengthFromASN returns the length of a slice of ASN1 encoded bytes from the ASN1 length header it contains.
 func GetLengthFromASN(b []byte) int {
 	if int(b[1]) <= 127 {
 		return int(b[1])

+ 1 - 1
client/ASExchange.go

@@ -15,7 +15,7 @@ import (
 // Perform an AS exchange for the client to retrieve a TGT.
 func (cl *Client) ASExchange() error {
 	if !cl.IsConfigured() {
-		return errors.New("Client is not configured correctly.")
+		return errors.New("Client is not configured correctly")
 	}
 	ASReq := messages.NewASReq(cl.Config, cl.Credentials.CName)
 	err := setPAData(cl, &ASReq)

+ 1 - 2
client/client.go

@@ -77,9 +77,8 @@ func (cl *Client) IsConfigured() bool {
 		if r.Realm == cl.Config.LibDefaults.Default_realm {
 			if len(r.Kdc) > 0 {
 				return true
-			} else {
-				return false
 			}
+			return false
 		}
 	}
 	return false

+ 11 - 11
config/krb5conf.go

@@ -366,7 +366,7 @@ func parseRealms(lines []string) ([]Realm, error) {
 		if strings.Contains(l, "{") {
 			if start >= 0 {
 				// already started a block!!!
-				return nil, errors.New("Invalid Realms section in configuration.")
+				return nil, errors.New("Invalid Realms section in configuration")
 			}
 			start = i
 			if !strings.Contains(l, "=") {
@@ -378,7 +378,7 @@ func parseRealms(lines []string) ([]Realm, error) {
 		if strings.Contains(l, "}") {
 			if start < 0 {
 				// but not started a block!!!
-				return nil, errors.New("Invalid Realms section in configuration.")
+				return nil, errors.New("Invalid Realms section in configuration")
 			}
 			var r Realm
 			r.parseLines(name, lines[start+1:i])
@@ -424,7 +424,7 @@ func (d *DomainRealm) deleteMapping(domain, realm string) {
 func (c *Config) ResolveRealm(domainName string) string {
 	domainName = strings.TrimSuffix(domainName, ".")
 	periods := strings.Count(domainName, ".") + 1
-	for i := 1; i <= periods; i += 1 {
+	for i := 1; i <= periods; i++ {
 		z := strings.SplitN(domainName, ".", i)
 		if r, ok := c.DomainRealm[z[len(z)-1]]; ok {
 			return r
@@ -460,7 +460,7 @@ func NewConfigFromReader(r io.Reader) (*Config, error) {
 func NewConfigFromScanner(scanner *bufio.Scanner) (*Config, error) {
 	c := NewConfig()
 	sections := make(map[int]string)
-	var section_line_num []int
+	var sectionLineNum []int
 	var lines []string
 	for scanner.Scan() {
 		// Skip comments and blank lines
@@ -469,32 +469,32 @@ func NewConfigFromScanner(scanner *bufio.Scanner) (*Config, error) {
 		}
 		if matched, _ := regexp.MatchString(`\s*\[libdefaults\]\s*`, scanner.Text()); matched {
 			sections[len(lines)] = "libdefaults"
-			section_line_num = append(section_line_num, len(lines))
+			sectionLineNum = append(sectionLineNum, len(lines))
 			continue
 		}
 		if matched, _ := regexp.MatchString(`\s*\[realms\]\s*`, scanner.Text()); matched {
 			sections[len(lines)] = "realms"
-			section_line_num = append(section_line_num, len(lines))
+			sectionLineNum = append(sectionLineNum, len(lines))
 			continue
 		}
 		if matched, _ := regexp.MatchString(`\s*\[domain_realm\]\s*`, scanner.Text()); matched {
 			sections[len(lines)] = "domain_realm"
-			section_line_num = append(section_line_num, len(lines))
+			sectionLineNum = append(sectionLineNum, len(lines))
 			continue
 		}
 		if matched, _ := regexp.MatchString(`\s*\[.*\]\s*`, scanner.Text()); matched {
 			sections[len(lines)] = "unknown_section"
-			section_line_num = append(section_line_num, len(lines))
+			sectionLineNum = append(sectionLineNum, len(lines))
 			continue
 		}
 		lines = append(lines, scanner.Text())
 	}
-	for i, start := range section_line_num {
+	for i, start := range sectionLineNum {
 		var end int
-		if i+1 >= len(section_line_num) {
+		if i+1 >= len(sectionLineNum) {
 			end = len(lines) - 1
 		} else {
-			end = section_line_num[i+1] - 1
+			end = sectionLineNum[i+1] - 1
 		}
 		switch section := sections[start]; section {
 		case "libdefaults":

+ 1 - 1
crypto/rfc3961/encryption.go

@@ -71,7 +71,7 @@ func DES3DecryptData(key, data []byte, e etype.EType) ([]byte, error) {
 	}
 
 	if len(data) < des.BlockSize || len(data)%des.BlockSize != 0 {
-		return []byte{}, errors.New("Ciphertext is not a multiple of the block size.")
+		return []byte{}, errors.New("Ciphertext is not a multiple of the block size")
 	}
 	block, err := des.NewTripleDESCipher(key)
 	if err != nil {

+ 1 - 1
crypto/rfc3961/keyDerivation.go

@@ -160,7 +160,7 @@ func calcEvenParity(b byte) (uint8, uint8) {
 	for p := 1; p < 8; p++ {
 		v := b & (1 << uint(p))
 		if v != 0 {
-			c += 1
+			c++
 		}
 	}
 	if c%2 == 0 {

+ 2 - 2
examples/example-AD.go

@@ -73,8 +73,8 @@ func httpServer() *httptest.Server {
 func testAppHandler(w http.ResponseWriter, r *http.Request) {
 	ctx := r.Context()
 	fmt.Fprint(w, "<html>\n<p><h1>TEST.GOKRB5 Handler</h1></p>\n")
-	if validuser, ok := ctx.Value("authenticated").(bool); ok && validuser {
-		if creds, ok := ctx.Value("credentials").(credentials.Credentials); ok {
+	if validuser, ok := ctx.Value(service.AUTHENTICATED_CTXKEY).(bool); ok && validuser {
+		if creds, ok := ctx.Value(service.CREDENTIALS_CTXKEY).(credentials.Credentials); ok {
 			fmt.Fprintf(w, "<ul><li>Authenticed user: %s</li>\n", creds.Username)
 			fmt.Fprintf(w, "<li>User's realm: %s</li>\n", creds.Realm)
 			if ADCreds, ok := creds.Attributes["ADCredentials"].(credentials.ADCredentials); ok {

+ 2 - 2
examples/example.go

@@ -86,8 +86,8 @@ func httpServer() *httptest.Server {
 func testAppHandler(w http.ResponseWriter, r *http.Request) {
 	ctx := r.Context()
 	fmt.Fprint(w, "<html>\n<p><h1>TEST.GOKRB5 Handler</h1></p>\n")
-	if validuser, ok := ctx.Value("authenticated").(bool); ok && validuser {
-		if creds, ok := ctx.Value("credentials").(credentials.Credentials); ok {
+	if validuser, ok := ctx.Value(service.AUTHENTICATED_CTXKEY).(bool); ok && validuser {
+		if creds, ok := ctx.Value(service.CREDENTIALS_CTXKEY).(credentials.Credentials); ok {
 			fmt.Fprintf(w, "<ul><li>Authenticed user: %s</li>\n", creds.Username)
 			fmt.Fprintf(w, "<li>User's realm: %s</li></ul>\n", creds.Realm)
 		}

+ 1 - 1
examples/httpServer.go

@@ -37,6 +37,6 @@ func main() {
 func testAppHandler(w http.ResponseWriter, r *http.Request) {
 	w.WriteHeader(http.StatusOK)
 	ctx := r.Context()
-	fmt.Fprintf(w, "<html>\nTEST.GOKRB5 Handler\nAuthenticed user: %s\nUser's realm: %s\n</html>", ctx.Value("credentials").(credentials.Credentials).Username, ctx.Value("credentials").(credentials.Credentials).Realm)
+	fmt.Fprintf(w, "<html>\nTEST.GOKRB5 Handler\nAuthenticed user: %s\nUser's realm: %s\n</html>", ctx.Value(service.CREDENTIALS_CTXKEY).(credentials.Credentials).Username, ctx.Value(service.CREDENTIALS_CTXKEY).(credentials.Credentials).Realm)
 	return
 }

+ 2 - 2
gssapi/krb5Token_test.go

@@ -46,8 +46,8 @@ func TestMechToken_newAuthenticatorChksum(t *testing.T) {
 func TestMechToken_newAuthenticator(t *testing.T) {
 	creds := credentials.NewCredentials("hftsai", testdata.TEST_REALM)
 	creds.CName.NameString = testdata.TEST_PRINCIPALNAME_NAMESTRING
-	etypeId := 18
-	a := newAuthenticator(creds, etypeId)
+	etypeID := 18
+	a := newAuthenticator(creds, etypeID)
 	assert.Equal(t, 32771, a.Cksum.CksumType, "Checksum type in authenticator for SPNEGO mechtoken not as expected.")
 	assert.Equal(t, 18, a.SubKey.KeyType, "Subkey not of the expected type.")
 	assert.Equal(t, 32, len(a.SubKey.KeyValue), "Subkey value not of the right length")

+ 1 - 1
iana/errorcode/constants.go

@@ -74,7 +74,7 @@ const (
 	KDC_ERR_KDC_NAME_MISMATCH             = 76 //Reserved for PKINIT
 )
 
-func ErrorCodeLookup(i int) string {
+func Lookup(i int) string {
 	if s, ok := errorcodeLookup[i]; ok {
 		return fmt.Sprintf("(%d) %s", i, s)
 	}

+ 11 - 11
keytab/keytab.go

@@ -15,11 +15,11 @@ import (
 // Keytab struct.
 type Keytab struct {
 	Version uint16
-	Entries []KeytabEntry
+	Entries []Entry
 }
 
 // Keytab entry struct.
-type KeytabEntry struct {
+type Entry struct {
 	Principal Principal
 	Timestamp time.Time
 	KVNO8     uint8
@@ -37,7 +37,7 @@ type Principal struct {
 
 //Create new, empty Keytab type.
 func NewKeytab() Keytab {
-	var e []KeytabEntry
+	var e []Entry
 	return Keytab{
 		Version: 0,
 		Entries: e,
@@ -69,9 +69,9 @@ func (kt *Keytab) GetEncryptionKey(nameString []string, realm string, kvno, etyp
 }
 
 // Create a new Keytab entry.
-func newKeytabEntry() KeytabEntry {
+func newKeytabEntry() Entry {
 	var b []byte
-	return KeytabEntry{
+	return Entry{
 		Principal: newPrincipal(),
 		Timestamp: time.Time{},
 		KVNO8:     0,
@@ -176,11 +176,11 @@ func Parse(b []byte) (kt Keytab, err error) {
 }
 
 // Parse the Keytab bytes of a principal into a Keytab entry's principal.
-func parse_principal(b []byte, p *int, kt *Keytab, ke *KeytabEntry, e *binary.ByteOrder) (err error) {
+func parse_principal(b []byte, p *int, kt *Keytab, ke *Entry, e *binary.ByteOrder) (err error) {
 	ke.Principal.NumComponents = read_int16(b, p, e)
 	if kt.Version == 1 {
 		//In version 1 the number of components includes the realm. Minus 1 to make consistent with version 2
-		ke.Principal.NumComponents -= 1
+		ke.Principal.NumComponents--
 	}
 	len_realm := read_int16(b, p, e)
 	ke.Principal.Realm = string(read_Bytes(b, p, int(len_realm), e))
@@ -204,7 +204,7 @@ func read_timestamp(b []byte, p *int, e *binary.ByteOrder) time.Time {
 func read_int8(b []byte, p *int, e *binary.ByteOrder) (i int8) {
 	buf := bytes.NewBuffer(b[*p : *p+1])
 	binary.Read(buf, *e, &i)
-	*p += 1
+	*p++
 	return
 }
 
@@ -233,9 +233,9 @@ func read_Bytes(b []byte, p *int, s int, e *binary.ByteOrder) []byte {
 }
 
 func isNativeEndianLittle() bool {
-	var x int = 0x012345678
-	var p unsafe.Pointer = unsafe.Pointer(&x)
-	var bp *[4]byte = (*[4]byte)(p)
+	var x = 0x012345678
+	var p = unsafe.Pointer(&x)
+	var bp = (*[4]byte)(p)
 
 	var endian bool
 	if 0x01 == bp[0] {

+ 10 - 11
krberror/error.go

@@ -16,37 +16,36 @@ const (
 	KRBMSG_ERROR     = "KRBMessage_Handling_Error"
 )
 
-type krberror struct {
+type Krberror struct {
 	RootCause string
 	EText     []string
 }
 
-func (e krberror) Error() string {
+func (e Krberror) Error() string {
 	return fmt.Sprintf("[Root cause: %s] ", e.RootCause) + strings.Join(e.EText, SEPARATOR)
 }
 
-func (e *krberror) Add2(et string, s string) {
+func (e *Krberror) Add2(et string, s string) {
 	e.EText = append([]string{fmt.Sprintf("%s: %s", et, s)}, e.EText...)
 }
 
-func NewKrberror(et, s string) krberror {
-	return krberror{
+func NewKrberror(et, s string) Krberror {
+	return Krberror{
 		RootCause: et,
 		EText:     []string{s},
 	}
 }
 
-func Errorf(err error, et, format string, a ...interface{}) krberror {
-	if e, ok := err.(krberror); ok {
+func Errorf(err error, et, format string, a ...interface{}) Krberror {
+	if e, ok := err.(Krberror); ok {
 		e.EText = append([]string{fmt.Sprintf("%s: "+format, et, a)}, e.EText...)
 		return e
-	} else {
-		return NewErrorf(et, format+": %v", a, err)
 	}
+	return NewErrorf(et, format+": %v", a, err)
 }
 
-func NewErrorf(et, format string, a ...interface{}) krberror {
-	return krberror{
+func NewErrorf(et, format string, a ...interface{}) Krberror {
+	return Krberror{
 		RootCause: et,
 		EText:     []string{fmt.Sprintf("%s: %s", et, fmt.Sprintf(format, a))},
 	}

+ 1 - 1
messages/KRBError.go

@@ -59,7 +59,7 @@ func (k *KRBError) Unmarshal(b []byte) error {
 
 // Error method implementing error interface on KRBError struct.
 func (k KRBError) Error() string {
-	etxt := fmt.Sprintf("KRB Error: %s", errorcode.ErrorCodeLookup(k.ErrorCode))
+	etxt := fmt.Sprintf("KRB Error: %s", errorcode.Lookup(k.ErrorCode))
 	if k.EText != "" {
 		etxt = fmt.Sprintf("%s - %s", etxt, k.EText)
 	}

+ 1 - 1
mstypes/rpc_unicode_string.go

@@ -17,7 +17,7 @@ func Read_RPC_UnicodeString(b *[]byte, p *int, e *binary.ByteOrder) (RPC_Unicode
 	l := ndr.Read_uint16(b, p, e)
 	ml := ndr.Read_uint16(b, p, e)
 	if ml < l || l%2 != 0 || ml%2 != 0 {
-		return RPC_UnicodeString{}, ndr.NDRMalformed{EText: "Invalid data for RPC_UNICODE_STRING"}
+		return RPC_UnicodeString{}, ndr.Malformed{EText: "Invalid data for RPC_UNICODE_STRING"}
 	}
 	ptr := ndr.Read_uint32(b, p, e)
 	return RPC_UnicodeString{

+ 2 - 2
mstypes/sid.go

@@ -24,13 +24,13 @@ func Read_RPC_SID(b *[]byte, p *int, e *binary.ByteOrder) (RPC_SID, error) {
 	size := int(ndr.Read_uint32(b, p, e)) // This is part of the NDR encoding rather than the data type.
 	r := ndr.Read_uint8(b, p)
 	if r != uint8(1) {
-		return RPC_SID{}, ndr.NDRMalformed{EText: fmt.Sprintf("SID revision value read as %d when it must be 1", r)}
+		return RPC_SID{}, ndr.Malformed{EText: fmt.Sprintf("SID revision value read as %d when it must be 1", r)}
 	}
 	c := ndr.Read_uint8(b, p)
 	a := Read_RPC_SIDIdentifierAuthority(b, p, e)
 	s := make([]uint32, c, c)
 	if size != len(s) {
-		return RPC_SID{}, ndr.NDRMalformed{EText: fmt.Sprintf("Number of elements (%d) within SID in the byte stream does not equal the SubAuthorityCount (%d)", size, c)}
+		return RPC_SID{}, ndr.Malformed{EText: fmt.Sprintf("Number of elements (%d) within SID in the byte stream does not equal the SubAuthorityCount (%d)", size, c)}
 	}
 	for i := 0; i < len(s); i++ {
 		s[i] = ndr.Read_uint32(b, p, e)

+ 2 - 2
ndr/error.go

@@ -2,10 +2,10 @@ package ndr
 
 import "fmt"
 
-type NDRMalformed struct {
+type Malformed struct {
 	EText string
 }
 
-func (e NDRMalformed) Error() string {
+func (e Malformed) Error() string {
 	return fmt.Sprintf("Malformed NDR steam: %s", e.EText)
 }

+ 9 - 9
ndr/ndr.go

@@ -69,18 +69,18 @@ func ReadHeaders(b *[]byte) (CommonHeader, PrivateHeader, int, error) {
 func GetCommonHeader(b *[]byte) (CommonHeader, int, error) {
 	//The first 8 bytes comprise the Common RPC Header for type marshalling.
 	if len(*b) < COMMON_HEADER_BYTES {
-		return CommonHeader{}, 0, NDRMalformed{EText: "Not enough bytes."}
+		return CommonHeader{}, 0, Malformed{EText: "Not enough bytes."}
 	}
 	if (*b)[0] != PROTOCOL_VERSION {
-		return CommonHeader{}, 0, NDRMalformed{EText: fmt.Sprintf("Stream does not indicate a RPC Type serialization of version %v", PROTOCOL_VERSION)}
+		return CommonHeader{}, 0, Malformed{EText: fmt.Sprintf("Stream does not indicate a RPC Type serialization of version %v", PROTOCOL_VERSION)}
 	}
 	endian := int((*b)[1] >> 4 & 0xF)
 	if endian != 0 && endian != 1 {
-		return CommonHeader{}, 1, NDRMalformed{EText: "Common header does not indicate a valid endianness"}
+		return CommonHeader{}, 1, Malformed{EText: "Common header does not indicate a valid endianness"}
 	}
 	charEncoding := uint8((*b)[1] & 0xF)
 	if charEncoding != 0 && charEncoding != 1 {
-		return CommonHeader{}, 1, NDRMalformed{EText: "Common header does not indicate a valid charater encoding"}
+		return CommonHeader{}, 1, Malformed{EText: "Common header does not indicate a valid charater encoding"}
 	}
 	var bo binary.ByteOrder
 	switch endian {
@@ -91,7 +91,7 @@ func GetCommonHeader(b *[]byte) (CommonHeader, int, error) {
 	}
 	l := bo.Uint16((*b)[2:4])
 	if l != COMMON_HEADER_BYTES {
-		return CommonHeader{}, 4, NDRMalformed{EText: fmt.Sprintf("Common header does not indicate a valid length: %v instead of %v", uint8((*b)[3]), COMMON_HEADER_BYTES)}
+		return CommonHeader{}, 4, Malformed{EText: fmt.Sprintf("Common header does not indicate a valid length: %v instead of %v", uint8((*b)[3]), COMMON_HEADER_BYTES)}
 	}
 
 	return CommonHeader{
@@ -107,13 +107,13 @@ func GetCommonHeader(b *[]byte) (CommonHeader, int, error) {
 func GetPrivateHeader(b *[]byte, p *int, bo *binary.ByteOrder) (PrivateHeader, error) {
 	//The next 8 bytes comprise the RPC type marshalling private header for constructed types.
 	if len(*b) < (PRIVATE_HEADER_BYTES) {
-		return PrivateHeader{}, NDRMalformed{EText: "Not enough bytes."}
+		return PrivateHeader{}, Malformed{EText: "Not enough bytes."}
 	}
 	var l uint32
 	buf := bytes.NewBuffer((*b)[*p : *p+4])
 	binary.Read(buf, *bo, &l)
 	if l%8 != 0 {
-		return PrivateHeader{}, NDRMalformed{EText: "Object buffer length not a multiple of 8"}
+		return PrivateHeader{}, Malformed{EText: "Object buffer length not a multiple of 8"}
 	}
 	*p += 8
 	return PrivateHeader{
@@ -129,7 +129,7 @@ func Read_uint8(b *[]byte, p *int) (i uint8) {
 	}
 	ensureAlignment(p, 1)
 	i = uint8((*b)[*p])
-	*p += 1
+	*p++
 	return
 }
 
@@ -208,7 +208,7 @@ func Read_ConformantVaryingString(b *[]byte, p *int, e *binary.ByteOrder) (strin
 	o := Read_uint32(b, p, e) // Offset
 	a := Read_uint32(b, p, e) // Actual count
 	if a > (m-o) || o > m {
-		return "", NDRMalformed{EText: fmt.Sprintf("Not enough bytes. Max: %d, Offset: %d, Actual: %d", m, o, a)}
+		return "", Malformed{EText: fmt.Sprintf("Not enough bytes. Max: %d, Offset: %d, Actual: %d", m, o, a)}
 	}
 	//Unicode string so each element is 2 bytes
 	//move position based on the offset

+ 3 - 3
pac/client_claims.go

@@ -7,11 +7,11 @@ import (
 )
 
 // https://msdn.microsoft.com/en-us/library/hh536365.aspx
-type PAC_ClientClaimsInfo struct {
+type ClientClaimsInfo struct {
 	Claims mstypes.ClaimsSetMetadata
 }
 
-func (k *PAC_ClientClaimsInfo) Unmarshal(b []byte) error {
+func (k *ClientClaimsInfo) Unmarshal(b []byte) error {
 	ch, _, p, err := ndr.ReadHeaders(&b)
 	if err != nil {
 		return fmt.Errorf("Error parsing byte stream headers: %v", err)
@@ -27,7 +27,7 @@ func (k *PAC_ClientClaimsInfo) Unmarshal(b []byte) error {
 	if len(b) >= p {
 		for _, v := range b[p:] {
 			if v != 0 {
-				return ndr.NDRMalformed{EText: "Non-zero padding left over at end of data stream"}
+				return ndr.Malformed{EText: "Non-zero padding left over at end of data stream"}
 			}
 		}
 	}

+ 4 - 4
pac/client_info.go

@@ -7,13 +7,13 @@ import (
 )
 
 // https://msdn.microsoft.com/en-us/library/cc237951.aspx
-type PAC_ClientInfo struct {
+type ClientInfo struct {
 	ClientID   mstypes.FileTime // A FILETIME structure in little-endian format that contains the Kerberos initial ticket-granting ticket TGT authentication time
 	NameLength uint16           // An unsigned 16-bit integer in little-endian format that specifies the length, in bytes, of the Name field.
 	Name       string           // An array of 16-bit Unicode characters in little-endian format that contains the client's account name.
 }
 
-func (k *PAC_ClientInfo) Unmarshal(b []byte) error {
+func (k *ClientInfo) Unmarshal(b []byte) error {
 	//The PAC_CLIENT_INFO structure is a simple structure that is not NDR-encoded.
 	var p int
 	var e binary.ByteOrder = binary.LittleEndian
@@ -21,7 +21,7 @@ func (k *PAC_ClientInfo) Unmarshal(b []byte) error {
 	k.ClientID = mstypes.Read_FileTime(&b, &p, &e)
 	k.NameLength = ndr.Read_uint16(&b, &p, &e)
 	if len(b[p:]) < int(k.NameLength) {
-		return ndr.NDRMalformed{EText: "PAC ClientInfo length truncated"}
+		return ndr.Malformed{EText: "PAC ClientInfo length truncated"}
 	}
 	//Length devided by 2 as each run is 16bits = 2bytes
 	s := make([]rune, k.NameLength/2, k.NameLength/2)
@@ -34,7 +34,7 @@ func (k *PAC_ClientInfo) Unmarshal(b []byte) error {
 	if len(b) >= p {
 		for _, v := range b[p:] {
 			if v != 0 {
-				return ndr.NDRMalformed{EText: "Non-zero padding left over at end of data stream"}
+				return ndr.Malformed{EText: "Non-zero padding left over at end of data stream"}
 			}
 		}
 	}

+ 1 - 1
pac/client_info_test.go

@@ -13,7 +13,7 @@ func TestPAC_ClientInfo_Unmarshal(t *testing.T) {
 	if err != nil {
 		t.Fatal("Could not decode test data hex string")
 	}
-	var k PAC_ClientInfo
+	var k ClientInfo
 	err = k.Unmarshal(b)
 	if err != nil {
 		t.Fatalf("Error unmarshaling test data: %v", err)

+ 7 - 7
pac/credentials_info.go

@@ -13,14 +13,14 @@ import (
 // https://msdn.microsoft.com/en-us/library/cc237931.aspx
 
 // https://msdn.microsoft.com/en-us/library/cc237953.aspx
-type PAC_CredentialsInfo struct {
+type CredentialsInfo struct {
 	Version                      uint32 // A 32-bit unsigned integer in little-endian format that defines the version. MUST be 0x00000000.
 	EType                        uint32
 	PAC_CredentialData_Encrypted []byte // Key usage number for encryption: KERB_NON_KERB_SALT (16)
-	PAC_CredentialData           PAC_CredentialData
+	PAC_CredentialData           CredentialData
 }
 
-func (c *PAC_CredentialsInfo) Unmarshal(b []byte, k types.EncryptionKey) error {
+func (c *CredentialsInfo) Unmarshal(b []byte, k types.EncryptionKey) error {
 	ch, _, p, err := ndr.ReadHeaders(&b)
 	if err != nil {
 		return fmt.Errorf("Error parsing byte stream headers: %v", err)
@@ -41,7 +41,7 @@ func (c *PAC_CredentialsInfo) Unmarshal(b []byte, k types.EncryptionKey) error {
 	return nil
 }
 
-func (c *PAC_CredentialsInfo) DecryptEncPart(k types.EncryptionKey, e *binary.ByteOrder) error {
+func (c *CredentialsInfo) DecryptEncPart(k types.EncryptionKey, e *binary.ByteOrder) error {
 	if k.KeyType != int(c.EType) {
 		return fmt.Errorf("Key provided is not the correct type. Type needed: %d, type provided: %d", c.EType, k.KeyType)
 	}
@@ -59,18 +59,18 @@ func (c *PAC_CredentialsInfo) DecryptEncPart(k types.EncryptionKey, e *binary.By
 // Encryption is performed by first serializing the data structure via Network Data Representation (NDR) encoding, as specified in [MS-RPCE].
 // Once serialized, the data is encrypted using the key and cryptographic system selected through the AS protocol and the KRB_AS_REP message
 // Fields (for capturing this information) and cryptographic parameters are specified in PAC_CREDENTIAL_INFO (section 2.6.1).
-type PAC_CredentialData struct {
+type CredentialData struct {
 	CredentialCount uint32
 	Credentials     []SECPKG_SupplementalCred // Size is the value of CredentialCount
 }
 
-func Read_PAC_CredentialData(b *[]byte, p *int, e *binary.ByteOrder) PAC_CredentialData {
+func Read_PAC_CredentialData(b *[]byte, p *int, e *binary.ByteOrder) CredentialData {
 	c := ndr.Read_uint32(b, p, e)
 	cr := make([]SECPKG_SupplementalCred, c, c)
 	for i := range cr {
 		cr[i] = Read_SECPKG_SupplementalCred(b, p, e)
 	}
-	return PAC_CredentialData{
+	return CredentialData{
 		CredentialCount: c,
 		Credentials:     cr,
 	}

+ 3 - 3
pac/device_claims.go

@@ -7,11 +7,11 @@ import (
 )
 
 // https://msdn.microsoft.com/en-us/library/hh554226.aspx
-type PAC_DeviceClaimsInfo struct {
+type DeviceClaimsInfo struct {
 	Claims mstypes.ClaimsSetMetadata
 }
 
-func (k *PAC_DeviceClaimsInfo) Unmarshal(b []byte) error {
+func (k *DeviceClaimsInfo) Unmarshal(b []byte) error {
 	ch, _, p, err := ndr.ReadHeaders(&b)
 	if err != nil {
 		return fmt.Errorf("Error parsing byte stream headers: %v", err)
@@ -27,7 +27,7 @@ func (k *PAC_DeviceClaimsInfo) Unmarshal(b []byte) error {
 	if len(b) >= p {
 		for _, v := range b[p:] {
 			if v != 0 {
-				return ndr.NDRMalformed{EText: "Non-zero padding left over at end of data stream"}
+				return ndr.Malformed{EText: "Non-zero padding left over at end of data stream"}
 			}
 		}
 	}

+ 4 - 4
pac/device_info.go

@@ -7,7 +7,7 @@ import (
 )
 
 // https://msdn.microsoft.com/en-us/library/hh536402.aspx
-type PAC_DeviceInfo struct {
+type DeviceInfo struct {
 	UserID            uint32                          // A 32-bit unsigned integer that contains the RID of the account. If the UserId member equals 0x00000000, the first group SID in this member is the SID for this account.
 	PrimaryGroupID    uint32                          // A 32-bit unsigned integer that contains the RID for the primary group to which this account belongs.
 	AccountDomainID   mstypes.RPC_SID                 // A SID structure that contains the SID for the domain of the account.This member is used in conjunction with the UserId, and GroupIds members to create the user and group SIDs for the client.
@@ -19,7 +19,7 @@ type PAC_DeviceInfo struct {
 	DomainGroup       []mstypes.DomainGroupMembership // A pointer to a list of DOMAIN_GROUP_MEMBERSHIP structures (section 2.2.3) that contains the domains to which the account belongs to a group. The number of sets in this list MUST be equal to DomainCount.
 }
 
-func (k *PAC_DeviceInfo) Unmarshal(b []byte) error {
+func (k *DeviceInfo) Unmarshal(b []byte) error {
 	ch, _, p, err := ndr.ReadHeaders(&b)
 	if err != nil {
 		return fmt.Errorf("Error parsing byte stream headers: %v", err)
@@ -62,7 +62,7 @@ func (k *PAC_DeviceInfo) Unmarshal(b []byte) error {
 				s, err := mstypes.Read_RPC_SID(&b, &p, e)
 				es[i] = mstypes.KerbSidAndAttributes{SID: s, Attributes: attr[i]}
 				if err != nil {
-					return ndr.NDRMalformed{EText: fmt.Sprintf("Could not read ExtraSIDs: %v", err)}
+					return ndr.Malformed{EText: fmt.Sprintf("Could not read ExtraSIDs: %v", err)}
 				}
 			}
 		}
@@ -82,7 +82,7 @@ func (k *PAC_DeviceInfo) Unmarshal(b []byte) error {
 	if len(b) >= p {
 		for _, v := range b[p:] {
 			if v != 0 {
-				return ndr.NDRMalformed{EText: "Non-zero padding left over at end of data stream"}
+				return ndr.Malformed{EText: "Non-zero padding left over at end of data stream"}
 			}
 		}
 	}

+ 2 - 2
pac/kerb_validation_info.go

@@ -183,7 +183,7 @@ func (k *KerbValidationInfo) Unmarshal(b []byte) (err error) {
 				s, err := mstypes.Read_RPC_SID(&b, &p, e)
 				es[i] = mstypes.KerbSidAndAttributes{SID: s, Attributes: attr[i]}
 				if err != nil {
-					return ndr.NDRMalformed{EText: fmt.Sprintf("Could not read ExtraSIDs: %v", err)}
+					return ndr.Malformed{EText: fmt.Sprintf("Could not read ExtraSIDs: %v", err)}
 				}
 			}
 		}
@@ -213,7 +213,7 @@ func (k *KerbValidationInfo) Unmarshal(b []byte) (err error) {
 	if len(b) >= p {
 		for _, v := range b[p:] {
 			if v != 0 {
-				return ndr.NDRMalformed{EText: "Non-zero padding left over at end of data stream"}
+				return ndr.Malformed{EText: "Non-zero padding left over at end of data stream"}
 			}
 		}
 	}

+ 3 - 3
pac/pac_info_buffer.go

@@ -19,17 +19,17 @@ const (
 )
 
 // https://msdn.microsoft.com/en-us/library/cc237954.aspx
-type PACInfoBuffer struct {
+type InfoBuffer struct {
 	ULType       uint32 // A 32-bit unsigned integer in little-endian format that describes the type of data present in the buffer contained at Offset.
 	CBBufferSize uint32 // A 32-bit unsigned integer in little-endian format that contains the size, in bytes, of the buffer in the PAC located at Offset.
 	Offset       uint64 // A 64-bit unsigned integer in little-endian format that contains the offset to the beginning of the buffer, in bytes, from the beginning of the PACTYPE structure. The data offset MUST be a multiple of eight. The following sections specify the format of each type of element.
 }
 
-func Read_PACInfoBuffer(b *[]byte, p *int, e *binary.ByteOrder) PACInfoBuffer {
+func Read_PACInfoBuffer(b *[]byte, p *int, e *binary.ByteOrder) InfoBuffer {
 	u := ndr.Read_uint32(b, p, e)
 	s := ndr.Read_uint32(b, p, e)
 	o := ndr.Read_uint64(b, p, e)
-	return PACInfoBuffer{
+	return InfoBuffer{
 		ULType:       u,
 		CBBufferSize: s,
 		Offset:       o,

+ 16 - 16
pac/pac_type.go

@@ -14,18 +14,18 @@ import (
 type PACType struct {
 	CBuffers           uint32
 	Version            uint32
-	Buffers            []PACInfoBuffer
+	Buffers            []InfoBuffer
 	Data               []byte
 	KerbValidationInfo *KerbValidationInfo
-	CredentialsInfo    *PAC_CredentialsInfo
-	ServerChecksum     *PAC_SignatureData
-	KDCChecksum        *PAC_SignatureData
-	ClientInfo         *PAC_ClientInfo
+	CredentialsInfo    *CredentialsInfo
+	ServerChecksum     *SignatureData
+	KDCChecksum        *SignatureData
+	ClientInfo         *ClientInfo
 	S4U_DelegationInfo *S4U_DelegationInfo
 	UPN_DNSInfo        *UPN_DNSInfo
-	ClientClaimsInfo   *PAC_ClientClaimsInfo
-	DeviceInfo         *PAC_DeviceInfo
-	DeviceClaimsInfo   *PAC_DeviceClaimsInfo
+	ClientClaimsInfo   *ClientClaimsInfo
+	DeviceInfo         *DeviceInfo
+	DeviceClaimsInfo   *DeviceClaimsInfo
 	ZeroSigData        []byte
 }
 
@@ -38,7 +38,7 @@ func (pac *PACType) Unmarshal(b []byte) error {
 	pac.ZeroSigData = zb
 	pac.CBuffers = ndr.Read_uint32(&b, &p, &e)
 	pac.Version = ndr.Read_uint32(&b, &p, &e)
-	buf := make([]PACInfoBuffer, pac.CBuffers, pac.CBuffers)
+	buf := make([]InfoBuffer, pac.CBuffers, pac.CBuffers)
 	for i := range buf {
 		buf[i] = Read_PACInfoBuffer(&b, &p, &e)
 	}
@@ -68,7 +68,7 @@ func (pac *PACType) ProcessPACInfoBuffers(key types.EncryptionKey) error {
 				//Must ignore subsequent buffers of this type
 				continue
 			}
-			var k PAC_CredentialsInfo
+			var k CredentialsInfo
 			err := k.Unmarshal(p, key)
 			if err != nil {
 				return fmt.Errorf("Error processing CredentialsInfo: %v", err)
@@ -79,7 +79,7 @@ func (pac *PACType) ProcessPACInfoBuffers(key types.EncryptionKey) error {
 				//Must ignore subsequent buffers of this type
 				continue
 			}
-			var k PAC_SignatureData
+			var k SignatureData
 			zb, err := k.Unmarshal(p)
 			copy(pac.ZeroSigData[int(buf.Offset):int(buf.Offset)+int(buf.CBBufferSize)], zb)
 			if err != nil {
@@ -91,7 +91,7 @@ func (pac *PACType) ProcessPACInfoBuffers(key types.EncryptionKey) error {
 				//Must ignore subsequent buffers of this type
 				continue
 			}
-			var k PAC_SignatureData
+			var k SignatureData
 			zb, err := k.Unmarshal(p)
 			copy(pac.ZeroSigData[int(buf.Offset):int(buf.Offset)+int(buf.CBBufferSize)], zb)
 			if err != nil {
@@ -103,7 +103,7 @@ func (pac *PACType) ProcessPACInfoBuffers(key types.EncryptionKey) error {
 				//Must ignore subsequent buffers of this type
 				continue
 			}
-			var k PAC_ClientInfo
+			var k ClientInfo
 			err := k.Unmarshal(p)
 			if err != nil {
 				return fmt.Errorf("Error processing ClientInfo: %v", err)
@@ -136,7 +136,7 @@ func (pac *PACType) ProcessPACInfoBuffers(key types.EncryptionKey) error {
 				//Must ignore subsequent buffers of this type
 				continue
 			}
-			var k PAC_ClientClaimsInfo
+			var k ClientClaimsInfo
 			err := k.Unmarshal(p)
 			if err != nil {
 				return fmt.Errorf("Error processing ClientClaimsInfo: %v", err)
@@ -147,7 +147,7 @@ func (pac *PACType) ProcessPACInfoBuffers(key types.EncryptionKey) error {
 				//Must ignore subsequent buffers of this type
 				continue
 			}
-			var k PAC_DeviceInfo
+			var k DeviceInfo
 			err := k.Unmarshal(p)
 			if err != nil {
 				return fmt.Errorf("Error processing DeviceInfo: %v", err)
@@ -158,7 +158,7 @@ func (pac *PACType) ProcessPACInfoBuffers(key types.EncryptionKey) error {
 				//Must ignore subsequent buffers of this type
 				continue
 			}
-			var k PAC_DeviceClaimsInfo
+			var k DeviceClaimsInfo
 			err := k.Unmarshal(p)
 			if err != nil {
 				return fmt.Errorf("Error processing DeviceClaimsInfo: %v", err)

+ 1 - 1
pac/s4u_delegation_info.go

@@ -42,7 +42,7 @@ func (k *S4U_DelegationInfo) Unmarshal(b []byte) error {
 	//Check that there is only zero padding left
 	for _, v := range b[p:] {
 		if v != 0 {
-			return ndr.NDRMalformed{EText: "Non-zero padding left over at end of data stream"}
+			return ndr.Malformed{EText: "Non-zero padding left over at end of data stream"}
 		}
 	}
 

+ 3 - 3
pac/signature_data.go

@@ -30,13 +30,13 @@ The cryptographic system that is used to calculate the checksum depends on which
 - Does not support RC4-HMAC, AES128-CTS-HMAC-SHA1-96 or AES256-CTS-HMAC-SHA1-96 -->  None. The checksum operation will fail.
 */
 
-type PAC_SignatureData struct {
+type SignatureData struct {
 	SignatureType  uint32 // A 32-bit unsigned integer value in little-endian format that defines the cryptographic system used to calculate the checksum. This MUST be one of the following checksum types: KERB_CHECKSUM_HMAC_MD5 (signature size = 16), HMAC_SHA1_96_AES128 (signature size = 12), HMAC_SHA1_96_AES256 (signature size = 12).
 	Signature      []byte // Size depends on the type. See comment above.
 	RODCIdentifier uint16 // A 16-bit unsigned integer value in little-endian format that contains the first 16 bits of the key version number ([MS-KILE] section 3.1.5.8) when the KDC is an RODC. When the KDC is not an RODC, this field does not exist.
 }
 
-func (k *PAC_SignatureData) Unmarshal(b []byte) ([]byte, error) {
+func (k *SignatureData) Unmarshal(b []byte) ([]byte, error) {
 	var p int
 	var e binary.ByteOrder = binary.LittleEndian
 
@@ -57,7 +57,7 @@ func (k *PAC_SignatureData) Unmarshal(b []byte) ([]byte, error) {
 	//Check that there is only zero padding left
 	for _, v := range b[p:] {
 		if v != 0 {
-			return []byte{}, ndr.NDRMalformed{EText: "Non-zero padding left over at end of data stream"}
+			return []byte{}, ndr.Malformed{EText: "Non-zero padding left over at end of data stream"}
 		}
 	}
 

+ 2 - 2
pac/signature_data_test.go

@@ -13,7 +13,7 @@ func TestPAC_SignatureData_Unmarshal_Server_Signature(t *testing.T) {
 	if err != nil {
 		t.Fatal("Could not decode test data hex string")
 	}
-	var k PAC_SignatureData
+	var k SignatureData
 	bz, err := k.Unmarshal(b)
 	if err != nil {
 		t.Fatalf("Error unmarshaling test data: %v", err)
@@ -31,7 +31,7 @@ func TestPAC_SignatureData_Unmarshal_KDC_Signature(t *testing.T) {
 	if err != nil {
 		t.Fatal("Could not decode test data hex string")
 	}
-	var k PAC_SignatureData
+	var k SignatureData
 	bz, err := k.Unmarshal(b)
 	if err != nil {
 		t.Fatalf("Error unmarshaling test data: %v", err)

+ 1 - 1
pac/upn_dns_info.go

@@ -56,7 +56,7 @@ func (k *UPN_DNSInfo) Unmarshal(b []byte) error {
 	//Check that there is only zero padding left
 	for _, v := range b[l[2]:] {
 		if v != 0 {
-			return ndr.NDRMalformed{EText: "Non-zero padding left over at end of data stream."}
+			return ndr.Malformed{EText: "Non-zero padding left over at end of data stream."}
 		}
 	}
 

+ 7 - 7
service/cache.go

@@ -30,7 +30,7 @@ them following an event that caused the server to lose track of
 recently seen authenticators.*/
 
 // Cache for tickets received from clients keyed by fully qualified client name. Used to track replay of tickets.
-type ServiceCache map[string]clientEntries
+type Cache map[string]clientEntries
 
 // Entries for client details sent to the service.
 type clientEntries struct {
@@ -47,14 +47,14 @@ type replayCacheEntry struct {
 }
 
 // Instance of the ServiceCache. This needs to be a singleton.
-var replayCache ServiceCache
+var replayCache Cache
 var once sync.Once
 
 // Get a pointer to the ServiceCache singleton.
-func GetReplayCache(d time.Duration) *ServiceCache {
+func GetReplayCache(d time.Duration) *Cache {
 	// Create a singleton of the ReplayCache and start a background thread to regularly clean out old entries
 	once.Do(func() {
-		replayCache = make(ServiceCache)
+		replayCache = make(Cache)
 		go func() {
 			for {
 				// TODO consider using a context here.
@@ -67,7 +67,7 @@ func GetReplayCache(d time.Duration) *ServiceCache {
 }
 
 // Add an entry to the ServiceCache.
-func (c *ServiceCache) AddEntry(sname types.PrincipalName, a types.Authenticator) {
+func (c *Cache) AddEntry(sname types.PrincipalName, a types.Authenticator) {
 	ct := a.CTime.Add(time.Duration(a.Cusec) * time.Microsecond)
 	if ce, ok := (*c)[a.CName.GetPrincipalNameString()]; ok {
 		ce.ReplayMap[ct] = replayCacheEntry{
@@ -93,7 +93,7 @@ func (c *ServiceCache) AddEntry(sname types.PrincipalName, a types.Authenticator
 }
 
 // Clear entries from the ServiceCache that are older than the duration provided.
-func (c *ServiceCache) ClearOldEntries(d time.Duration) {
+func (c *Cache) ClearOldEntries(d time.Duration) {
 	for ck := range *c {
 		for ct, e := range (*c)[ck].ReplayMap {
 			if time.Now().UTC().Sub(e.PresentedTime) > d {
@@ -107,7 +107,7 @@ func (c *ServiceCache) ClearOldEntries(d time.Duration) {
 }
 
 // Check if the Authenticator provided is a replay within the duration defined. If this is not a replay add the entry to the cache for tracking.
-func (c *ServiceCache) IsReplay(sname types.PrincipalName, a types.Authenticator) bool {
+func (c *Cache) IsReplay(sname types.PrincipalName, a types.Authenticator) bool {
 	if ck, ok := (*c)[a.CName.GetPrincipalNameString()]; ok {
 		ct := a.CTime.Add(time.Duration(a.Cusec) * time.Microsecond)
 		if e, ok := ck.ReplayMap[ct]; ok {

+ 7 - 3
service/http.go

@@ -11,11 +11,15 @@ import (
 	"strings"
 )
 
+type ctxKey int
+
 const (
 	// The response on successful authentication always has this header. Capturing as const so we don't have marshaling and encoding overhead.
 	SPNEGO_NegTokenResp_Krb_Accept_Completed = "Negotiate oRQwEqADCgEAoQsGCSqGSIb3EgECAg=="
 	// The response on a failed authentication always has this rejection header. Capturing as const so we don't have marshaling and encoding overhead.
-	SPNEGO_NegTokenResp_Reject = "Negotiate oQcwBaADCgEC"
+	SPNEGO_NegTokenResp_Reject        = "Negotiate oQcwBaADCgEC"
+	CREDENTIALS_CTXKEY         ctxKey = 0
+	AUTHENTICATED_CTXKEY       ctxKey = 1
 )
 
 // Kerberos SPNEGO authentication HTTP handler wrapper.
@@ -62,8 +66,8 @@ func SPNEGOKRB5Authenticate(f http.Handler, kt keytab.Keytab, sa string, l *log.
 
 		if ok, creds, err := ValidateAPREQ(mt.APReq, kt, sa, r.RemoteAddr); ok {
 			ctx := r.Context()
-			ctx = context.WithValue(ctx, "credentials", creds)
-			ctx = context.WithValue(ctx, "authenticated", true)
+			ctx = context.WithValue(ctx, CREDENTIALS_CTXKEY, creds)
+			ctx = context.WithValue(ctx, AUTHENTICATED_CTXKEY, true)
 			if l != nil {
 				l.Printf("%v %s@%s - SPNEGO authentication succeeded", r.RemoteAddr, creds.Username, creds.Realm)
 			}

+ 1 - 1
service/http_test.go

@@ -129,6 +129,6 @@ func httpServer() *httptest.Server {
 func testAppHandler(w http.ResponseWriter, r *http.Request) {
 	w.WriteHeader(http.StatusOK)
 	ctx := r.Context()
-	fmt.Fprintf(w, "<html>\nTEST.GOKRB5 Handler\nAuthenticed user: %s\nUser's realm: %s\n</html>", ctx.Value("credentials").(credentials.Credentials).Username, ctx.Value("credentials").(credentials.Credentials).Realm)
+	fmt.Fprintf(w, "<html>\nTEST.GOKRB5 Handler\nAuthenticed user: %s\nUser's realm: %s\n</html>", ctx.Value(CREDENTIALS_CTXKEY).(credentials.Credentials).Username, ctx.Value(CREDENTIALS_CTXKEY).(credentials.Credentials).Realm)
 	return
 }

+ 2 - 2
types/KerberosFlags.go

@@ -77,7 +77,7 @@ func SetFlags(f *asn1.BitString, j []int) {
 }
 
 func SetFlag(f *asn1.BitString, i int) {
-	for l := len(f.Bytes); l < 4; l += 1 {
+	for l := len(f.Bytes); l < 4; l++ {
 		(*f).Bytes = append((*f).Bytes, byte(0))
 		(*f).BitLength = len((*f).Bytes) * 8
 	}
@@ -95,7 +95,7 @@ func UnsetFlags(f *asn1.BitString, j []int) {
 }
 
 func UnsetFlag(f *asn1.BitString, i int) {
-	for l := len(f.Bytes); l < 4; l += 1 {
+	for l := len(f.Bytes); l < 4; l++ {
 		(*f).Bytes = append((*f).Bytes, byte(0))
 		(*f).BitLength = len((*f).Bytes) * 8
 	}

+ 2 - 2
types/PAData.go

@@ -72,8 +72,8 @@ func (pa *PAData) Unmarshal(b []byte) error {
 	return err
 }
 
-func (pa *PADataSequence) Unmarshal(b []byte) error {
-	_, err := asn1.Unmarshal(b, pa)
+func (pas *PADataSequence) Unmarshal(b []byte) error {
+	_, err := asn1.Unmarshal(b, pas)
 	return err
 }