Added modified ntlm vendor lib (with fixed negotiation message)

This commit is contained in:
Andreas Schneider 2018-04-03 11:46:34 +02:00
parent 944b8a356d
commit 0c1c63e20e
23 changed files with 2996 additions and 0 deletions

View File

@ -0,0 +1,27 @@
Copyright (c) 2013, Thomson Reuters Global Resources
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by the Thomson Reuters Global Resources.
4. Neither the name of the Thomson Reuters Global Resources nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Thomson Reuters Global Resources ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Thomson Reuters Global Resources BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,187 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
)
type AvPairType uint16
// MS-NLMP - 2.2.2.1 AV_PAIR
const (
// Indicates that this is the last AV_PAIR in the list. AvLen MUST be 0. This type of information MUST be present in the AV pair list.
MsvAvEOL AvPairType = iota
// The server's NetBIOS computer name. The name MUST be in Unicode, and is not null-terminated. This type of information MUST be present in the AV_pair list.
MsvAvNbComputerName
// The server's NetBIOS domain name. The name MUST be in Unicode, and is not null-terminated. This type of information MUST be present in the AV_pair list.
MsvAvNbDomainName
// The fully qualified domain name (FQDN (1)) of the computer. The name MUST be in Unicode, and is not null-terminated.
MsvAvDnsComputerName
// The FQDN (2) of the domain. The name MUST be in Unicode, and is not null-terminate.
MsvAvDnsDomainName
// The FQDN (2) of the forest. The name MUST be in Unicode, and is not null-terminated.<11>
MsvAvDnsTreeName
// A 32-bit value indicating server or client configuration.
// 0x00000001: indicates to the client that the account authentication is constrained.
// 0x00000002: indicates that the client is providing message integrity in the MIC field (section 2.2.1.3) in the AUTHENTICATE_MESSAGE.<12>
// 0x00000004: indicates that the client is providing a target SPN generated from an untrusted source.<13>
MsvAvFlags
// A FILETIME structure ([MS-DTYP] section 2.3.1) in little-endian byte order that contains the server local time.<14>
MsvAvTimestamp
//A Restriction_Encoding (section 2.2.2.2) structure. The Value field contains a structure representing the integrity level of the security principal, as well as a MachineID created at computer startup to identify the calling machine.<15>
MsAvRestrictions
// The SPN of the target server. The name MUST be in Unicode and is not null-terminated.<16>
MsvAvTargetName
// annel bindings hash. The Value field contains an MD5 hash ([RFC4121] section 4.1.1.2) of a gss_channel_bindings_struct ([RFC2744] section 3.11).
// An all-zero value of the hash is used to indicate absence of channel bindings.<17>
MsvChannelBindings
)
// Helper struct that contains a list of AvPairs with helper methods for running through them
type AvPairs struct {
List []AvPair
}
func (p *AvPairs) AddAvPair(avId AvPairType, bytes []byte) {
a := &AvPair{AvId: avId, AvLen: uint16(len(bytes)), Value: bytes}
p.List = append(p.List, *a)
}
func ReadAvPairs(data []byte) *AvPairs {
pairs := new(AvPairs)
// Get the number of AvPairs and allocate enough AvPair structures to hold them
offset := 0
for i := 0; len(data) > 0 && i < 11; i++ {
pair := ReadAvPair(data, offset)
offset = offset + 4 + int(pair.AvLen)
pairs.List = append(pairs.List, *pair)
if pair.AvId == MsvAvEOL {
break
}
}
return pairs
}
func (p *AvPairs) Bytes() (result []byte) {
totalLength := 0
for i := range p.List {
a := p.List[i]
totalLength = totalLength + int(a.AvLen) + 4
}
result = make([]byte, 0, totalLength)
for i := range p.List {
a := p.List[i]
result = append(result, a.Bytes()...)
}
return result
}
func (p *AvPairs) String() string {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("Av Pairs (Total %d pairs)\n", len(p.List)))
for i := range p.List {
buffer.WriteString(p.List[i].String())
buffer.WriteString("\n")
}
return buffer.String()
}
func (p *AvPairs) Find(avType AvPairType) (result *AvPair) {
for i := range p.List {
pair := p.List[i]
if avType == pair.AvId {
result = &pair
break
}
}
return
}
func (p *AvPairs) ByteValue(avType AvPairType) (result []byte) {
pair := p.Find(avType)
if pair != nil {
result = pair.Value
}
return
}
func (p *AvPairs) StringValue(avType AvPairType) (result string) {
pair := p.Find(avType)
if pair != nil {
result = pair.UnicodeStringValue()
}
return
}
// AvPair as described by MS-NLMP
type AvPair struct {
AvId AvPairType
AvLen uint16
Value []byte
}
func ReadAvPair(data []byte, offset int) *AvPair {
pair := new(AvPair)
pair.AvId = AvPairType(binary.LittleEndian.Uint16(data[offset : offset+2]))
pair.AvLen = binary.LittleEndian.Uint16(data[offset+2 : offset+4])
pair.Value = data[offset+4 : offset+4+int(pair.AvLen)]
return pair
}
func (a *AvPair) UnicodeStringValue() string {
return utf16ToString(a.Value)
}
func (a *AvPair) Bytes() (result []byte) {
result = make([]byte, 4, a.AvLen+4)
result[0] = byte(a.AvId)
result[1] = byte(a.AvId >> 8)
result[2] = byte(a.AvLen)
result[3] = byte(a.AvLen >> 8)
result = append(result, a.Value...)
return
}
func (a *AvPair) String() string {
var outString string
switch a.AvId {
case MsvAvEOL:
outString = "MsvAvEOL"
case MsvAvNbComputerName:
outString = "MsAvNbComputerName: " + a.UnicodeStringValue()
case MsvAvNbDomainName:
outString = "MsvAvNbDomainName: " + a.UnicodeStringValue()
case MsvAvDnsComputerName:
outString = "MsvAvDnsComputerName: " + a.UnicodeStringValue()
case MsvAvDnsDomainName:
outString = "MsvAvDnsDomainName: " + a.UnicodeStringValue()
case MsvAvDnsTreeName:
outString = "MsvAvDnsTreeName: " + a.UnicodeStringValue()
case MsvAvFlags:
outString = "MsvAvFlags: " + hex.EncodeToString(a.Value)
case MsvAvTimestamp:
outString = "MsvAvTimestamp: " + hex.EncodeToString(a.Value)
case MsAvRestrictions:
outString = "MsAvRestrictions: " + hex.EncodeToString(a.Value)
case MsvAvTargetName:
outString = "MsvAvTargetName: " + a.UnicodeStringValue()
case MsvChannelBindings:
outString = "MsvChannelBindings: " + hex.EncodeToString(a.Value)
default:
outString = fmt.Sprintf("unknown pair type: '%d'", a.AvId)
}
return outString
}

View File

@ -0,0 +1,154 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
)
// NTLMv1
// ******
type NtlmV1Response struct {
// 24 byte array
Response []byte
}
func (n *NtlmV1Response) String() string {
return fmt.Sprintf("NtlmV1Response: %s", hex.EncodeToString(n.Response))
}
func ReadNtlmV1Response(bytes []byte) (*NtlmV1Response, error) {
r := new(NtlmV1Response)
r.Response = bytes[0:24]
return r, nil
}
// *** NTLMv2
// The NTLMv2_CLIENT_CHALLENGE structure defines the client challenge in the AUTHENTICATE_MESSAGE.
// This structure is used only when NTLM v2 authentication is configured.
type NtlmV2ClientChallenge struct {
// An 8-bit unsigned char that contains the current version of the challenge response type.
// This field MUST be 0x01.
RespType byte
// An 8-bit unsigned char that contains the maximum supported version of the challenge response type.
// This field MUST be 0x01.
HiRespType byte
// A 16-bit unsigned integer that SHOULD be 0x0000 and MUST be ignored on receipt.
Reserved1 uint16
// A 32-bit unsigned integer that SHOULD be 0x00000000 and MUST be ignored on receipt.
Reserved2 uint32
// A 64-bit unsigned integer that contains the current system time, represented as the number of 100 nanosecond
// ticks elapsed since midnight of January 1, 1601 (UTC).
TimeStamp []byte
// An 8-byte array of unsigned char that contains the client's ClientChallenge (section 3.1.5.1.2).
ChallengeFromClient []byte
// A 32-bit unsigned integer that SHOULD be 0x00000000 and MUST be ignored on receipt.
Reserved3 uint32
AvPairs *AvPairs
}
func (n *NtlmV2ClientChallenge) String() string {
var buffer bytes.Buffer
buffer.WriteString("NTLM v2 ClientChallenge\n")
buffer.WriteString(fmt.Sprintf("Timestamp: %s\n", hex.EncodeToString(n.TimeStamp)))
buffer.WriteString(fmt.Sprintf("ChallengeFromClient: %s\n", hex.EncodeToString(n.ChallengeFromClient)))
buffer.WriteString("AvPairs\n")
buffer.WriteString(n.AvPairs.String())
return buffer.String()
}
// The NTLMv2_RESPONSE structure defines the NTLMv2 authentication NtChallengeResponse in the AUTHENTICATE_MESSAGE.
// This response is used only when NTLMv2 authentication is configured.
type NtlmV2Response struct {
// A 16-byte array of unsigned char that contains the client's NT challenge- response as defined in section 3.3.2.
// Response corresponds to the NTProofStr variable from section 3.3.2.
Response []byte
// A variable-length byte array that contains the ClientChallenge as defined in section 3.3.2.
// ChallengeFromClient corresponds to the temp variable from section 3.3.2.
NtlmV2ClientChallenge *NtlmV2ClientChallenge
}
func (n *NtlmV2Response) String() string {
var buffer bytes.Buffer
buffer.WriteString("NTLM v2 Response\n")
buffer.WriteString(fmt.Sprintf("Response: %s\n", hex.EncodeToString(n.Response)))
buffer.WriteString(n.NtlmV2ClientChallenge.String())
return buffer.String()
}
func ReadNtlmV2Response(bytes []byte) (*NtlmV2Response, error) {
r := new(NtlmV2Response)
r.Response = bytes[0:16]
r.NtlmV2ClientChallenge = new(NtlmV2ClientChallenge)
c := r.NtlmV2ClientChallenge
c.RespType = bytes[16]
c.HiRespType = bytes[17]
if c.RespType != 1 || c.HiRespType != 1 {
return nil, errors.New("Does not contain a valid NTLM v2 client challenge - could be NTLMv1.")
}
// Ignoring - 2 bytes reserved
// c.Reserved1
// Ignoring - 4 bytes reserved
// c.Reserved2
c.TimeStamp = bytes[24:32]
c.ChallengeFromClient = bytes[32:40]
// Ignoring - 4 bytes reserved
// c.Reserved3
c.AvPairs = ReadAvPairs(bytes[44:])
return r, nil
}
// LMv1
// ****
type LmV1Response struct {
// 24 bytes
Response []byte
}
func ReadLmV1Response(bytes []byte) *LmV1Response {
r := new(LmV1Response)
r.Response = bytes[0:24]
return r
}
func (l *LmV1Response) String() string {
return fmt.Sprintf("LmV1Response: %s", hex.EncodeToString(l.Response))
}
// *** LMv2
type LmV2Response struct {
// A 16-byte array of unsigned char that contains the client's LM challenge-response.
// This is the portion of the LmChallengeResponse field to which the HMAC_MD5 algorithm
/// has been applied, as defined in section 3.3.2. Specifically, Response corresponds
// to the result of applying the HMAC_MD5 algorithm, using the key ResponseKeyLM, to a
// message consisting of the concatenation of the ResponseKeyLM, ServerChallenge and ClientChallenge.
Response []byte
// An 8-byte array of unsigned char that contains the client's ClientChallenge, as defined in section 3.1.5.1.2.
ChallengeFromClient []byte
}
func ReadLmV2Response(bytes []byte) *LmV2Response {
r := new(LmV2Response)
r.Response = bytes[0:16]
r.ChallengeFromClient = bytes[16:24]
return r
}
func (l *LmV2Response) String() string {
var buffer bytes.Buffer
buffer.WriteString("LM v2 Response\n")
buffer.WriteString(fmt.Sprintf("Response: %s\n", hex.EncodeToString(l.Response)))
buffer.WriteString(fmt.Sprintf("ChallengeFromClient: %s\n", hex.EncodeToString(l.ChallengeFromClient)))
return buffer.String()
}

View File

@ -0,0 +1,136 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
desP "crypto/des"
hmacP "crypto/hmac"
md5P "crypto/md5"
"crypto/rand"
rc4P "crypto/rc4"
crc32P "hash/crc32"
md4P "github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4"
)
func md4(data []byte) []byte {
md4 := md4P.New()
md4.Write(data)
return md4.Sum(nil)
}
func md5(data []byte) []byte {
md5 := md5P.New()
md5.Write(data)
return md5.Sum(nil)
}
// Indicates the computation of a 16-byte HMAC-keyed MD5 message digest of the byte string M using the key K.
func hmacMd5(key []byte, data []byte) []byte {
mac := hmacP.New(md5P.New, key)
mac.Write(data)
return mac.Sum(nil)
}
// Indicates the computation of an N-byte cryptographic- strength random number.
func nonce(length int) []byte {
result := make([]byte, length)
rand.Read(result)
return result
}
func crc32(bytes []byte) uint32 {
crc := crc32P.New(crc32P.IEEETable)
crc.Write(bytes)
return crc.Sum32()
}
// Indicates the encryption of data item D with the key K using the RC4 algorithm.
func rc4K(key []byte, ciphertext []byte) ([]byte, error) {
cipher, err := rc4P.NewCipher(key)
if err != nil {
return nil, err
}
result := make([]byte, len(ciphertext))
cipher.XORKeyStream(result, ciphertext)
return result, nil
}
func rc4Init(key []byte) (cipher *rc4P.Cipher, err error) {
cipher, err = rc4P.NewCipher(key)
if err != nil {
return nil, err
}
return cipher, nil
}
func rc4(cipher *rc4P.Cipher, ciphertext []byte) []byte {
result := make([]byte, len(ciphertext))
cipher.XORKeyStream(result, ciphertext)
return result
}
// Indicates the encryption of an 8-byte data item D with the 7-byte key K using the Data Encryption Standard (DES)
// algorithm in Electronic Codebook (ECB) mode. The result is 8 bytes in length ([FIPS46-2]).
func des(key []byte, ciphertext []byte) ([]byte, error) {
calcKey := createDesKey(key)
cipher, err := desP.NewCipher(calcKey)
if err != nil {
return nil, err
}
result := make([]byte, len(ciphertext))
cipher.Encrypt(result, ciphertext)
return result, nil
}
// Indicates the encryption of an 8-byte data item D with the 16-byte key K using the Data Encryption Standard Long (DESL) algorithm.
// The result is 24 bytes in length. DESL(K, D) is computed as follows.
// Note K[] implies a key represented as a character array.
func desL(key []byte, cipherText []byte) ([]byte, error) {
out1, err := des(zeroPaddedBytes(key, 0, 7), cipherText)
if err != nil {
return nil, err
}
out2, err := des(zeroPaddedBytes(key, 7, 7), cipherText)
if err != nil {
return nil, err
}
out3, err := des(zeroPaddedBytes(key, 14, 7), cipherText)
if err != nil {
return nil, err
}
return concat(out1, out2, out3), nil
}
// Creates a DES encryption key from the given 7 byte key material.
func createDesKey(keyBytes []byte) []byte {
material := zeroBytes(8)
material[0] = keyBytes[0]
material[1] = (byte)(keyBytes[0]<<7 | (keyBytes[1]&0xff)>>1)
material[2] = (byte)(keyBytes[1]<<6 | (keyBytes[2]&0xff)>>2)
material[3] = (byte)(keyBytes[2]<<5 | (keyBytes[3]&0xff)>>3)
material[4] = (byte)(keyBytes[3]<<4 | (keyBytes[4]&0xff)>>4)
material[5] = (byte)(keyBytes[4]<<3 | (keyBytes[5]&0xff)>>5)
material[6] = (byte)(keyBytes[5]<<2 | (keyBytes[6]&0xff)>>6)
material[7] = (byte)(keyBytes[6] << 1)
oddParity(material)
return material
}
// Applies odd parity to the given byte array.
func oddParity(bytes []byte) {
for i := 0; i < len(bytes); i++ {
b := bytes[i]
needsParity := (((b >> 7) ^ (b >> 6) ^ (b >> 5) ^ (b >> 4) ^ (b >> 3) ^ (b >> 2) ^ (b >> 1)) & 0x01) == 0
if needsParity {
bytes[i] = bytes[i] | byte(0x01)
} else {
bytes[i] = bytes[i] & byte(0xfe)
}
}
}

View File

@ -0,0 +1,88 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
"bytes"
"crypto/rand"
"encoding/binary"
"unicode/utf16"
)
// Concatenate two byte slices into a new slice
func concat(ar ...[]byte) []byte {
return bytes.Join(ar, nil)
}
// Create a 0 initialized slice of bytes
func zeroBytes(length int) []byte {
return make([]byte, length, length)
}
func randomBytes(length int) []byte {
randombytes := make([]byte, length)
_, err := rand.Read(randombytes)
if err != nil {
} // TODO: What to do with err here
return randombytes
}
// Zero pad the input byte slice to the given size
// bytes - input byte slice
// offset - where to start taking the bytes from the input slice
// size - size of the output byte slize
func zeroPaddedBytes(bytes []byte, offset int, size int) []byte {
newSlice := zeroBytes(size)
for i := 0; i < size && i+offset < len(bytes); i++ {
newSlice[i] = bytes[i+offset]
}
return newSlice
}
func MacsEqual(slice1, slice2 []byte) bool {
if len(slice1) != len(slice2) {
return false
}
for i := 0; i < len(slice1); i++ {
// bytes between 4 and 7 (inclusive) contains random
// data that should be ignored while comparing the
// macs
if (i < 4 || i > 7) && slice1[i] != slice2[i] {
return false
}
}
return true
}
func utf16FromString(s string) []byte {
encoded := utf16.Encode([]rune(s))
// TODO: I'm sure there is an easier way to do the conversion from utf16 to bytes
result := zeroBytes(len(encoded) * 2)
for i := 0; i < len(encoded); i++ {
result[i*2] = byte(encoded[i])
result[i*2+1] = byte(encoded[i] << 8)
}
return result
}
// Convert a UTF16 string to UTF8 string for Go usage
func utf16ToString(bytes []byte) string {
var data []uint16
// NOTE: This is definitely not the best way to do this, but when I tried using a buffer.Read I could not get it to work
for offset := 0; offset < len(bytes); offset = offset + 2 {
i := binary.LittleEndian.Uint16(bytes[offset : offset+2])
data = append(data, i)
}
return string(utf16.Decode(data))
}
func uint32ToBytes(v uint32) []byte {
bytes := make([]byte, 4)
bytes[0] = byte(v & 0xff)
bytes[1] = byte((v >> 8) & 0xff)
bytes[2] = byte((v >> 16) & 0xff)
bytes[3] = byte((v >> 24) & 0xff)
return bytes
}

View File

@ -0,0 +1,70 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
// Define KXKEY(SessionBaseKey, LmChallengeResponse, ServerChallenge) as
func kxKey(flags uint32, sessionBaseKey []byte, lmChallengeResponse []byte, serverChallenge []byte, lmnowf []byte) (keyExchangeKey []byte, err error) {
if NTLMSSP_NEGOTIATE_LM_KEY.IsSet(flags) {
var part1, part2 []byte
part1, err = des(lmnowf[0:7], lmChallengeResponse[0:8])
if err != nil {
return nil, err
}
key := append([]byte{lmnowf[7]}, []byte{0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD}...)
part2, err = des(key, lmChallengeResponse[0:8])
if err != nil {
return nil, err
}
keyExchangeKey = concat(part1, part2)
} else if NTLMSSP_REQUEST_NON_NT_SESSION_KEY.IsSet(flags) {
keyExchangeKey = concat(lmnowf[0:8], zeroBytes(8))
} else {
keyExchangeKey = sessionBaseKey
}
return
}
// Define SIGNKEY(NegFlg, RandomSessionKey, Mode) as
func signKey(flags uint32, randomSessionKey []byte, mode string) (signKey []byte) {
if NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.IsSet(flags) {
if mode == "Client" {
signKey = md5(concat(randomSessionKey, []byte("session key to client-to-server signing key magic constant\x00")))
} else {
signKey = md5(concat(randomSessionKey, []byte("session key to server-to-client signing key magic constant\x00")))
}
} else {
signKey = nil
}
return
}
// Define SEALKEY(NegotiateFlags, RandomSessionKey, Mode) as
func sealKey(flags uint32, randomSessionKey []byte, mode string) (sealKey []byte) {
if NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.IsSet(flags) {
if NTLMSSP_NEGOTIATE_128.IsSet(flags) {
sealKey = randomSessionKey
} else if NTLMSSP_NEGOTIATE_56.IsSet(flags) {
sealKey = randomSessionKey[0:7]
} else {
sealKey = randomSessionKey[0:5]
}
if mode == "Client" {
sealKey = md5(concat(sealKey, []byte("session key to client-to-server sealing key magic constant\x00")))
} else {
sealKey = md5(concat(sealKey, []byte("session key to server-to-client sealing key magic constant\x00")))
}
} else if NTLMSSP_NEGOTIATE_LM_KEY.IsSet(flags) {
if NTLMSSP_NEGOTIATE_56.IsSet(flags) {
sealKey = concat(randomSessionKey[0:7], []byte{0xA0})
} else {
sealKey = concat(randomSessionKey[0:5], []byte{0xE5, 0x38, 0xB0})
}
} else {
sealKey = randomSessionKey
}
return
}

View File

@ -0,0 +1,27 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,118 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package md4 implements the MD4 hash algorithm as defined in RFC 1320.
package md4
import (
"crypto"
"hash"
)
func init() {
crypto.RegisterHash(crypto.MD4, New)
}
// The size of an MD4 checksum in bytes.
const Size = 16
// The blocksize of MD4 in bytes.
const BlockSize = 64
const (
_Chunk = 64
_Init0 = 0x67452301
_Init1 = 0xEFCDAB89
_Init2 = 0x98BADCFE
_Init3 = 0x10325476
)
// digest represents the partial evaluation of a checksum.
type digest struct {
s [4]uint32
x [_Chunk]byte
nx int
len uint64
}
func (d *digest) Reset() {
d.s[0] = _Init0
d.s[1] = _Init1
d.s[2] = _Init2
d.s[3] = _Init3
d.nx = 0
d.len = 0
}
// New returns a new hash.Hash computing the MD4 checksum.
func New() hash.Hash {
d := new(digest)
d.Reset()
return d
}
func (d *digest) Size() int { return Size }
func (d *digest) BlockSize() int { return BlockSize }
func (d *digest) Write(p []byte) (nn int, err error) {
nn = len(p)
d.len += uint64(nn)
if d.nx > 0 {
n := len(p)
if n > _Chunk-d.nx {
n = _Chunk - d.nx
}
for i := 0; i < n; i++ {
d.x[d.nx+i] = p[i]
}
d.nx += n
if d.nx == _Chunk {
_Block(d, d.x[0:])
d.nx = 0
}
p = p[n:]
}
n := _Block(d, p)
p = p[n:]
if len(p) > 0 {
d.nx = copy(d.x[:], p)
}
return
}
func (d0 *digest) Sum(in []byte) []byte {
// Make a copy of d0, so that caller can keep writing and summing.
d := new(digest)
*d = *d0
// Padding. Add a 1 bit and 0 bits until 56 bytes mod 64.
len := d.len
var tmp [64]byte
tmp[0] = 0x80
if len%64 < 56 {
d.Write(tmp[0 : 56-len%64])
} else {
d.Write(tmp[0 : 64+56-len%64])
}
// Length in bits.
len <<= 3
for i := uint(0); i < 8; i++ {
tmp[i] = byte(len >> (8 * i))
}
d.Write(tmp[0:8])
if d.nx != 0 {
panic("d.nx != 0")
}
for _, s := range d.s {
in = append(in, byte(s>>0))
in = append(in, byte(s>>8))
in = append(in, byte(s>>16))
in = append(in, byte(s>>24))
}
return in
}

View File

@ -0,0 +1,89 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// MD4 block step.
// In its own file so that a faster assembly or C version
// can be substituted easily.
package md4
var shift1 = []uint{3, 7, 11, 19}
var shift2 = []uint{3, 5, 9, 13}
var shift3 = []uint{3, 9, 11, 15}
var xIndex2 = []uint{0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15}
var xIndex3 = []uint{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}
func _Block(dig *digest, p []byte) int {
a := dig.s[0]
b := dig.s[1]
c := dig.s[2]
d := dig.s[3]
n := 0
var X [16]uint32
for len(p) >= _Chunk {
aa, bb, cc, dd := a, b, c, d
j := 0
for i := 0; i < 16; i++ {
X[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24
j += 4
}
// If this needs to be made faster in the future,
// the usual trick is to unroll each of these
// loops by a factor of 4; that lets you replace
// the shift[] lookups with constants and,
// with suitable variable renaming in each
// unrolled body, delete the a, b, c, d = d, a, b, c
// (or you can let the optimizer do the renaming).
//
// The index variables are uint so that % by a power
// of two can be optimized easily by a compiler.
// Round 1.
for i := uint(0); i < 16; i++ {
x := i
s := shift1[i%4]
f := ((c ^ d) & b) ^ d
a += f + X[x]
a = a<<s | a>>(32-s)
a, b, c, d = d, a, b, c
}
// Round 2.
for i := uint(0); i < 16; i++ {
x := xIndex2[i]
s := shift2[i%4]
g := (b & c) | (b & d) | (c & d)
a += g + X[x] + 0x5a827999
a = a<<s | a>>(32-s)
a, b, c, d = d, a, b, c
}
// Round 3.
for i := uint(0); i < 16; i++ {
x := xIndex3[i]
s := shift3[i%4]
h := b ^ c ^ d
a += h + X[x] + 0x6ed9eba1
a = a<<s | a>>(32-s)
a, b, c, d = d, a, b, c
}
a += aa
b += bb
c += cc
d += dd
p = p[_Chunk:]
n += _Chunk
}
dig.s[0] = a
dig.s[1] = b
dig.s[2] = c
dig.s[3] = d
return n
}

View File

@ -0,0 +1,291 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
)
type AuthenticateMessage struct {
// sig - 8 bytes
Signature []byte
// message type - 4 bytes
MessageType uint32
// The LmChallenge Response can be v1 or v2
LmChallengeResponse *PayloadStruct // 8 bytes
LmV1Response *LmV1Response
LmV2Response *LmV2Response
// The NtChallengeResponse can be v1 or v2
NtChallengeResponseFields *PayloadStruct // 8 bytes
NtlmV1Response *NtlmV1Response
NtlmV2Response *NtlmV2Response
DomainName *PayloadStruct // 8 bytes
UserName *PayloadStruct // 8 bytes
Workstation *PayloadStruct // 8 bytes
// If the NTLMSSP_NEGOTIATE_KEY_EXCH flag is set in the neogitate flags then this will point to the offset in the payload
// with the key, otherwise it will have Len = 0. According to Davenport these bytes are optional (see Type3 message).
// The MS-NLMP docs do not mention this.
EncryptedRandomSessionKey *PayloadStruct // 8 bytes
/// MS-NLMP 2.2.1.3 - In connectionless mode, a NEGOTIATE structure that contains a set of bit flags (section 2.2.2.5) and represents the
// conclusion of negotiation—the choices the client has made from the options the server offered in the CHALLENGE_MESSAGE.
// In connection-oriented mode, a NEGOTIATE structure that contains the set of bit flags (section 2.2.2.5) negotiated in
// the previous
NegotiateFlags uint32 // 4 bytes
// Version (8 bytes): A VERSION structure (section 2.2.2.10) that is present only when the NTLMSSP_NEGOTIATE_VERSION
// flag is set in the NegotiateFlags field. This structure is used for debugging purposes only. In normal protocol
// messages, it is ignored and does not affect the NTLM message processing.<9>
Version *VersionStruct
// The message integrity for the NTLM NEGOTIATE_MESSAGE, CHALLENGE_MESSAGE, and AUTHENTICATE_MESSAGE.<10>
Mic []byte // 16 bytes
// payload - variable
Payload []byte
}
func ParseAuthenticateMessage(body []byte, ntlmVersion int) (*AuthenticateMessage, error) {
am := new(AuthenticateMessage)
am.Signature = body[0:8]
if !bytes.Equal(am.Signature, []byte("NTLMSSP\x00")) {
return nil, errors.New("Invalid NTLM message signature")
}
am.MessageType = binary.LittleEndian.Uint32(body[8:12])
if am.MessageType != 3 {
return nil, errors.New("Invalid NTLM message type should be 0x00000003 for authenticate message")
}
var err error
am.LmChallengeResponse, err = ReadBytePayload(12, body)
if err != nil {
return nil, err
}
if ntlmVersion == 2 {
am.LmV2Response = ReadLmV2Response(am.LmChallengeResponse.Payload)
} else {
am.LmV1Response = ReadLmV1Response(am.LmChallengeResponse.Payload)
}
am.NtChallengeResponseFields, err = ReadBytePayload(20, body)
if err != nil {
return nil, err
}
// Check to see if this is a v1 or v2 response
if ntlmVersion == 2 {
am.NtlmV2Response, err = ReadNtlmV2Response(am.NtChallengeResponseFields.Payload)
} else {
am.NtlmV1Response, err = ReadNtlmV1Response(am.NtChallengeResponseFields.Payload)
}
if err != nil {
return nil, err
}
am.DomainName, err = ReadStringPayload(28, body)
if err != nil {
return nil, err
}
am.UserName, err = ReadStringPayload(36, body)
if err != nil {
return nil, err
}
am.Workstation, err = ReadStringPayload(44, body)
if err != nil {
return nil, err
}
lowestOffset := am.getLowestPayloadOffset()
offset := 52
// If the lowest payload offset is 52 then:
// The Session Key, flags, and OS Version structure are omitted. The data (payload) block in this case starts after the Workstation Name
// security buffer header, at offset 52. This form is seen in older Win9x-based systems. This is from the davenport notes about Type 3
// messages and this information does not seem to be present in the MS-NLMP document
if lowestOffset > 52 {
am.EncryptedRandomSessionKey, err = ReadBytePayload(offset, body)
if err != nil {
return nil, err
}
offset = offset + 8
am.NegotiateFlags = binary.LittleEndian.Uint32(body[offset : offset+4])
offset = offset + 4
// Version (8 bytes): A VERSION structure (section 2.2.2.10) that is present only when the NTLMSSP_NEGOTIATE_VERSION flag is set in the NegotiateFlags field. This structure is used for debugging purposes only. In normal protocol messages, it is ignored and does not affect the NTLM message processing.<9>
if NTLMSSP_NEGOTIATE_VERSION.IsSet(am.NegotiateFlags) {
am.Version, err = ReadVersionStruct(body[offset : offset+8])
if err != nil {
return nil, err
}
offset = offset + 8
}
// The MS-NLMP has this to say about the MIC
// "An AUTHENTICATE_MESSAGE indicates the presence of a MIC field if the TargetInfo field has an AV_PAIR structure whose two fields are:
// AvId == MsvAvFlags Value bit 0x2 == 1"
// However there is no TargetInfo structure in the Authenticate Message! There is one in the Challenge Message though. So I'm using
// a hack to check to see if there is a MIC. I look to see if there is room for the MIC before the payload starts. If so I assume
// there is a MIC and read it out.
var lowestOffset = am.getLowestPayloadOffset()
if lowestOffset > offset {
// MIC - 16 bytes
am.Mic = body[offset : offset+16]
offset = offset + 16
}
}
am.Payload = body[offset:]
return am, nil
}
func (a *AuthenticateMessage) ClientChallenge() (response []byte) {
if a.NtlmV2Response != nil {
response = a.NtlmV2Response.NtlmV2ClientChallenge.ChallengeFromClient
} else if a.NtlmV1Response != nil && NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.IsSet(a.NegotiateFlags) {
response = a.LmV1Response.Response[0:8]
}
return response
}
func (a *AuthenticateMessage) getLowestPayloadOffset() int {
payloadStructs := [...]*PayloadStruct{a.LmChallengeResponse, a.NtChallengeResponseFields, a.DomainName, a.UserName, a.Workstation, a.EncryptedRandomSessionKey}
// Find the lowest offset value
lowest := 9999
for i := range payloadStructs {
p := payloadStructs[i]
if p != nil && p.Offset > 0 && int(p.Offset) < lowest {
lowest = int(p.Offset)
}
}
return lowest
}
func (a *AuthenticateMessage) Bytes() []byte {
payloadLen := int(a.LmChallengeResponse.Len + a.NtChallengeResponseFields.Len + a.DomainName.Len + a.UserName.Len + a.Workstation.Len + a.EncryptedRandomSessionKey.Len)
messageLen := 8 + 4 + 6*8 + 4 + 8 + 16
payloadOffset := uint32(messageLen)
messageBytes := make([]byte, 0, messageLen+payloadLen)
buffer := bytes.NewBuffer(messageBytes)
buffer.Write(a.Signature)
binary.Write(buffer, binary.LittleEndian, a.MessageType)
a.LmChallengeResponse.Offset = payloadOffset
payloadOffset += uint32(a.LmChallengeResponse.Len)
buffer.Write(a.LmChallengeResponse.Bytes())
a.NtChallengeResponseFields.Offset = payloadOffset
payloadOffset += uint32(a.NtChallengeResponseFields.Len)
buffer.Write(a.NtChallengeResponseFields.Bytes())
a.DomainName.Offset = payloadOffset
payloadOffset += uint32(a.DomainName.Len)
buffer.Write(a.DomainName.Bytes())
a.UserName.Offset = payloadOffset
payloadOffset += uint32(a.UserName.Len)
buffer.Write(a.UserName.Bytes())
a.Workstation.Offset = payloadOffset
payloadOffset += uint32(a.Workstation.Len)
buffer.Write(a.Workstation.Bytes())
a.EncryptedRandomSessionKey.Offset = payloadOffset
payloadOffset += uint32(a.EncryptedRandomSessionKey.Len)
buffer.Write(a.EncryptedRandomSessionKey.Bytes())
buffer.Write(uint32ToBytes(a.NegotiateFlags))
if a.Version != nil {
buffer.Write(a.Version.Bytes())
} else {
buffer.Write(make([]byte, 8))
}
if a.Mic != nil {
buffer.Write(a.Mic)
} else {
buffer.Write(make([]byte, 16))
}
// Write out the payloads
buffer.Write(a.LmChallengeResponse.Payload)
buffer.Write(a.NtChallengeResponseFields.Payload)
buffer.Write(a.DomainName.Payload)
buffer.Write(a.UserName.Payload)
buffer.Write(a.Workstation.Payload)
buffer.Write(a.EncryptedRandomSessionKey.Payload)
return buffer.Bytes()
}
func (a *AuthenticateMessage) String() string {
var buffer bytes.Buffer
buffer.WriteString("Authenticate NTLM Message\n")
buffer.WriteString(fmt.Sprintf("Payload Offset: %d Length: %d\n", a.getLowestPayloadOffset(), len(a.Payload)))
if a.LmV2Response != nil {
buffer.WriteString(a.LmV2Response.String())
buffer.WriteString("\n")
}
if a.LmV1Response != nil {
buffer.WriteString(a.LmV1Response.String())
buffer.WriteString("\n")
}
if a.NtlmV2Response != nil {
buffer.WriteString(a.NtlmV2Response.String())
buffer.WriteString("\n")
}
if a.NtlmV1Response != nil {
buffer.WriteString(fmt.Sprintf("NtlmResponse Length: %d\n", a.NtChallengeResponseFields.Len))
buffer.WriteString(a.NtlmV1Response.String())
buffer.WriteString("\n")
}
buffer.WriteString(fmt.Sprintf("UserName: %s\n", a.UserName.String()))
buffer.WriteString(fmt.Sprintf("DomainName: %s\n", a.DomainName.String()))
buffer.WriteString(fmt.Sprintf("Workstation: %s\n", a.Workstation.String()))
if a.EncryptedRandomSessionKey != nil {
buffer.WriteString(fmt.Sprintf("EncryptedRandomSessionKey: %s\n", a.EncryptedRandomSessionKey.String()))
}
if a.Version != nil {
buffer.WriteString(fmt.Sprintf("Version: %s\n", a.Version.String()))
}
if a.Mic != nil {
buffer.WriteString(fmt.Sprintf("MIC: %s\n", hex.EncodeToString(a.Mic)))
}
buffer.WriteString(fmt.Sprintf("Flags %d\n", a.NegotiateFlags))
buffer.WriteString(FlagsToString(a.NegotiateFlags))
return buffer.String()
}

View File

@ -0,0 +1,171 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
)
type ChallengeMessage struct {
// sig - 8 bytes
Signature []byte
// message type - 4 bytes
MessageType uint32
// targetname - 12 bytes
TargetName *PayloadStruct
// negotiate flags - 4bytes
NegotiateFlags uint32
// server challenge - 8 bytes
ServerChallenge []byte
// MS-NLMP and Davenport disagree a little on the next few fields and how optional they are
// This is what Davenport has to say:
// As with the Type 1 message, there are a few versions of the Type 2 that have been observed:
//
// Version 1 -- The Context, Target Information, and OS Version structure are all omitted. The data block
// (containing only the contents of the Target Name security buffer) begins at offset 32. This form
// is seen in older Win9x-based systems, and is roughly documented in the Open Group's ActiveX reference
// documentation (Section 11.2.3).
//
// Version 2 -- The Context and Target Information fields are present, but the OS Version structure is not.
// The data block begins after the Target Information header, at offset 48. This form is seen in most out-of-box
// shipping versions of Windows.
//
// Version 3 -- The Context, Target Information, and OS Version structure are all present. The data block begins
// after the OS Version structure, at offset 56. Again, the buffers may be empty (yielding a zero-length data block).
// This form was introduced in a relatively recent Service Pack, and is seen on currently-patched versions of Windows 2000,
// Windows XP, and Windows 2003.
// reserved - 8 bytes (set to 0). This field is also known as 'context' in the davenport documentation
Reserved []byte
// targetinfo - 12 bytes
TargetInfoPayloadStruct *PayloadStruct
TargetInfo *AvPairs
// version - 8 bytes
Version *VersionStruct
// payload - variable
Payload []byte
}
func ParseChallengeMessage(body []byte) (*ChallengeMessage, error) {
challenge := new(ChallengeMessage)
challenge.Signature = body[0:8]
if !bytes.Equal(challenge.Signature, []byte("NTLMSSP\x00")) {
return challenge, errors.New("Invalid NTLM message signature")
}
challenge.MessageType = binary.LittleEndian.Uint32(body[8:12])
if challenge.MessageType != 2 {
return challenge, errors.New("Invalid NTLM message type should be 0x00000002 for challenge message")
}
var err error
challenge.TargetName, err = ReadStringPayload(12, body)
if err != nil {
return nil, err
}
challenge.NegotiateFlags = binary.LittleEndian.Uint32(body[20:24])
challenge.ServerChallenge = body[24:32]
challenge.Reserved = body[32:40]
challenge.TargetInfoPayloadStruct, err = ReadBytePayload(40, body)
if err != nil {
return nil, err
}
challenge.TargetInfo = ReadAvPairs(challenge.TargetInfoPayloadStruct.Payload)
offset := 48
if NTLMSSP_NEGOTIATE_VERSION.IsSet(challenge.NegotiateFlags) {
challenge.Version, err = ReadVersionStruct(body[offset : offset+8])
if err != nil {
return nil, err
}
offset = offset + 8
}
challenge.Payload = body[offset:]
return challenge, nil
}
func (c *ChallengeMessage) Bytes() []byte {
payloadLen := int(c.TargetName.Len + c.TargetInfoPayloadStruct.Len)
messageLen := 8 + 4 + 8 + 4 + 8 + 8 + 8 + 8
payloadOffset := uint32(messageLen)
messageBytes := make([]byte, 0, messageLen+payloadLen)
buffer := bytes.NewBuffer(messageBytes)
buffer.Write(c.Signature)
binary.Write(buffer, binary.LittleEndian, c.MessageType)
c.TargetName.Offset = payloadOffset
buffer.Write(c.TargetName.Bytes())
payloadOffset += uint32(c.TargetName.Len)
binary.Write(buffer, binary.LittleEndian, c.NegotiateFlags)
buffer.Write(c.ServerChallenge)
buffer.Write(make([]byte, 8))
c.TargetInfoPayloadStruct.Offset = payloadOffset
buffer.Write(c.TargetInfoPayloadStruct.Bytes())
payloadOffset += uint32(c.TargetInfoPayloadStruct.Len)
// if(c.Version != nil) {
buffer.Write(c.Version.Bytes())
// } else {
// buffer.Write(make([]byte, 8))
//}
// Write out the payloads
buffer.Write(c.TargetName.Payload)
buffer.Write(c.TargetInfoPayloadStruct.Payload)
return buffer.Bytes()
}
func (c *ChallengeMessage) getLowestPayloadOffset() int {
payloadStructs := [...]*PayloadStruct{c.TargetName, c.TargetInfoPayloadStruct}
// Find the lowest offset value
lowest := 9999
for i := range payloadStructs {
p := payloadStructs[i]
if p != nil && p.Offset > 0 && int(p.Offset) < lowest {
lowest = int(p.Offset)
}
}
return lowest
}
func (c *ChallengeMessage) String() string {
var buffer bytes.Buffer
buffer.WriteString("Challenge NTLM Message")
buffer.WriteString(fmt.Sprintf("\nPayload Offset: %d Length: %d", c.getLowestPayloadOffset(), len(c.Payload)))
buffer.WriteString(fmt.Sprintf("\nTargetName: %s", c.TargetName.String()))
buffer.WriteString(fmt.Sprintf("\nServerChallenge: %s", hex.EncodeToString(c.ServerChallenge)))
if c.Version != nil {
buffer.WriteString(fmt.Sprintf("\nVersion: %s\n", c.Version.String()))
}
buffer.WriteString("\nTargetInfo")
buffer.WriteString(c.TargetInfo.String())
buffer.WriteString(fmt.Sprintf("\nFlags %d\n", c.NegotiateFlags))
buffer.WriteString(FlagsToString(c.NegotiateFlags))
return buffer.String()
}

View File

@ -0,0 +1,27 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
type NegotiateMessage struct {
// All bytes of the message
Bytes []byte
// sig - 8 bytes
Signature []byte
// message type - 4 bytes
MessageType uint32
// negotiate flags - 4bytes
NegotiateFlags uint32
// If the NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED flag is not set in NegotiateFlags,
// indicating that no DomainName is supplied in Payload - then this should have Len 0 / MaxLen 0
// this contains a domain name
DomainNameFields *PayloadStruct
// If the NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED flag is not set in NegotiateFlags,
// indicating that no WorkstationName is supplied in Payload - then this should have Len 0 / MaxLen 0
WorkstationFields *PayloadStruct
// version - 8 bytes
Version *VersionStruct
// payload - variable
Payload []byte
PayloadOffset int
}

View File

@ -0,0 +1,202 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
// During NTLM authentication, each of the following flags is a possible value of the NegotiateFlags field of the NEGOTIATE_MESSAGE,
// CHALLENGE_MESSAGE, and AUTHENTICATE_MESSAGE, unless otherwise noted. These flags define client or server NTLM capabilities
// ssupported by the sender.
import (
"bytes"
"fmt"
"reflect"
)
type NegotiateFlag uint32
const (
// A (1 bit): If set, requests Unicode character set encoding. An alternate name for this field is NTLMSSP_NEGOTIATE_UNICODE.
NTLMSSP_NEGOTIATE_UNICODE NegotiateFlag = 1 << iota
// B (1 bit): If set, requests OEM character set encoding. An alternate name for this field is NTLM_NEGOTIATE_OEM. See bit A for details.
NTLM_NEGOTIATE_OEM
// The A and B bits are evaluated together as follows:
// A==1: The choice of character set encoding MUST be Unicode.
// A==0 and B==1: The choice of character set encoding MUST be OEM.
// A==0 and B==0: The protocol MUST return SEC_E_INVALID_TOKEN.
// C (1 bit): If set, a TargetName field of the CHALLENGE_MESSAGE (section 2.2.1.2) MUST be supplied. An alternate name for this field is NTLMSSP_REQUEST_TARGET.
NTLMSSP_REQUEST_TARGET
// r10 (1 bit): This bit is unused and MUST be zero.
NTLMSSP_R10
// D (1 bit): If set, requests session key negotiation for message signatures. If the client sends NTLMSSP_NEGOTIATE_SIGN to the server
// in the NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_SIGN to the client in the CHALLENGE_MESSAGE. An alternate name
// for this field is NTLMSSP_NEGOTIATE_SIGN.
NTLMSSP_NEGOTIATE_SIGN
// E (1 bit): If set, requests session key negotiation for message confidentiality. If the client sends NTLMSSP_NEGOTIATE_SEAL
// to the server in the NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_SEAL to the client in the CHALLENGE_MESSAGE.
// Clients and servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD always set NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128,
// if they are supported. An alternate name for this field is NTLMSSP_NEGOTIATE_SEAL.
NTLMSSP_NEGOTIATE_SEAL
// F (1 bit): If set, requests connectionless authentication. If NTLMSSP_NEGOTIATE_DATAGRAM is set, then NTLMSSP_NEGOTIATE_KEY_EXCH
// MUST always be set in the AUTHENTICATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the client. An alternate name for
// this field is NTLMSSP_NEGOTIATE_DATAGRAM.
NTLMSSP_NEGOTIATE_DATAGRAM
// G (1 bit): If set, requests LAN Manager (LM) session key computation. NTLMSSP_NEGOTIATE_LM_KEY and NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
// are mutually exclusive. If both NTLMSSP_NEGOTIATE_LM_KEY and NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are requested,
// NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY alone MUST be returned to the client. NTLM v2 authentication session key generation
// MUST be supported by both the client and the DC in order to be used, and extended session security signing and sealing requires
// support from the client and the server to be used. An alternate name for this field is NTLMSSP_NEGOTIATE_LM_KEY.
NTLMSSP_NEGOTIATE_LM_KEY
// r9 (1 bit): This bit is unused and MUST be zero.
NTLMSSP_R9
// H (1 bit): If set, requests usage of the NTLM v1 session security protocol. NTLMSSP_NEGOTIATE_NTLM MUST be set in the
// NEGOTIATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the client. An alternate name for this field is NTLMSSP_NEGOTIATE_NTLM.
NTLMSSP_NEGOTIATE_NTLM
// r8 (1 bit): This bit is unused and MUST be zero.
NTLMSSP_R8
// J (1 bit): If set, the connection SHOULD be anonymous.<26> r8 (1 bit): This bit is unused and SHOULD be zero.<27>
NTLMSSP_ANONYMOUS
// K (1 bit): If set, the domain name is provided (section 2.2.1.1).<25> An alternate name for this field is NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED.
NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED
// L (1 bit): This flag indicates whether the Workstation field is present. If this flag is not set, the Workstation field
// MUST be ignored. If this flag is set, the length field of the Workstation field specifies whether the workstation name
// is nonempty or not.<24> An alternate name for this field is NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED.
NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED
// r7 (1 bit): This bit is unused and MUST be zero.
NTLMSSP_R7
// M (1 bit): If set, requests the presence of a signature block on all NTLMSSP_NEGOTIATE_ALWAYS_SIGN MUST be
// set in the NEGOTIATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the client. NTLMSSP_NEGOTIATE_ALWAYS_SIGN is
// overridden by NTLMSSP_NEGOTIATE_SIGN and NTLMSSP_NEGOTIATE_SEAL, if they are supported. An alternate name for this field
// is NTLMSSP_NEGOTIATE_ALWAYS_SIGN.
NTLMSSP_NEGOTIATE_ALWAYS_SIGN
// N (1 bit): If set, TargetName MUST be a domain name. The data corresponding to this flag is provided by the server in the
// TargetName field of the CHALLENGE_MESSAGE. If set, then NTLMSSP_TARGET_TYPE_SERVER MUST NOT be set. This flag MUST be ignored
// in the NEGOTIATE_MESSAGE and the AUTHENTICATE_MESSAGE. An alternate name for this field is NTLMSSP_TARGET_TYPE_DOMAIN.
NTLMSSP_TARGET_TYPE_DOMAIN
// O (1 bit): If set, TargetName MUST be a server name. The data corresponding to this flag is provided by the server in the
// TargetName field of the CHALLENGE_MESSAGE. If this bit is set, then NTLMSSP_TARGET_TYPE_DOMAIN MUST NOT be set. This flag MUST
// be ignored in the NEGOTIATE_MESSAGE and the AUTHENTICATE_MESSAGE. An alternate name for this field is NTLMSSP_TARGET_TYPE_SERVER.
NTLMSSP_TARGET_TYPE_SERVER
// r6 (1 bit): This bit is unused and MUST be zero.
NTLMSSP_R6
// P (1 bit): If set, requests usage of the NTLM v2 session security. NTLM v2 session security is a misnomer because it is not
// NTLM v2. It is NTLM v1 using the extended session security that is also in NTLM v2. NTLMSSP_NEGOTIATE_LM_KEY and
// NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are mutually exclusive. If both NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY and
// NTLMSSP_NEGOTIATE_LM_KEY are requested, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY alone MUST be returned to the client.
// NTLM v2 authentication session key generation MUST be supported by both the client and the DC in order to be used, and extended
// session security signing and sealing requires support from the client and the server in order to be used.<23> An alternate name
// for this field is NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.
NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
// Q (1 bit): If set, requests an identify level token. An alternate name for this field is NTLMSSP_NEGOTIATE_IDENTIFY.
NTLMSSP_NEGOTIATE_IDENTIFY
// r5 (1 bit): This bit is unused and MUST be zero.
NTLMSSP_R5
// R (1 bit): If set, requests the usage of the LMOWF (section 3.3). An alternate name for this field is NTLMSSP_REQUEST_NON_NT_SESSION_KEY.
NTLMSSP_REQUEST_NON_NT_SESSION_KEY
// S (1 bit): If set, indicates that the TargetInfo fields in the CHALLENGE_MESSAGE (section 2.2.1.2) are populated. An alternate
// name for this field is NTLMSSP_NEGOTIATE_TARGET_INFO.
NTLMSSP_NEGOTIATE_TARGET_INFO
// r4 (1 bit): This bit is unused and MUST be zero.
NTLMSSP_R4
// T (1 bit): If set, requests the protocol version number. The data corresponding to this flag is provided in the Version field of the
// NEGOTIATE_MESSAGE, the CHALLENGE_MESSAGE, and the AUTHENTICATE_MESSAGE.<22> An alternate name for this field is NTLMSSP_NEGOTIATE_VERSION.
NTLMSSP_NEGOTIATE_VERSION
// r3 (1 bit): This bit is unused and MUST be zero.
NTLMSSP_R3
// r2 (1 bit): This bit is unused and MUST be zero.
NTLMSSP_R2
// r1 (1 bit): This bit is unused and MUST be zero.
NTLMSSP_R1
// U (1 bit): If set, requests 128-bit session key negotiation. An alternate name for this field is NTLMSSP_NEGOTIATE_128. If the client
// sends NTLMSSP_NEGOTIATE_128 to the server in the NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_128 to the client in the
// CHALLENGE_MESSAGE only if the client sets NTLMSSP_NEGOTIATE_SEAL or NTLMSSP_NEGOTIATE_SIGN. Otherwise it is ignored. If both
// NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 are requested and supported by the client and server, NTLMSSP_NEGOTIATE_56 and
// NTLMSSP_NEGOTIATE_128 will both be returned to the client. Clients and servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD set
// NTLMSSP_NEGOTIATE_128 if it is supported. An alternate name for this field is NTLMSSP_NEGOTIATE_128.<21>
NTLMSSP_NEGOTIATE_128
// V (1 bit): If set, requests an explicit key exchange. This capability SHOULD be used because it improves security for message integrity or
// confidentiality. See sections 3.2.5.1.2, 3.2.5.2.1, and 3.2.5.2.2 for details. An alternate name for this field is NTLMSSP_NEGOTIATE_KEY_EXCH.
NTLMSSP_NEGOTIATE_KEY_EXCH
// If set, requests 56-bit encryption. If the client sends NTLMSSP_NEGOTIATE_SEAL or NTLMSSP_NEGOTIATE_SIGN with NTLMSSP_NEGOTIATE_56 to the
// server in the NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_56 to the client in the CHALLENGE_MESSAGE. Otherwise it is ignored.
// If both NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 are requested and supported by the client and server, NTLMSSP_NEGOTIATE_56 and
// NTLMSSP_NEGOTIATE_128 will both be returned to the client. Clients and servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD set NTLMSSP_NEGOTIATE_56
// if it is supported. An alternate name for this field is NTLMSSP_NEGOTIATE_56.
NTLMSSP_NEGOTIATE_56
)
func (f NegotiateFlag) Set(flags uint32) uint32 {
return flags | uint32(f)
}
func (f NegotiateFlag) IsSet(flags uint32) bool {
return (flags & uint32(f)) != 0
}
func (f NegotiateFlag) Unset(flags uint32) uint32 {
return flags &^ uint32(f)
}
func (f NegotiateFlag) String() string {
return reflect.TypeOf(f).Name()
}
func GetFlagName(flag NegotiateFlag) string {
nameMap := map[NegotiateFlag]string{
NTLMSSP_NEGOTIATE_56: "NTLMSSP_NEGOTIATE_56",
NTLMSSP_NEGOTIATE_KEY_EXCH: "NTLMSSP_NEGOTIATE_KEY_EXCH",
NTLMSSP_NEGOTIATE_128: "NTLMSSP_NEGOTIATE_128",
NTLMSSP_NEGOTIATE_VERSION: "NTLMSSP_NEGOTIATE_VERSION",
NTLMSSP_NEGOTIATE_TARGET_INFO: "NTLMSSP_NEGOTIATE_TARGET_INFO",
NTLMSSP_REQUEST_NON_NT_SESSION_KEY: "NTLMSSP_REQUEST_NON_NT_SESSION_KEY",
NTLMSSP_NEGOTIATE_IDENTIFY: "NTLMSSP_NEGOTIATE_IDENTIFY",
NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY: "NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY",
NTLMSSP_TARGET_TYPE_SERVER: "NTLMSSP_TARGET_TYPE_SERVER",
NTLMSSP_TARGET_TYPE_DOMAIN: "NTLMSSP_TARGET_TYPE_DOMAIN",
NTLMSSP_NEGOTIATE_ALWAYS_SIGN: "NTLMSSP_NEGOTIATE_ALWAYS_SIGN",
NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED: "NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED",
NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED: "NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED",
NTLMSSP_ANONYMOUS: "NTLMSSP_ANONYMOUS",
NTLMSSP_NEGOTIATE_NTLM: "NTLMSSP_NEGOTIATE_NTLM",
NTLMSSP_NEGOTIATE_LM_KEY: "NTLMSSP_NEGOTIATE_LM_KEY",
NTLMSSP_NEGOTIATE_DATAGRAM: "NTLMSSP_NEGOTIATE_DATAGRAM",
NTLMSSP_NEGOTIATE_SEAL: "NTLMSSP_NEGOTIATE_SEAL",
NTLMSSP_NEGOTIATE_SIGN: "NTLMSSP_NEGOTIATE_SIGN",
NTLMSSP_REQUEST_TARGET: "NTLMSSP_REQUEST_TARGET",
NTLM_NEGOTIATE_OEM: "NTLM_NEGOTIATE_OEM",
NTLMSSP_NEGOTIATE_UNICODE: "NTLMSSP_NEGOTIATE_UNICODE"}
return nameMap[flag]
}
func FlagsToString(flags uint32) string {
allFlags := [...]NegotiateFlag{
NTLMSSP_NEGOTIATE_56,
NTLMSSP_NEGOTIATE_KEY_EXCH,
NTLMSSP_NEGOTIATE_128,
NTLMSSP_NEGOTIATE_VERSION,
NTLMSSP_NEGOTIATE_TARGET_INFO,
NTLMSSP_REQUEST_NON_NT_SESSION_KEY,
NTLMSSP_NEGOTIATE_IDENTIFY,
NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY,
NTLMSSP_TARGET_TYPE_SERVER,
NTLMSSP_TARGET_TYPE_DOMAIN,
NTLMSSP_NEGOTIATE_ALWAYS_SIGN,
NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED,
NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED,
NTLMSSP_ANONYMOUS,
NTLMSSP_NEGOTIATE_NTLM,
NTLMSSP_NEGOTIATE_LM_KEY,
NTLMSSP_NEGOTIATE_DATAGRAM,
NTLMSSP_NEGOTIATE_SEAL,
NTLMSSP_NEGOTIATE_SIGN,
NTLMSSP_REQUEST_TARGET,
NTLM_NEGOTIATE_OEM,
NTLMSSP_NEGOTIATE_UNICODE}
var buffer bytes.Buffer
for i := range allFlags {
f := allFlags[i]
buffer.WriteString(fmt.Sprintf("%s: %v\n", GetFlagName(f), f.IsSet(flags)))
}
return buffer.String()
}

View File

@ -0,0 +1,127 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
// Package NTLM implements the interfaces used for interacting with NTLMv1 and NTLMv2.
// To create NTLM v1 or v2 sessions you would use CreateClientSession and create ClientServerSession.
package ntlm
import (
rc4P "crypto/rc4"
"errors"
)
type Version int
const (
Version1 Version = 1
Version2 Version = 2
)
type Mode int
const (
ConnectionlessMode Mode = iota
ConnectionOrientedMode
)
// Creates an NTLM v1 or v2 client
// mode - This must be ConnectionlessMode or ConnectionOrientedMode depending on what type of NTLM is used
// version - This must be Version1 or Version2 depending on the version of NTLM used
func CreateClientSession(version Version, mode Mode) (n ClientSession, err error) {
switch version {
case Version1:
n = new(V1ClientSession)
case Version2:
n = new(V2ClientSession)
default:
return nil, errors.New("Unknown NTLM Version, must be 1 or 2")
}
return n, nil
}
type ClientSession interface {
SetUserInfo(username string, password string, domain string)
SetMode(mode Mode)
GenerateNegotiateMessage() (*NegotiateMessage, error)
ProcessChallengeMessage(*ChallengeMessage) error
GenerateAuthenticateMessage() (*AuthenticateMessage, error)
Seal(message []byte) ([]byte, error)
Sign(message []byte) ([]byte, error)
Mac(message []byte, sequenceNumber int) ([]byte, error)
VerifyMac(message, expectedMac []byte, sequenceNumber int) (bool, error)
}
// Creates an NTLM v1 or v2 server
// mode - This must be ConnectionlessMode or ConnectionOrientedMode depending on what type of NTLM is used
// version - This must be Version1 or Version2 depending on the version of NTLM used
func CreateServerSession(version Version, mode Mode) (n ServerSession, err error) {
switch version {
case Version1:
n = new(V1ServerSession)
case Version2:
n = new(V2ServerSession)
default:
return nil, errors.New("Unknown NTLM Version, must be 1 or 2")
}
n.SetMode(mode)
return n, nil
}
type ServerSession interface {
SetUserInfo(username string, password string, domain string)
GetUserInfo() (string, string, string)
SetMode(mode Mode)
SetServerChallenge(challenge []byte)
ProcessNegotiateMessage(*NegotiateMessage) error
GenerateChallengeMessage() (*ChallengeMessage, error)
ProcessAuthenticateMessage(*AuthenticateMessage) error
GetSessionData() *SessionData
Version() int
Seal(message []byte) ([]byte, error)
Sign(message []byte) ([]byte, error)
Mac(message []byte, sequenceNumber int) ([]byte, error)
VerifyMac(message, expectedMac []byte, sequenceNumber int) (bool, error)
}
// This struct collects NTLM data structures and keys that are used across all types of NTLM requests
type SessionData struct {
mode Mode
user string
password string
userDomain string
NegotiateFlags uint32
negotiateMessage *NegotiateMessage
challengeMessage *ChallengeMessage
authenticateMessage *AuthenticateMessage
serverChallenge []byte
clientChallenge []byte
ntChallengeResponse []byte
lmChallengeResponse []byte
responseKeyLM []byte
responseKeyNT []byte
exportedSessionKey []byte
encryptedRandomSessionKey []byte
keyExchangeKey []byte
sessionBaseKey []byte
mic []byte
ClientSigningKey []byte
ServerSigningKey []byte
ClientSealingKey []byte
ServerSealingKey []byte
clientHandle *rc4P.Cipher
serverHandle *rc4P.Cipher
}

View File

@ -0,0 +1,392 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
"bytes"
rc4P "crypto/rc4"
"errors"
"log"
"strings"
)
/*******************************
Shared Session Data and Methods
*******************************/
type V1Session struct {
SessionData
}
func (n *V1Session) SetUserInfo(username string, password string, domain string) {
n.user = username
n.password = password
n.userDomain = domain
}
func (n *V1Session) GetUserInfo() (string, string, string) {
return n.user, n.password, n.userDomain
}
func (n *V1Session) SetMode(mode Mode) {
n.mode = mode
}
func (n *V1Session) Version() int {
return 1
}
func (n *V1Session) fetchResponseKeys() (err error) {
n.responseKeyLM, err = lmowfv1(n.password)
if err != nil {
return err
}
n.responseKeyNT = ntowfv1(n.password)
return
}
func (n *V1Session) computeExpectedResponses() (err error) {
if NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.IsSet(n.NegotiateFlags) {
n.ntChallengeResponse, err = desL(n.responseKeyNT, md5(concat(n.serverChallenge, n.clientChallenge))[0:8])
if err != nil {
return err
}
n.lmChallengeResponse = concat(n.clientChallenge, make([]byte, 16))
} else {
n.ntChallengeResponse, err = desL(n.responseKeyNT, n.serverChallenge)
if err != nil {
return err
}
// NoLMResponseNTLMv1: A Boolean setting that controls using the NTLM response for the LM
// response to the server challenge when NTLMv1 authentication is used.<30>
// <30> Section 3.1.1.1: The default value of this state variable is TRUE. Windows NT Server 4.0 SP3
// does not support providing NTLM instead of LM responses.
noLmResponseNtlmV1 := false
if noLmResponseNtlmV1 {
n.lmChallengeResponse = n.ntChallengeResponse
} else {
n.lmChallengeResponse, err = desL(n.responseKeyLM, n.serverChallenge)
if err != nil {
return err
}
}
}
return nil
}
func (n *V1Session) computeSessionBaseKey() (err error) {
n.sessionBaseKey = md4(n.responseKeyNT)
return
}
func (n *V1Session) computeKeyExchangeKey() (err error) {
if NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.IsSet(n.NegotiateFlags) {
n.keyExchangeKey = hmacMd5(n.sessionBaseKey, concat(n.serverChallenge, n.lmChallengeResponse[0:8]))
} else {
n.keyExchangeKey, err = kxKey(n.NegotiateFlags, n.sessionBaseKey, n.lmChallengeResponse, n.serverChallenge, n.responseKeyLM)
}
return
}
func (n *V1Session) calculateKeys(ntlmRevisionCurrent uint8) (err error) {
// This lovely piece of code comes courtesy of an the excellent Open Document support system from MSFT
// In order to calculate the keys correctly when the client has set the NTLMRevisionCurrent to 0xF (15)
// We must treat the flags as if NTLMSSP_NEGOTIATE_LM_KEY is set.
// This information is not contained (at least currently, until they correct it) in the MS-NLMP document
if ntlmRevisionCurrent == 15 {
n.NegotiateFlags = NTLMSSP_NEGOTIATE_LM_KEY.Set(n.NegotiateFlags)
}
n.ClientSigningKey = signKey(n.NegotiateFlags, n.exportedSessionKey, "Client")
n.ServerSigningKey = signKey(n.NegotiateFlags, n.exportedSessionKey, "Server")
n.ClientSealingKey = sealKey(n.NegotiateFlags, n.exportedSessionKey, "Client")
n.ServerSealingKey = sealKey(n.NegotiateFlags, n.exportedSessionKey, "Server")
return
}
func (n *V1Session) Seal(message []byte) ([]byte, error) {
return nil, nil
}
func (n *V1Session) Sign(message []byte) ([]byte, error) {
return nil, nil
}
func ntlmV1Mac(message []byte, sequenceNumber int, handle *rc4P.Cipher, sealingKey, signingKey []byte, NegotiateFlags uint32) []byte {
// TODO: Need to keep track of the sequence number for connection oriented NTLM
if NTLMSSP_NEGOTIATE_DATAGRAM.IsSet(NegotiateFlags) && NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.IsSet(NegotiateFlags) {
handle, _ = reinitSealingKey(sealingKey, sequenceNumber)
} else if NTLMSSP_NEGOTIATE_DATAGRAM.IsSet(NegotiateFlags) {
// CONOR: Reinitializing the rc4 cipher on every requst, but not using the
// algorithm as described in the MS-NTLM document. Just reinitialize it directly.
handle, _ = rc4Init(sealingKey)
}
sig := mac(NegotiateFlags, handle, signingKey, uint32(sequenceNumber), message)
return sig.Bytes()
}
func (n *V1ServerSession) Mac(message []byte, sequenceNumber int) ([]byte, error) {
mac := ntlmV1Mac(message, sequenceNumber, n.serverHandle, n.ServerSealingKey, n.ServerSigningKey, n.NegotiateFlags)
return mac, nil
}
func (n *V1ClientSession) Mac(message []byte, sequenceNumber int) ([]byte, error) {
mac := ntlmV1Mac(message, sequenceNumber, n.clientHandle, n.ClientSealingKey, n.ClientSigningKey, n.NegotiateFlags)
return mac, nil
}
func (n *V1ServerSession) VerifyMac(message, expectedMac []byte, sequenceNumber int) (bool, error) {
mac := ntlmV1Mac(message, sequenceNumber, n.clientHandle, n.ClientSealingKey, n.ClientSigningKey, n.NegotiateFlags)
return MacsEqual(mac, expectedMac), nil
}
func (n *V1ClientSession) VerifyMac(message, expectedMac []byte, sequenceNumber int) (bool, error) {
mac := ntlmV1Mac(message, sequenceNumber, n.serverHandle, n.ServerSealingKey, n.ServerSigningKey, n.NegotiateFlags)
return MacsEqual(mac, expectedMac), nil
}
/**************
Server Session
**************/
type V1ServerSession struct {
V1Session
}
func (n *V1ServerSession) ProcessNegotiateMessage(nm *NegotiateMessage) (err error) {
n.negotiateMessage = nm
return
}
func (n *V1ServerSession) GenerateChallengeMessage() (cm *ChallengeMessage, err error) {
// TODO: Generate this challenge message
return
}
func (n *V1ServerSession) SetServerChallenge(challenge []byte) {
n.serverChallenge = challenge
}
func (n *V1ServerSession) GetSessionData() *SessionData {
return &n.SessionData
}
func (n *V1ServerSession) ProcessAuthenticateMessage(am *AuthenticateMessage) (err error) {
n.authenticateMessage = am
n.NegotiateFlags = am.NegotiateFlags
n.clientChallenge = am.ClientChallenge()
n.encryptedRandomSessionKey = am.EncryptedRandomSessionKey.Payload
// Ignore the values used in SetUserInfo and use these instead from the authenticate message
// They should always be correct (I hope)
n.user = am.UserName.String()
n.userDomain = am.DomainName.String()
log.Printf("(ProcessAuthenticateMessage)NTLM v1 User %s Domain %s", n.user, n.userDomain)
err = n.fetchResponseKeys()
if err != nil {
return err
}
err = n.computeExpectedResponses()
if err != nil {
return err
}
err = n.computeSessionBaseKey()
if err != nil {
return err
}
err = n.computeKeyExchangeKey()
if err != nil {
return err
}
if !bytes.Equal(am.NtChallengeResponseFields.Payload, n.ntChallengeResponse) {
// There is a bug with the steps in MS-NLMP. In section 3.2.5.1.2 it says you should fall through
// to compare the lmChallengeResponse if the ntChallengeRepsonse fails, but with extended session security
// this would *always* pass because the lmChallengeResponse and expectedLmChallengeRepsonse will always
// be the same
if !bytes.Equal(am.LmChallengeResponse.Payload, n.lmChallengeResponse) || NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.IsSet(n.NegotiateFlags) {
return errors.New("Could not authenticate")
}
}
n.mic = am.Mic
am.Mic = zeroBytes(16)
err = n.computeExportedSessionKey()
if err != nil {
return err
}
if am.Version == nil {
//UGH not entirely sure how this could possibly happen, going to put this in for now
//TODO investigate if this ever is really happening
am.Version = &VersionStruct{ProductMajorVersion: uint8(5), ProductMinorVersion: uint8(1), ProductBuild: uint16(2600), NTLMRevisionCurrent: uint8(15)}
log.Printf("Nil version in ntlmv1")
}
err = n.calculateKeys(am.Version.NTLMRevisionCurrent)
if err != nil {
return err
}
n.clientHandle, err = rc4Init(n.ClientSealingKey)
if err != nil {
return err
}
n.serverHandle, err = rc4Init(n.ServerSealingKey)
if err != nil {
return err
}
return nil
}
func (n *V1ServerSession) computeExportedSessionKey() (err error) {
if NTLMSSP_NEGOTIATE_KEY_EXCH.IsSet(n.NegotiateFlags) {
n.exportedSessionKey, err = rc4K(n.keyExchangeKey, n.encryptedRandomSessionKey)
if err != nil {
return err
}
// TODO: Calculate mic correctly. This calculation is not producing the right results now
// n.calculatedMic = HmacMd5(n.exportedSessionKey, concat(n.challengeMessage.Payload, n.authenticateMessage.Bytes))
} else {
n.exportedSessionKey = n.keyExchangeKey
// TODO: Calculate mic correctly. This calculation is not producing the right results now
// n.calculatedMic = HmacMd5(n.keyExchangeKey, concat(n.challengeMessage.Payload, n.authenticateMessage.Bytes))
}
return nil
}
/*************
Client Session
**************/
type V1ClientSession struct {
V1Session
}
func (n *V1ClientSession) GenerateNegotiateMessage() (nm *NegotiateMessage, err error) {
return nil, nil
}
func (n *V1ClientSession) ProcessChallengeMessage(cm *ChallengeMessage) (err error) {
n.challengeMessage = cm
n.serverChallenge = cm.ServerChallenge
n.clientChallenge = randomBytes(8)
// Set up the default flags for processing the response. These are the flags that we will return
// in the authenticate message
flags := uint32(0)
flags = NTLMSSP_NEGOTIATE_KEY_EXCH.Set(flags)
// NOTE: Unsetting this flag in order to get the server to generate the signatures we can recognize
flags = NTLMSSP_NEGOTIATE_VERSION.Set(flags)
flags = NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.Set(flags)
flags = NTLMSSP_NEGOTIATE_TARGET_INFO.Set(flags)
flags = NTLMSSP_NEGOTIATE_IDENTIFY.Set(flags)
flags = NTLMSSP_NEGOTIATE_ALWAYS_SIGN.Set(flags)
flags = NTLMSSP_NEGOTIATE_NTLM.Set(flags)
flags = NTLMSSP_NEGOTIATE_DATAGRAM.Set(flags)
flags = NTLMSSP_NEGOTIATE_SIGN.Set(flags)
flags = NTLMSSP_REQUEST_TARGET.Set(flags)
flags = NTLMSSP_NEGOTIATE_UNICODE.Set(flags)
n.NegotiateFlags = flags
err = n.fetchResponseKeys()
if err != nil {
return err
}
err = n.computeExpectedResponses()
if err != nil {
return err
}
err = n.computeSessionBaseKey()
if err != nil {
return err
}
err = n.computeKeyExchangeKey()
if err != nil {
return err
}
err = n.computeEncryptedSessionKey()
if err != nil {
return err
}
err = n.calculateKeys(cm.Version.NTLMRevisionCurrent)
if err != nil {
return err
}
n.clientHandle, err = rc4Init(n.ClientSealingKey)
if err != nil {
return err
}
n.serverHandle, err = rc4Init(n.ServerSealingKey)
if err != nil {
return err
}
return nil
}
func (n *V1ClientSession) GenerateAuthenticateMessage() (am *AuthenticateMessage, err error) {
am = new(AuthenticateMessage)
am.Signature = []byte("NTLMSSP\x00")
am.MessageType = uint32(3)
am.LmChallengeResponse, _ = CreateBytePayload(n.lmChallengeResponse)
am.NtChallengeResponseFields, _ = CreateBytePayload(n.ntChallengeResponse)
am.DomainName, _ = CreateStringPayload(n.userDomain)
am.UserName, _ = CreateStringPayload(n.user)
am.Workstation, _ = CreateStringPayload("SQUAREMILL")
am.EncryptedRandomSessionKey, _ = CreateBytePayload(n.encryptedRandomSessionKey)
am.NegotiateFlags = n.NegotiateFlags
am.Version = &VersionStruct{ProductMajorVersion: uint8(5), ProductMinorVersion: uint8(1), ProductBuild: uint16(2600), NTLMRevisionCurrent: uint8(15)}
return am, nil
}
func (n *V1ClientSession) computeEncryptedSessionKey() (err error) {
if NTLMSSP_NEGOTIATE_KEY_EXCH.IsSet(n.NegotiateFlags) {
n.exportedSessionKey = randomBytes(16)
n.encryptedRandomSessionKey, err = rc4K(n.keyExchangeKey, n.exportedSessionKey)
if err != nil {
return err
}
} else {
n.encryptedRandomSessionKey = n.keyExchangeKey
}
return nil
}
/********************************
NTLM V1 Password hash functions
*********************************/
func ntowfv1(passwd string) []byte {
return md4(utf16FromString(passwd))
}
// ConcatenationOf( DES( UpperCase( Passwd)[0..6],"KGS!@#$%"), DES( UpperCase( Passwd)[7..13],"KGS!@#$%"))
func lmowfv1(passwd string) ([]byte, error) {
asciiPassword := []byte(strings.ToUpper(passwd))
keyBytes := zeroPaddedBytes(asciiPassword, 0, 14)
first, err := des(keyBytes[0:7], []byte("KGS!@#$%"))
if err != nil {
return nil, err
}
second, err := des(keyBytes[7:14], []byte("KGS!@#$%"))
if err != nil {
return nil, err
}
return append(first, second...), nil
}

View File

@ -0,0 +1,408 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
"bytes"
rc4P "crypto/rc4"
"encoding/binary"
"errors"
"log"
"strings"
"time"
)
/*******************************
Shared Session Data and Methods
*******************************/
type V2Session struct {
SessionData
}
func (n *V2Session) SetUserInfo(username string, password string, domain string) {
n.user = username
n.password = password
n.userDomain = domain
}
func (n *V2Session) GetUserInfo() (string, string, string) {
return n.user, n.password, n.userDomain
}
func (n *V2Session) SetMode(mode Mode) {
n.mode = mode
}
func (n *V2Session) Version() int {
return 2
}
func (n *V2Session) fetchResponseKeys() (err error) {
// Usually at this point we'd go out to Active Directory and get these keys
// Here we are assuming we have the information locally
n.responseKeyLM = lmowfv2(n.user, n.password, n.userDomain)
n.responseKeyNT = ntowfv2(n.user, n.password, n.userDomain)
return
}
func (n *V2ServerSession) GetSessionData() *SessionData {
return &n.SessionData
}
// Define ComputeResponse(NegFlg, ResponseKeyNT, ResponseKeyLM, CHALLENGE_MESSAGE.ServerChallenge, ClientChallenge, Time, ServerName)
// ServerNameBytes - The NtChallengeResponseFields.NTLMv2_RESPONSE.NTLMv2_CLIENT_CHALLENGE.AvPairs field structure of the AUTHENTICATE_MESSAGE payload.
func (n *V2Session) computeExpectedResponses(timestamp []byte, avPairBytes []byte) (err error) {
temp := concat([]byte{0x01}, []byte{0x01}, zeroBytes(6), timestamp, n.clientChallenge, zeroBytes(4), avPairBytes, zeroBytes(4))
ntProofStr := hmacMd5(n.responseKeyNT, concat(n.serverChallenge, temp))
n.ntChallengeResponse = concat(ntProofStr, temp)
n.lmChallengeResponse = concat(hmacMd5(n.responseKeyLM, concat(n.serverChallenge, n.clientChallenge)), n.clientChallenge)
n.sessionBaseKey = hmacMd5(n.responseKeyNT, ntProofStr)
return
}
func (n *V2Session) computeKeyExchangeKey() (err error) {
n.keyExchangeKey = n.sessionBaseKey
return
}
func (n *V2Session) calculateKeys(ntlmRevisionCurrent uint8) (err error) {
// This lovely piece of code comes courtesy of an the excellent Open Document support system from MSFT
// In order to calculate the keys correctly when the client has set the NTLMRevisionCurrent to 0xF (15)
// We must treat the flags as if NTLMSSP_NEGOTIATE_LM_KEY is set.
// This information is not contained (at least currently, until they correct it) in the MS-NLMP document
if ntlmRevisionCurrent == 15 {
n.NegotiateFlags = NTLMSSP_NEGOTIATE_LM_KEY.Set(n.NegotiateFlags)
}
n.ClientSigningKey = signKey(n.NegotiateFlags, n.exportedSessionKey, "Client")
n.ServerSigningKey = signKey(n.NegotiateFlags, n.exportedSessionKey, "Server")
n.ClientSealingKey = sealKey(n.NegotiateFlags, n.exportedSessionKey, "Client")
n.ServerSealingKey = sealKey(n.NegotiateFlags, n.exportedSessionKey, "Server")
return
}
func (n *V2Session) Seal(message []byte) ([]byte, error) {
return nil, nil
}
func (n *V2Session) Sign(message []byte) ([]byte, error) {
return nil, nil
}
//Mildly ghetto that we expose this
func NtlmVCommonMac(message []byte, sequenceNumber int, sealingKey, signingKey []byte, NegotiateFlags uint32) []byte {
var handle *rc4P.Cipher
// TODO: Need to keep track of the sequence number for connection oriented NTLM
if NTLMSSP_NEGOTIATE_DATAGRAM.IsSet(NegotiateFlags) && NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.IsSet(NegotiateFlags) {
handle, _ = reinitSealingKey(sealingKey, sequenceNumber)
} else if NTLMSSP_NEGOTIATE_DATAGRAM.IsSet(NegotiateFlags) {
// CONOR: Reinitializing the rc4 cipher on every requst, but not using the
// algorithm as described in the MS-NTLM document. Just reinitialize it directly.
handle, _ = rc4Init(sealingKey)
}
sig := mac(NegotiateFlags, handle, signingKey, uint32(sequenceNumber), message)
return sig.Bytes()
}
func NtlmV2Mac(message []byte, sequenceNumber int, handle *rc4P.Cipher, sealingKey, signingKey []byte, NegotiateFlags uint32) []byte {
// TODO: Need to keep track of the sequence number for connection oriented NTLM
if NTLMSSP_NEGOTIATE_DATAGRAM.IsSet(NegotiateFlags) && NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.IsSet(NegotiateFlags) {
handle, _ = reinitSealingKey(sealingKey, sequenceNumber)
} else if NTLMSSP_NEGOTIATE_DATAGRAM.IsSet(NegotiateFlags) {
// CONOR: Reinitializing the rc4 cipher on every requst, but not using the
// algorithm as described in the MS-NTLM document. Just reinitialize it directly.
handle, _ = rc4Init(sealingKey)
}
sig := mac(NegotiateFlags, handle, signingKey, uint32(sequenceNumber), message)
return sig.Bytes()
}
func (n *V2ServerSession) Mac(message []byte, sequenceNumber int) ([]byte, error) {
mac := NtlmV2Mac(message, sequenceNumber, n.serverHandle, n.ServerSealingKey, n.ServerSigningKey, n.NegotiateFlags)
return mac, nil
}
func (n *V2ServerSession) VerifyMac(message, expectedMac []byte, sequenceNumber int) (bool, error) {
mac := NtlmV2Mac(message, sequenceNumber, n.clientHandle, n.ClientSealingKey, n.ClientSigningKey, n.NegotiateFlags)
return MacsEqual(mac, expectedMac), nil
}
func (n *V2ClientSession) Mac(message []byte, sequenceNumber int) ([]byte, error) {
mac := NtlmV2Mac(message, sequenceNumber, n.clientHandle, n.ClientSealingKey, n.ClientSigningKey, n.NegotiateFlags)
return mac, nil
}
func (n *V2ClientSession) VerifyMac(message, expectedMac []byte, sequenceNumber int) (bool, error) {
mac := NtlmV2Mac(message, sequenceNumber, n.serverHandle, n.ServerSealingKey, n.ServerSigningKey, n.NegotiateFlags)
return MacsEqual(mac, expectedMac), nil
}
/**************
Server Session
**************/
type V2ServerSession struct {
V2Session
}
func (n *V2ServerSession) SetServerChallenge(challenge []byte) {
n.serverChallenge = challenge
}
func (n *V2ServerSession) ProcessNegotiateMessage(nm *NegotiateMessage) (err error) {
n.negotiateMessage = nm
return
}
func (n *V2ServerSession) GenerateChallengeMessage() (cm *ChallengeMessage, err error) {
cm = new(ChallengeMessage)
cm.Signature = []byte("NTLMSSP\x00")
cm.MessageType = uint32(2)
cm.TargetName, _ = CreateBytePayload(make([]byte, 0))
flags := uint32(0)
flags = NTLMSSP_NEGOTIATE_KEY_EXCH.Set(flags)
flags = NTLMSSP_NEGOTIATE_VERSION.Set(flags)
flags = NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.Set(flags)
flags = NTLMSSP_NEGOTIATE_TARGET_INFO.Set(flags)
flags = NTLMSSP_NEGOTIATE_IDENTIFY.Set(flags)
flags = NTLMSSP_NEGOTIATE_ALWAYS_SIGN.Set(flags)
flags = NTLMSSP_NEGOTIATE_NTLM.Set(flags)
flags = NTLMSSP_NEGOTIATE_DATAGRAM.Set(flags)
flags = NTLMSSP_NEGOTIATE_SIGN.Set(flags)
flags = NTLMSSP_REQUEST_TARGET.Set(flags)
flags = NTLMSSP_NEGOTIATE_UNICODE.Set(flags)
flags = NTLMSSP_NEGOTIATE_128.Set(flags)
cm.NegotiateFlags = flags
n.serverChallenge = randomBytes(8)
cm.ServerChallenge = n.serverChallenge
cm.Reserved = make([]byte, 8)
// Create the AvPairs we need
pairs := new(AvPairs)
pairs.AddAvPair(MsvAvNbDomainName, utf16FromString("REUTERS"))
pairs.AddAvPair(MsvAvNbComputerName, utf16FromString("UKBP-CBTRMFE06"))
pairs.AddAvPair(MsvAvDnsDomainName, utf16FromString("Reuters.net"))
pairs.AddAvPair(MsvAvDnsComputerName, utf16FromString("ukbp-cbtrmfe06.Reuters.net"))
pairs.AddAvPair(MsvAvDnsTreeName, utf16FromString("Reuters.net"))
pairs.AddAvPair(MsvAvEOL, make([]byte, 0))
cm.TargetInfo = pairs
cm.TargetInfoPayloadStruct, _ = CreateBytePayload(pairs.Bytes())
cm.Version = &VersionStruct{ProductMajorVersion: uint8(5), ProductMinorVersion: uint8(1), ProductBuild: uint16(2600), NTLMRevisionCurrent: uint8(15)}
return cm, nil
}
func (n *V2ServerSession) ProcessAuthenticateMessage(am *AuthenticateMessage) (err error) {
n.authenticateMessage = am
n.NegotiateFlags = am.NegotiateFlags
n.clientChallenge = am.ClientChallenge()
n.encryptedRandomSessionKey = am.EncryptedRandomSessionKey.Payload
// Ignore the values used in SetUserInfo and use these instead from the authenticate message
// They should always be correct (I hope)
n.user = am.UserName.String()
n.userDomain = am.DomainName.String()
log.Printf("(ProcessAuthenticateMessage)NTLM v2 User %s Domain %s", n.user, n.userDomain)
err = n.fetchResponseKeys()
if err != nil {
return err
}
timestamp := am.NtlmV2Response.NtlmV2ClientChallenge.TimeStamp
avPairsBytes := am.NtlmV2Response.NtlmV2ClientChallenge.AvPairs.Bytes()
err = n.computeExpectedResponses(timestamp, avPairsBytes)
if err != nil {
return err
}
if !bytes.Equal(am.NtChallengeResponseFields.Payload, n.ntChallengeResponse) {
if !bytes.Equal(am.LmChallengeResponse.Payload, n.lmChallengeResponse) {
return errors.New("Could not authenticate")
}
}
err = n.computeKeyExchangeKey()
if err != nil {
return err
}
n.mic = am.Mic
am.Mic = zeroBytes(16)
err = n.computeExportedSessionKey()
if err != nil {
return err
}
if am.Version == nil {
//UGH not entirely sure how this could possibly happen, going to put this in for now
//TODO investigate if this ever is really happening
am.Version = &VersionStruct{ProductMajorVersion: uint8(5), ProductMinorVersion: uint8(1), ProductBuild: uint16(2600), NTLMRevisionCurrent: uint8(15)}
log.Printf("Nil version in ntlmv2")
}
err = n.calculateKeys(am.Version.NTLMRevisionCurrent)
if err != nil {
return err
}
n.clientHandle, err = rc4Init(n.ClientSealingKey)
if err != nil {
return err
}
n.serverHandle, err = rc4Init(n.ServerSealingKey)
if err != nil {
return err
}
return nil
}
func (n *V2ServerSession) computeExportedSessionKey() (err error) {
if NTLMSSP_NEGOTIATE_KEY_EXCH.IsSet(n.NegotiateFlags) {
n.exportedSessionKey, err = rc4K(n.keyExchangeKey, n.encryptedRandomSessionKey)
if err != nil {
return err
}
// TODO: Calculate mic correctly. This calculation is not producing the right results now
// n.calculatedMic = HmacMd5(n.exportedSessionKey, concat(n.challengeMessage.Payload, n.authenticateMessage.Bytes))
} else {
n.exportedSessionKey = n.keyExchangeKey
// TODO: Calculate mic correctly. This calculation is not producing the right results now
// n.calculatedMic = HmacMd5(n.keyExchangeKey, concat(n.challengeMessage.Payload, n.authenticateMessage.Bytes))
}
return nil
}
/*************
Client Session
**************/
type V2ClientSession struct {
V2Session
}
func (n *V2ClientSession) GenerateNegotiateMessage() (nm *NegotiateMessage, err error) {
return nil, nil
}
func (n *V2ClientSession) ProcessChallengeMessage(cm *ChallengeMessage) (err error) {
n.challengeMessage = cm
n.serverChallenge = cm.ServerChallenge
n.clientChallenge = randomBytes(8)
// Set up the default flags for processing the response. These are the flags that we will return
// in the authenticate message
flags := uint32(0)
flags = NTLMSSP_NEGOTIATE_KEY_EXCH.Set(flags)
flags = NTLMSSP_NEGOTIATE_VERSION.Set(flags)
flags = NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.Set(flags)
flags = NTLMSSP_NEGOTIATE_TARGET_INFO.Set(flags)
flags = NTLMSSP_NEGOTIATE_IDENTIFY.Set(flags)
flags = NTLMSSP_NEGOTIATE_ALWAYS_SIGN.Set(flags)
flags = NTLMSSP_NEGOTIATE_NTLM.Set(flags)
flags = NTLMSSP_NEGOTIATE_DATAGRAM.Set(flags)
flags = NTLMSSP_NEGOTIATE_SIGN.Set(flags)
flags = NTLMSSP_REQUEST_TARGET.Set(flags)
flags = NTLMSSP_NEGOTIATE_UNICODE.Set(flags)
flags = NTLMSSP_NEGOTIATE_128.Set(flags)
n.NegotiateFlags = flags
err = n.fetchResponseKeys()
if err != nil {
return err
}
timestamp := timeToWindowsFileTime(time.Now())
err = n.computeExpectedResponses(timestamp, cm.TargetInfoPayloadStruct.Payload)
if err != nil {
return err
}
err = n.computeKeyExchangeKey()
if err != nil {
return err
}
err = n.computeEncryptedSessionKey()
if err != nil {
return err
}
err = n.calculateKeys(cm.Version.NTLMRevisionCurrent)
if err != nil {
return err
}
n.clientHandle, err = rc4Init(n.ClientSealingKey)
if err != nil {
return err
}
n.serverHandle, err = rc4Init(n.ServerSealingKey)
if err != nil {
return err
}
return nil
}
func (n *V2ClientSession) GenerateAuthenticateMessage() (am *AuthenticateMessage, err error) {
am = new(AuthenticateMessage)
am.Signature = []byte("NTLMSSP\x00")
am.MessageType = uint32(3)
am.LmChallengeResponse, _ = CreateBytePayload(n.lmChallengeResponse)
am.NtChallengeResponseFields, _ = CreateBytePayload(n.ntChallengeResponse)
am.DomainName, _ = CreateStringPayload(n.userDomain)
am.UserName, _ = CreateStringPayload(n.user)
am.Workstation, _ = CreateStringPayload("SQUAREMILL")
am.EncryptedRandomSessionKey, _ = CreateBytePayload(n.encryptedRandomSessionKey)
am.NegotiateFlags = n.NegotiateFlags
am.Mic = make([]byte, 16)
am.Version = &VersionStruct{ProductMajorVersion: uint8(5), ProductMinorVersion: uint8(1), ProductBuild: uint16(2600), NTLMRevisionCurrent: 0x0F}
return am, nil
}
func (n *V2ClientSession) computeEncryptedSessionKey() (err error) {
if NTLMSSP_NEGOTIATE_KEY_EXCH.IsSet(n.NegotiateFlags) {
n.exportedSessionKey = randomBytes(16)
n.encryptedRandomSessionKey, err = rc4K(n.keyExchangeKey, n.exportedSessionKey)
if err != nil {
return err
}
} else {
n.encryptedRandomSessionKey = n.keyExchangeKey
}
return nil
}
/********************************
NTLM V2 Password hash functions
*********************************/
// Define ntowfv2(Passwd, User, UserDom) as
func ntowfv2(user string, passwd string, userDom string) []byte {
concat := utf16FromString(strings.ToUpper(user) + userDom)
return hmacMd5(md4(utf16FromString(passwd)), concat)
}
// Define lmowfv2(Passwd, User, UserDom) as
func lmowfv2(user string, passwd string, userDom string) []byte {
return ntowfv2(user, passwd, userDom)
}
/********************************
Helper functions
*********************************/
func timeToWindowsFileTime(t time.Time) []byte {
var ll int64
ll = (int64(t.Unix()) * int64(10000000)) + int64(116444736000000000)
buffer := bytes.NewBuffer(make([]byte, 0, 8))
binary.Write(buffer, binary.LittleEndian, ll)
return buffer.Bytes()
}

View File

@ -0,0 +1,94 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
"bytes"
"encoding/binary"
"encoding/hex"
)
const (
UnicodeStringPayload = iota
OemStringPayload
BytesPayload
)
type PayloadStruct struct {
Type int
Len uint16
MaxLen uint16
Offset uint32
Payload []byte
}
func (p *PayloadStruct) Bytes() []byte {
dest := make([]byte, 0, 8)
buffer := bytes.NewBuffer(dest)
binary.Write(buffer, binary.LittleEndian, p.Len)
binary.Write(buffer, binary.LittleEndian, p.MaxLen)
binary.Write(buffer, binary.LittleEndian, p.Offset)
return buffer.Bytes()
}
func (p *PayloadStruct) String() string {
var returnString string
switch p.Type {
case UnicodeStringPayload:
returnString = utf16ToString(p.Payload)
case OemStringPayload:
returnString = string(p.Payload)
case BytesPayload:
returnString = hex.EncodeToString(p.Payload)
default:
returnString = "unknown type"
}
return returnString
}
func CreateBytePayload(bytes []byte) (*PayloadStruct, error) {
p := new(PayloadStruct)
p.Type = BytesPayload
p.Len = uint16(len(bytes))
p.MaxLen = uint16(len(bytes))
p.Payload = bytes // TODO: Copy these bytes instead of keeping a reference
return p, nil
}
func CreateStringPayload(value string) (*PayloadStruct, error) {
// Create UTF16 unicode bytes from string
bytes := utf16FromString(value)
p := new(PayloadStruct)
p.Type = UnicodeStringPayload
p.Len = uint16(len(bytes))
p.MaxLen = uint16(len(bytes))
p.Payload = bytes // TODO: Copy these bytes instead of keeping a reference
return p, nil
}
func ReadStringPayload(startByte int, bytes []byte) (*PayloadStruct, error) {
return ReadPayloadStruct(startByte, bytes, UnicodeStringPayload)
}
func ReadBytePayload(startByte int, bytes []byte) (*PayloadStruct, error) {
return ReadPayloadStruct(startByte, bytes, BytesPayload)
}
func ReadPayloadStruct(startByte int, bytes []byte, PayloadType int) (*PayloadStruct, error) {
p := new(PayloadStruct)
p.Type = PayloadType
p.Len = binary.LittleEndian.Uint16(bytes[startByte : startByte+2])
p.MaxLen = binary.LittleEndian.Uint16(bytes[startByte+2 : startByte+4])
p.Offset = binary.LittleEndian.Uint32(bytes[startByte+4 : startByte+8])
if p.Len > 0 {
endOffset := p.Offset + uint32(p.Len)
p.Payload = bytes[p.Offset:endOffset]
}
return p, nil
}

View File

@ -0,0 +1,120 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
rc4P "crypto/rc4"
"encoding/binary"
"encoding/hex"
"fmt"
)
type NtlmsspMessageSignature struct {
ByteData []byte
// A 32-bit unsigned integer that contains the signature version. This field MUST be 0x00000001.
Version []byte
// A 4-byte array that contains the random pad for the message.
RandomPad []byte
// A 4-byte array that contains the checksum for the message.
CheckSum []byte
// A 32-bit unsigned integer that contains the NTLM sequence number for this application message.
SeqNum []byte
}
func (n *NtlmsspMessageSignature) String() string {
return fmt.Sprintf("NtlmsspMessageSignature: %s", hex.EncodeToString(n.Bytes()))
}
func (n *NtlmsspMessageSignature) Bytes() []byte {
if n.ByteData != nil {
return n.ByteData
} else {
return concat(n.Version, n.RandomPad, n.CheckSum, n.SeqNum)
}
return nil
}
// Define SEAL(Handle, SigningKey, SeqNum, Message) as
func seal(negFlags uint32, handle *rc4P.Cipher, signingKey []byte, seqNum uint32, message []byte) (sealedMessage []byte, sig *NtlmsspMessageSignature) {
sealedMessage = rc4(handle, message)
sig = mac(negFlags, handle, signingKey, uint32(seqNum), message)
return
}
// Define SIGN(Handle, SigningKey, SeqNum, Message) as
func sign(negFlags uint32, handle *rc4P.Cipher, signingKey []byte, seqNum uint32, message []byte) []byte {
return concat(message, mac(negFlags, handle, signingKey, uint32(seqNum), message).Bytes())
}
func mac(negFlags uint32, handle *rc4P.Cipher, signingKey []byte, seqNum uint32, message []byte) (result *NtlmsspMessageSignature) {
if NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY.IsSet(negFlags) {
result = macWithExtendedSessionSecurity(negFlags, handle, signingKey, seqNum, message)
} else {
result = macWithoutExtendedSessionSecurity(handle, seqNum, message)
}
return result
}
// Define MAC(Handle, SigningKey, SeqNum, Message) as
// Set NTLMSSP_MESSAGE_SIGNATURE.Version to 0x00000001
// Set NTLMSSP_MESSAGE_SIGNATURE.Checksum to CRC32(Message)
// Set NTLMSSP_MESSAGE_SIGNATURE.RandomPad RC4(Handle, RandomPad)
// Set NTLMSSP_MESSAGE_SIGNATURE.Checksum to RC4(Handle, NTLMSSP_MESSAGE_SIGNATURE.Checksum)
// Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to RC4(Handle, 0x00000000)
// If (connection oriented)
// Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to NTLMSSP_MESSAGE_SIGNATURE.SeqNum XOR SeqNum
// Set SeqNum to SeqNum + 1
// Else
// Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to NTLMSSP_MESSAGE_SIGNATURE.SeqNum XOR (application supplied SeqNum)
// EndIf
// Set NTLMSSP_MESSAGE_SIGNATURE.RandomPad to 0
// End
func macWithoutExtendedSessionSecurity(handle *rc4P.Cipher, seqNum uint32, message []byte) *NtlmsspMessageSignature {
sig := new(NtlmsspMessageSignature)
seqNumBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(seqNumBytes, seqNum)
sig.Version = []byte{0x01, 0x00, 0x00, 0x00}
sig.CheckSum = make([]byte, 4)
binary.LittleEndian.PutUint32(sig.CheckSum, crc32(message))
sig.RandomPad = rc4(handle, zeroBytes(4))
sig.CheckSum = rc4(handle, sig.CheckSum)
sig.SeqNum = rc4(handle, zeroBytes(4))
for i := 0; i < 4; i++ {
sig.SeqNum[i] = sig.SeqNum[i] ^ seqNumBytes[i]
}
sig.RandomPad = zeroBytes(4)
return sig
}
// Define MAC(Handle, SigningKey, SeqNum, Message) as
// Set NTLMSSP_MESSAGE_SIGNATURE.Version to 0x00000001
// if Key Exchange Key Negotiated
// Set NTLMSSP_MESSAGE_SIGNATURE.Checksum to RC4(Handle, HMAC_MD5(SigningKey, ConcatenationOf(SeqNum, Message))[0..7])
// else
// Set NTLMSSP_MESSAGE_SIGNATURE.Checksum to HMAC_MD5(SigningKey, ConcatenationOf(SeqNum, Message))[0..7]
// end
// Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to SeqNum
// Set SeqNum to SeqNum + 1
// EndDefine
func macWithExtendedSessionSecurity(negFlags uint32, handle *rc4P.Cipher, signingKey []byte, seqNum uint32, message []byte) *NtlmsspMessageSignature {
sig := new(NtlmsspMessageSignature)
sig.Version = []byte{0x01, 0x00, 0x00, 0x00}
seqNumBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(seqNumBytes, seqNum)
sig.CheckSum = hmacMd5(signingKey, concat(seqNumBytes, message))[0:8]
if NTLMSSP_NEGOTIATE_KEY_EXCH.IsSet(negFlags) {
sig.CheckSum = rc4(handle, sig.CheckSum)
}
sig.SeqNum = seqNumBytes
return sig
}
func reinitSealingKey(key []byte, sequenceNumber int) (handle *rc4P.Cipher, err error) {
seqNumBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(seqNumBytes, uint32(sequenceNumber))
newKey := md5(concat(key, seqNumBytes))
handle, err = rc4Init(newKey)
return handle, err
}

View File

@ -0,0 +1,46 @@
//Copyright 2013 Thomson Reuters Global Resources. BSD License please see License file for more information
package ntlm
import (
"bytes"
"encoding/binary"
"fmt"
)
type VersionStruct struct {
ProductMajorVersion uint8
ProductMinorVersion uint8
ProductBuild uint16
Reserved []byte
NTLMRevisionCurrent uint8
}
func ReadVersionStruct(structSource []byte) (*VersionStruct, error) {
versionStruct := new(VersionStruct)
versionStruct.ProductMajorVersion = uint8(structSource[0])
versionStruct.ProductMinorVersion = uint8(structSource[1])
versionStruct.ProductBuild = binary.LittleEndian.Uint16(structSource[2:4])
versionStruct.Reserved = structSource[4:7]
versionStruct.NTLMRevisionCurrent = uint8(structSource[7])
return versionStruct, nil
}
func (v *VersionStruct) String() string {
return fmt.Sprintf("%d.%d.%d Ntlm %d", v.ProductMajorVersion, v.ProductMinorVersion, v.ProductBuild, v.NTLMRevisionCurrent)
}
func (v *VersionStruct) Bytes() []byte {
dest := make([]byte, 0, 8)
buffer := bytes.NewBuffer(dest)
binary.Write(buffer, binary.LittleEndian, v.ProductMajorVersion)
binary.Write(buffer, binary.LittleEndian, v.ProductMinorVersion)
binary.Write(buffer, binary.LittleEndian, v.ProductBuild)
buffer.Write(make([]byte, 3))
binary.Write(buffer, binary.LittleEndian, uint8(v.NTLMRevisionCurrent))
return buffer.Bytes()
}

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Vadim Ivanou
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,45 @@
package httpntlm
import (
"encoding/base64"
"encoding/binary"
)
const (
negotiateUnicode = 0x0001 // Text strings are in unicode
negotiateOEM = 0x0002 // Text strings are in OEM
requestTarget = 0x0004 // Server return its auth realm
negotiateSign = 0x0010 // Request signature capability
negotiateSeal = 0x0020 // Request confidentiality
negotiateLMKey = 0x0080 // Generate session key
negotiateNTLM = 0x0200 // NTLM authentication
negotiateLocalCall = 0x4000 // client/server on same machine
negotiateAlwaysSign = 0x8000 // Sign for all security levels
negotiateIdentify = 0x80000
)
var (
put32 = binary.LittleEndian.PutUint32
put16 = binary.LittleEndian.PutUint16
encBase64 = base64.StdEncoding.EncodeToString
decBase64 = base64.StdEncoding.DecodeString
)
// generates NTLM Negotiate type-1 message
// for details see http://www.innovation.ch/personal/ronald/ntlm.html
func negotiate() []byte {
ret := make([]byte, 32)
flags := negotiateAlwaysSign | negotiateNTLM | requestTarget | negotiateOEM | negotiateUnicode | negotiateIdentify
copy(ret, []byte("NTLMSSP\x00")) // protocol
put32(ret[8:], 1) // type
put32(ret[12:], uint32(flags)) // flags
put16(ret[16:], 0) // NT domain name length
put16(ret[18:], 0) // NT domain name max length
put32(ret[20:], 20) // NT domain name offset
put16(ret[24:], 0) // local workstation name length
put16(ret[26:], 0) // local workstation name max length
put32(ret[28:], 20) // local workstation name offset
return ret
}

View File

@ -0,0 +1,103 @@
package httpntlm
import (
"crypto/tls"
"errors"
"io"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
"github.com/ThomsonReutersEikon/go-ntlm/ntlm"
)
// NtlmTransport is implementation of http.RoundTripper interface
type NtlmTransport struct {
TLSClientConfig *tls.Config
Domain string
User string
Password string
}
// RoundTrip method send http request and tries to perform NTLM authentication
func (t NtlmTransport) RoundTrip(req *http.Request) (res *http.Response, err error) {
// first send NTLM Negotiate header
r, _ := http.NewRequest("GET", req.URL.String(), strings.NewReader(""))
r.Header.Add("Authorization", "NTLM "+encBase64(negotiate()))
client := http.Client{Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: t.TLSClientConfig,
}}
resp, err := client.Do(r)
if err != nil {
return nil, err
}
if err == nil && resp.StatusCode == http.StatusUnauthorized {
// it's necessary to reuse the same http connection
// in order to do that it's required to read Body and close it
_, err = io.Copy(ioutil.Discard, resp.Body)
if err != nil {
return nil, err
}
err = resp.Body.Close()
if err != nil {
return nil, err
}
// retrieve Www-Authenticate header from response
ntlmChallengeHeader := resp.Header.Get("WWW-Authenticate")
if ntlmChallengeHeader == "" {
return nil, errors.New("Wrong WWW-Authenticate header")
}
ntlmChallengeString := strings.Replace(ntlmChallengeHeader, "NTLM ", "", -1)
challengeBytes, err := decBase64(ntlmChallengeString)
if err != nil {
return nil, err
}
session, err := ntlm.CreateClientSession(ntlm.Version2, ntlm.ConnectionlessMode)
if err != nil {
return nil, err
}
session.SetUserInfo(t.User, t.Password, t.Domain)
// parse NTLM challenge
challenge, err := ntlm.ParseChallengeMessage(challengeBytes)
if err != nil {
return nil, err
}
err = session.ProcessChallengeMessage(challenge)
if err != nil {
return nil, err
}
// authenticate user
authenticate, err := session.GenerateAuthenticateMessage()
if err != nil {
return nil, err
}
// set NTLM Authorization header
req.Header.Set("Authorization", "NTLM "+encBase64(authenticate.Bytes()))
resp, err = client.Do(req)
}
return resp, err
}

View File

@ -0,0 +1,53 @@
# go-http-ntlm
go-http-ntlm is a Go package that contains NTLM transport (`http.RoundTripper` implementation) for `http.Client` to make NTLM auth protected http requests.
It is based on [https://github.com/ThomsonReutersEikon/go-ntlm](https://github.com/ThomsonReutersEikon/go-ntlm) library.
## Usage example
```go
package main
import (
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/vadimi/go-http-ntlm"
)
func main() {
// configure http client
client := http.Client{
Transport: &httpntlm.NtlmTransport{
Domain: "mydomain",
User: "testuser",
Password: "fish",
},
}
req, err := http.NewRequest("GET", "http://server/ntlm-auth-resource", strings.NewReader(""))
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer func() {
err := resp.Body.Close()
if err != nil {
log.Fatal(err)
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Println(body)
}
```