Beispiel #1
0
// Calculates the key and iv for AES decryption given a password and salt.
func calcAes30Params(pass []uint16, salt []byte) (key, iv []byte) {
	p := make([]byte, 0, len(pass)*2+len(salt))
	for _, v := range pass {
		p = append(p, byte(v), byte(v>>8))
	}
	p = append(p, salt...)

	hash := sha1.New()
	iv = make([]byte, 16)
	s := make([]byte, 0, hash.Size())
	for i := 0; i < hashRounds; i++ {
		hash.Write(p)
		hash.Write([]byte{byte(i), byte(i >> 8), byte(i >> 16)})
		if i%(hashRounds/16) == 0 {
			s = hash.Sum(s[:0])
			iv[i/(hashRounds/16)] = s[4*4+3]
		}
	}
	key = hash.Sum(s[:0])
	key = key[:16]

	for k := key; len(k) >= 4; k = k[4:] {
		k[0], k[1], k[2], k[3] = k[3], k[2], k[1], k[0]
	}
	return key, iv
}
Beispiel #2
0
// readBlockHeader returns the next block header in the archive.
// It will return io.EOF if there were no bytes read.
func (a *archive15) readBlockHeader() (*blockHeader15, error) {
	var err error
	b := a.buf[:7]
	r := a.v
	if a.encrypted {
		salt := a.buf[:saltSize]
		_, err = io.ReadFull(r, salt)
		if err != nil {
			return nil, err
		}
		key, iv := a.getKeys(salt)
		r = newAesDecryptReader(r, key, iv)
		err = readFull(r, b)
	} else {
		_, err = io.ReadFull(r, b)
	}
	if err != nil {
		return nil, err
	}

	crc := b.uint16()
	hash := crc32.NewIEEE()
	hash.Write(b)
	h := new(blockHeader15)
	h.htype = b.byte()
	h.flags = b.uint16()
	size := b.uint16()
	if size < 7 {
		return nil, errCorruptHeader
	}
	size -= 7
	if int(size) > cap(a.buf) {
		a.buf = readBuf(make([]byte, size))
	}
	h.data = a.buf[:size]
	if err := readFull(r, h.data); err != nil {
		return nil, err
	}
	hash.Write(h.data)
	if crc != uint16(hash.Sum32()) {
		return nil, errBadHeaderCrc
	}
	if h.flags&blockHasData > 0 {
		if len(h.data) < 4 {
			return nil, errCorruptHeader
		}
		h.dataSize = int64(h.data.uint32())
	}
	if h.htype == blockService && h.flags&fileLargeData > 0 {
		if len(h.data) < 25 {
			return nil, errCorruptHeader
		}
		b := h.data[21:25]
		h.dataSize |= int64(b.uint32()) << 32
	}
	return h, nil
}
Beispiel #3
0
// An implementation of PBKDF2 (Password-Based Key Derivation Function 2) as
// specified in PKCS #5 v2.0 from RSA Laboratorie and in `RFC 2898
// <http://www.ietf.org/rfc/rfc2898.txt>`.
func PBKDF2(hashfunc func([]byte) hash.Hash, password, salt []byte, iterations, keylen int) (key []byte) {

	var (
		digest          []byte
		i, j, k, length int
	)

	key = make([]byte, keylen)
	slice := key

	hash := hashfunc(password)
	hashlen := hash.Size()
	scratch := make([]byte, 4)

	for keylen > 0 {

		if hashlen > keylen {
			length = keylen
		} else {
			length = hashlen
		}

		i += 1

		scratch[0] = byte(i >> 24)
		scratch[1] = byte(i >> 16)
		scratch[2] = byte(i >> 8)
		scratch[3] = byte(i)

		hash.Write(salt)
		hash.Write(scratch)

		digest = hash.Sum()
		hash.Reset()

		for j = 0; j < length; j++ {
			slice[j] = digest[j]
		}

		for k = 1; k < iterations; k++ {
			hash.Write(digest)
			digest = hash.Sum()
			for j = 0; j < length; j++ {
				slice[j] ^= digest[j]
			}
			hash.Reset()
		}

		keylen -= length
		slice = slice[length:]

	}

	return

}
Beispiel #4
0
// hashForChannelID returns the hash to be signed for TLS Channel
// ID. If a resumption, resumeHash has the previous handshake
// hash. Otherwise, it is nil.
func (h finishedHash) hashForChannelID(resumeHash []byte) []byte {
	hash := sha256.New()
	hash.Write(channelIDLabel)
	if resumeHash != nil {
		hash.Write(channelIDResumeLabel)
		hash.Write(resumeHash)
	}
	hash.Write(h.server.Sum(nil))
	return hash.Sum(nil)
}
Beispiel #5
0
// | signature | deadline | str
func (c *Cipher) encrypt(deadline uint64, b []byte) []byte {
	result := make([]byte, c.hdrLen+len(b))
	binary.BigEndian.PutUint64(result[c.sigLen:c.hdrLen], deadline)
	copy(result[c.hdrLen:], b)

	hash := hmac.New(c.hash, c.signKey)
	hash.Write(b)
	hash.Write(result[c.sigLen:c.hdrLen])
	copy(result, hash.Sum(nil)[:c.sigLen])

	return result
}
Beispiel #6
0
func generateSalt(secret []byte) ([]byte, error) {
	buf := make([]byte, saltSize, saltSize+sha1.Size)
	_, err := io.ReadFull(rand.Reader, buf)
	if err != nil {
		return nil, err
	}

	hash := sha1.New()
	hash.Write(buf)
	hash.Write(secret)

	return hash.Sum(buf), nil
}
Beispiel #7
0
// Compute an SHA256 digest for a string.
func Digest(data string) string {
	hash := crypto.SHA256.New()
	if _, err := hash.Write([]byte(data)); err != nil {
		panic("Writing to a hash should never fail")
	}
	return hex.EncodeToString(hash.Sum())
}
Beispiel #8
0
// Private function
func generateSalt(secret string, saltSize uint) []byte {
	sc := []byte(secret)
	buf := make([]byte, saltSize, saltSize+sha1.Size)
	_, err := io.ReadFull(rand.Reader, buf)

	if err != nil {
		fmt.Printf("random read failed: %v", err)
		os.Exit(1)
	}

	hash := sha1.New()
	hash.Write(buf)
	hash.Write(sc)

	return hash.Sum(buf)
}
func (cri *checksummedReaderImpl) Verify() (bool, error) {
	originalOffset, err := cri.delegate.Seek(0, 1)
	if err != nil {
		return false, err
	}
	if cri.checksumOffset > 0 {
		_, err = cri.delegate.Seek(-int64(cri.checksumOffset), 1)
		if err != nil {
			return false, err
		}
	}
	block := make([]byte, cri.checksumInterval+4)
	checksum := block[cri.checksumInterval:]
	_, err = io.ReadFull(cri.delegate, block)
	if err != nil {
		return false, err
	}
	block = block[:cri.checksumInterval]
	hash := cri.newHash()
	hash.Write(block)
	verified := bytes.Equal(checksum, hash.Sum(cri.checksum[:0]))
	_, err = cri.delegate.Seek(originalOffset, 0)
	if err != nil {
		return verified, err
	}
	return verified, nil
}
Beispiel #10
0
// hashForClientCertificate returns a digest, hash function, and TLS 1.2 hash
// id suitable for signing by a TLS client certificate.
func (h finishedHash) hashForClientCertificate(signatureAndHash signatureAndHash, masterSecret []byte) ([]byte, crypto.Hash, error) {
	if (h.version == VersionSSL30 || h.version >= VersionTLS12) && h.buffer == nil {
		panic("a handshake hash for a client-certificate was requested after discarding the handshake buffer")
	}

	if h.version == VersionSSL30 {
		if signatureAndHash.signature != signatureRSA {
			return nil, 0, errors.New("ssltvd: unsupported signature type for client certificate")
		}

		md5Hash := md5.New()
		md5Hash.Write(h.buffer)
		sha1Hash := sha1.New()
		sha1Hash.Write(h.buffer)
		return finishedSum30(md5Hash, sha1Hash, masterSecret, nil), crypto.MD5SHA1, nil
	}
	if h.version >= VersionTLS12 {
		hashAlg, err := lookupTLSHash(signatureAndHash.hash)
		if err != nil {
			return nil, 0, err
		}
		hash := hashAlg.New()
		hash.Write(h.buffer)
		return hash.Sum(nil), hashAlg, nil
	}

	if signatureAndHash.signature == signatureECDSA {
		return h.server.Sum(nil), crypto.SHA1, nil
	}

	return h.Sum(), crypto.MD5SHA1, nil
}
Beispiel #11
0
func (c *Cipher) encrypt(now uint64, str []byte) []byte {
	hash := hmac.New(c.hash, c.signKey)

	hash.Write(str)
	timestamp := make([]byte, c.timestampLen)
	binary.BigEndian.PutUint64(timestamp, now)
	hash.Write(c.signKey)

	sig := hash.Sum(nil)[:c.sigLen]
	result := make([]byte, c.sigLen+c.timestampLen+len(str))
	copy(result, sig)
	copy(result[c.sigLen:], timestamp)
	copy(result[c.sigLen+c.timestampLen:], str)

	return result
}
Beispiel #12
0
func signPayload(payload, secret string, hashFunc func() hash.Hash) string {
	hash := hmac.New(hashFunc, []byte(secret))
	hash.Write([]byte(payload))
	signature := make([]byte, b64.EncodedLen(hash.Size()))
	b64.Encode(signature, hash.Sum(nil))
	return string(signature)
}
Beispiel #13
0
// Decode decodes the given token and return its data
// and creation time in UTC.
func (tok *T) Decode(token []byte) (data []byte, creation time.Time, err error) {
	raw := make([]byte, base64.RawURLEncoding.DecodedLen(len(token)))
	n, err := base64.RawURLEncoding.Decode(raw, token)
	if err != nil {
		return nil, time.Time{}, err
	}
	raw = raw[:n]
	hash := tok.hmac()
	if len(raw) < aes.BlockSize*2+hash.Size() {
		return nil, time.Time{}, ErrInvalidToken
	}
	soff := len(raw) - hash.Size() // signature offset
	hash.Write(raw[:soff])
	want := hash.Sum(nil)
	have := raw[soff:]
	if !hmac.Equal(want, have) {
		return nil, time.Time{}, ErrInvalidTokenSignature
	}
	iv := raw[:aes.BlockSize]
	body := raw[aes.BlockSize:soff]
	if len(body)%aes.BlockSize != 0 {
		return nil, time.Time{}, ErrInvalidToken
	}
	mode := cipher.NewCBCDecrypter(tok.aes, iv)
	mode.CryptBlocks(body, body)
	ts := time.Unix(int64(binary.BigEndian.Uint32(body)), 0)
	body, err = pkcs7Unpad(body, aes.BlockSize)
	if err != nil {
		return nil, time.Time{}, err
	}
	return body[4:], ts.UTC(), nil
}
Beispiel #14
0
// Encode encodes the given byte slice and returns a token.
func (tok *T) Encode(data []byte) (token []byte, err error) {
	if data == nil {
		data = []byte{}
	}
	body := make([]byte, 4+len(data))
	now := uint32(time.Now().UTC().Unix())
	binary.BigEndian.PutUint32(body, now)
	copy(body[4:], data)
	body, err = pkcs7Pad(body, aes.BlockSize)
	if err != nil {
		return nil, err
	}
	iv := NewKey(aes.BlockSize)
	mode := cipher.NewCBCEncrypter(tok.aes, iv)
	mode.CryptBlocks(body, body)
	hash := tok.hmac()
	// size = len(iv + aesblocks + signature)
	token = make([]byte, len(iv)+len(body)+hash.Size())
	copy(token, iv)
	offset := len(iv)
	copy(token[offset:], body)
	offset += len(body)
	hash.Write(token[:offset])
	copy(token[offset:], hash.Sum(nil))
	b := make([]byte, base64.RawURLEncoding.EncodedLen(len(token)))
	base64.RawURLEncoding.Encode(b, token)
	return b, nil
}
Beispiel #15
0
func GetIronValue(name, value string, key []byte, timestamped bool) (val string, ok bool) {
	split := strings.SplitN(value, ":", 2)
	if len(split) != 2 {
		return
	}
	expected, value := []byte(split[0]), split[1]
	message := fmt.Sprintf("%s|%s", strings.Replace(name, "|", `\|`, -1), value)
	hash := hmac.New(ironHMAC, key)
	hash.Write([]byte(message))
	digest := hash.Sum(nil)
	mac := make([]byte, base64.URLEncoding.EncodedLen(len(digest)))
	base64.URLEncoding.Encode(mac, digest)
	if subtle.ConstantTimeCompare(mac, expected) != 1 {
		return
	}
	if timestamped {
		split = strings.SplitN(value, ":", 2)
		if len(split) != 2 {
			return
		}
		timestring, value := split[0], split[1]
		timestamp, err := strconv.ParseInt(timestring, 10, 64)
		if err != nil {
			return
		}
		if time.Now().UnixNano() > timestamp {
			return
		}
		return value, true
	}
	return value, true
}
Beispiel #16
0
func Hash(fileName string, newHash func() hash.Hash) ([]byte, error) {
	hash := newHash()

	file, err := os.Open(fileName)
	if err != nil {
		return nil, common.TraceError(err)
	}
	defer file.Close()

	temp := make([]byte, 4096)

	for {
		nn, err := file.Read(temp)
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, common.TraceError(err)
		}

		hash.Write(temp[0:nn])
	}

	return hash.Sum(nil), nil
}
Beispiel #17
0
// hashForClientCertificate returns a digest, hash function, and TLS 1.2 hash
// id suitable for signing by a TLS client certificate.
func (h finishedHash) hashForClientCertificate(signatureAndHash signatureAndHash, masterSecret []byte) ([]byte, crypto.Hash, error) {
	if h.version == VersionSSL30 {
		if signatureAndHash.signature != signatureRSA {
			return nil, 0, errors.New("tls: unsupported signature type for client certificate")
		}

		md5Hash := md5.New()
		md5Hash.Write(h.buffer)
		sha1Hash := sha1.New()
		sha1Hash.Write(h.buffer)
		return finishedSum30(md5Hash, sha1Hash, masterSecret, nil), crypto.MD5SHA1, nil
	}
	if h.version >= VersionTLS12 {
		hashAlg, err := lookupTLSHash(signatureAndHash.hash)
		if err != nil {
			return nil, 0, err
		}
		hash := hashAlg.New()
		hash.Write(h.buffer)
		return hash.Sum(nil), hashAlg, nil
	}
	if signatureAndHash.signature == signatureECDSA {
		return h.server.Sum(nil), crypto.SHA1, nil
	}

	return h.Sum(), crypto.MD5SHA1, nil
}
Beispiel #18
0
// index returns the array index for the given data.
func (i *InverseBloomFilter) index(data []byte) uint32 {
	hash := i.hashPool.Get().(hash.Hash32)
	hash.Write(data)
	index := hash.Sum32() % uint32(i.capacity)
	hash.Reset()
	i.hashPool.Put(hash)
	return index
}
Beispiel #19
0
func calculateSparseFingerprint(path string, fileSize int64, h hash.Hash) (Fingerprint, error) {
	buffer := make([]byte, sparseFingerprintSize)
	hash := sha256.New()

	file, err := os.Open(path)
	if err != nil {
		return EMPTY, err
	}
	defer file.Close()

	// start
	count, err := file.Read(buffer)
	if err != nil {
		return EMPTY, err
	}
	hash.Write(buffer[:count])

	// middle
	_, err = file.Seek((fileSize-sparseFingerprintSize)/2, 0)
	if err != nil {
		return EMPTY, err
	}

	count, err = file.Read(buffer)
	if err != nil {
		return EMPTY, err
	}
	hash.Write(buffer[:count])

	// end
	_, err = file.Seek(-sparseFingerprintSize, 2)
	if err != nil {
		return EMPTY, err
	}

	count, err = file.Read(buffer)
	if err != nil {
		return EMPTY, err
	}
	hash.Write(buffer[:count])

	sum := hash.Sum(make([]byte, 0, 64))
	fingerprint := hex.EncodeToString(sum)

	return Fingerprint(fingerprint), nil
}
Beispiel #20
0
// Generates an ID for the node
func (vn *Vnode) genId(idx uint16, conf *Config) {
	hash := conf.HashFunc()
	hash.Write([]byte(conf.Hostname))
	binary.Write(hash, binary.BigEndian, idx)

	// Use the hash as the ID
	vn.Id = hash.Sum(nil)
}
Beispiel #21
0
func (c *Cipher) encrypt(now int64, str string) string {
	hash := hmac.New(c.Hash, unsafe2.Bytes(c.SecretKey))

	if now == 0 {
		now = time.Now().Add(c.TTL).UnixNano()
	}
	hash.Write(unsafe2.Bytes(str))
	hash.Write(unsafe2.Bytes(c.segSep()))
	nows := strconv.FormatInt(now, 10)
	hash.Write(unsafe2.Bytes(nows))
	hash.Write(unsafe2.Bytes(c.segSep()))
	hash.Write(unsafe2.Bytes(c.SecretKey))
	sig := hash.Sum(nil)

	sigStr := hex.EncodeToString(sig[:hash.Size()/2])
	return str + c.segSep() + nows + c.segSep() + sigStr[:len(sigStr)/2]
}
Beispiel #22
0
// Computes a cryptographic fingerprint of this identity
func (this *PublicIdentity) Fingerprint() (fingerprint *Digest) {
	hash := sha256.New224()
	data, err := x509.MarshalPKIXPublicKey(this.key)
	if err != nil {
		panic(err)
	}
	hash.Write(data)
	return &Digest{impl: hash.Sum(nil)}
}
Beispiel #23
0
// Called by the server to initiate a new client connection.
func (server *Server) handleIncomingClient(conn net.Conn) (err error) {
	client := new(Client)
	addr := conn.RemoteAddr()
	if addr == nil {
		err = errors.New("Unable to extract address for client.")
		return
	}

	client.lf = &clientLogForwarder{client, server.Logger}
	client.Logger = log.New(client.lf, "", 0)

	client.session = server.pool.Get()
	client.Printf("New connection: %v (%v)", conn.RemoteAddr(), client.Session())

	client.tcpaddr = addr.(*net.TCPAddr)
	client.server = server
	client.conn = conn
	client.reader = bufio.NewReader(client.conn)

	client.state = StateClientConnected

	client.udprecv = make(chan []byte)
	client.voiceTargets = make(map[uint32]*VoiceTarget)

	client.user = nil

	// Extract user's cert hash
	tlsconn := client.conn.(*tls.Conn)
	err = tlsconn.Handshake()
	if err != nil {
		client.Printf("TLS handshake failed: %v", err)
		client.Disconnect()
		return
	}

	state := tlsconn.ConnectionState()
	if len(state.PeerCertificates) > 0 {
		hash := sha1.New()
		hash.Write(state.PeerCertificates[0].Raw)
		sum := hash.Sum(nil)
		client.certHash = hex.EncodeToString(sum)
	}

	// Check whether the client's cert hash is banned
	if server.IsCertHashBanned(client.CertHash()) {
		client.Printf("Certificate hash is banned")
		client.Disconnect()
		return
	}

	// Launch network readers
	go client.tlsRecvLoop()
	go client.udpRecvLoop()

	return
}
Beispiel #24
0
// IronString returns "tamper-resistant" strings.
func IronString(name, value string, key []byte, duration int64) string {
	if duration > 0 {
		value = fmt.Sprintf("%d:%s", time.Now().UnixNano()+duration, value)
	}
	message := fmt.Sprintf("%s|%s", strings.Replace(name, "|", `\|`, -1), value)
	hash := hmac.New(ironHMAC, key)
	hash.Write([]byte(message))
	mac := base64.URLEncoding.EncodeToString(hash.Sum(nil))
	return fmt.Sprintf("%s:%s", mac, value)
}
Beispiel #25
0
func calculateHash(values url.Values, path string) string {
	hash := sha1.New()
	hash.Write([]byte(path))
	hash.Write([]byte{0x00})
	if len(values) > 0 {
		if len(values) == 1 {
			for key, value := range values {
				hash.Write([]byte(key))
				hash.Write([]byte{0x00})
				addSortedKeys(value, hash)
			}
		} else {
			urlValues := make(UrlValueSlice, 0, len(values))
			for key, value := range values {
				urlValue := new(UrlValue)
				urlValue.Key = key
				urlValue.Values = value
				urlValues = append(urlValues, urlValue)
			}
			sort.Sort(urlValues)
			for _, sortedUrlValue := range urlValues {
				hash.Write([]byte(sortedUrlValue.Key))
				hash.Write([]byte{0x00})
				addSortedKeys(sortedUrlValue.Values, hash)
			}
		}
	}
	return string(hash.Sum([]byte{0x00}))
}
Beispiel #26
0
func (x *Xsrf) sign(data []byte) []byte {
	hash := x.hash()
	hash.Write(data)
	signing := hash.Sum(nil)

	bs := x.Pool.Get(len(data)+hash.Size(), false) // data+signature
	buf := bytes.NewBuffer(bs)
	buf.Write(data)
	buf.Write(signing)

	dst := x.Pool.Get(_ENCODING.EncodedLen(buf.Len()), true)
	_ENCODING.Encode(dst, buf.Bytes())
	x.Pool.Put(bs)

	return dst
}
Beispiel #27
0
//NewMerkleBeat makes a Merklebeat instance.
func NewMerkleBeat(key []byte, seed []byte, chunksz int) Heartbeat {
	if seed == nil {
		seed = make([]byte, defaultKeySize)
		rand.Read(seed)
	}
	if chunksz <= 0 {
		chunksz = defaultChunkSize
	}

	hash := sha256.New()
	hash.Write(key)
	key32 := hash.Sum(nil)
	hmac := hmac.New(sha256.New, key)

	m := MerkleBeat{key: key32, seed: seed, chunksz: chunksz, hmac: hmac}
	return &m
}
Beispiel #28
0
func (c *Client) clientProof() []byte {
	mac := hmac.New(c.newHash, c.saltedPass)
	mac.Write([]byte("Client Key"))
	clientKey := mac.Sum(nil)
	hash := c.newHash()
	hash.Write(clientKey)
	storedKey := hash.Sum(nil)
	mac = hmac.New(c.newHash, storedKey)
	mac.Write(c.authMsg.Bytes())
	clientProof := mac.Sum(nil)
	for i, b := range clientKey {
		clientProof[i] ^= b
	}
	clientProof64 := make([]byte, b64.EncodedLen(len(clientProof)))
	b64.Encode(clientProof64, clientProof)
	return clientProof64
}
Beispiel #29
0
// SHA HMAC key calculation algorithm
func shaHMAC(password string, engineID string) []byte {
	hash := sha1.New()
	var pi int // password index
	for i := 0; i < 1048576; i += 64 {
		var chunk []byte
		for e := 0; e < 64; e++ {
			chunk = append(chunk, password[pi%len(password)])
			pi++
		}
		hash.Write(chunk)
	}
	hashed := hash.Sum(nil)
	local := sha1.New()
	local.Write(hashed)
	local.Write([]byte(engineID))
	local.Write(hashed)
	final := local.Sum(nil)
	return final
}
Beispiel #30
0
// BodyBSON is part of the ParserConsumer interface and receives BSON bodies from the parser.
// Its main role is to dispatch the body to the Read() function of the current DemuxOut.
func (demux *Demultiplexer) BodyBSON(buf []byte) error {
	if demux.currentNamespace == "" {
		return newError("collection data without a collection header")
	}
	hash, ok := demux.hashes[demux.currentNamespace]
	if !ok {
		return newError("no checksum for current namespace " + demux.currentNamespace)
	}
	hash.Write(buf)

	demux.lengths[demux.currentNamespace] += int64(len(buf))

	out, ok := demux.outs[demux.currentNamespace]
	if !ok {
		return newError("no demux consumer currently consuming namespace " + demux.currentNamespace)
	}
	_, err := out.Write(buf)
	return err
}