Example #1
0
// ExportEncrypted encrypts the current state of the key manager with the
// specified password and returns it. The salt used as input to PBKDF2 as well
// as nonce for input to secretbox are randomly generated. The actual key used
// for encryption is derived from the salt and the passphrase using PBKDF2.
func (mgr *Manager) ExportEncrypted(pass []byte) ([]byte, error) {
	plain, err := mgr.ExportPlaintext()
	if err != nil {
		return nil, err
	}

	var nonce [nonceSize]byte
	_, err = rand.Read(nonce[:])
	if err != nil {
		return nil, err
	}

	salt := make([]byte, saltLength)
	_, err = rand.Read(salt)
	if err != nil {
		return nil, err
	}

	ret := make([]byte, nonceSize+saltLength)
	copy(ret[:nonceSize], nonce[:])
	copy(ret[nonceSize:], salt)
	ret = secretbox.Seal(ret, plain, &nonce, deriveKey(pass, salt))

	return ret, nil
}
Example #2
0
func newSession(sessionRateLimit, globalRateLimit *ratelimit.Bucket) *session {
	serverkey := make([]byte, 32)
	_, err := rand.Read(serverkey)
	if err != nil {
		return nil
	}

	clientkey := make([]byte, 32)
	_, err = rand.Read(clientkey)
	if err != nil {
		return nil
	}

	ses := &session{
		serverkey: serverkey,
		clientkey: clientkey,
		rateLimit: makeRateLimitFunc(sessionRateLimit, globalRateLimit),
		conns:     make(chan net.Conn),
	}

	if debug {
		log.Println("New session", ses)
	}

	sessionMut.Lock()
	sessions[string(ses.serverkey)] = ses
	sessions[string(ses.clientkey)] = ses
	sessionMut.Unlock()

	return ses
}
Example #3
0
func replyWithChallenge(w http.ResponseWriter, login string) {

	var defaultSaltRaw [32]byte
	rand.Read(defaultSaltRaw[:])
	salt := base64.StdEncoding.EncodeToString(defaultSaltRaw[:])

	u, ok := users[login]
	if ok {
		salt = u.Salt
	}

	var token [32]byte
	rand.Read(token[:])
	sig := ed25519.Sign(signingKey, token[:])

	signedTokenRaw := make([]byte, len(token)+len(sig))
	copy(signedTokenRaw, token[:])
	copy(signedTokenRaw[len(token):], sig[:])
	signedToken := base64.StdEncoding.EncodeToString(signedTokenRaw)

	err := json.NewEncoder(w).Encode(challenge{signedToken, salt})
	if err != nil {
		log.Println(err)
		http.Error(w, "Error with your request", http.StatusBadRequest)
	}
}
func commandCreateUser() cli.Command {
	return cli.Command{
		Name:        "createuser",
		Usage:       "createuser",
		Description: "Create a new user account. The email address and password are prompted to enter.",
		Action: func(c *cli.Context) {
			failOnError(c, checkZeroArgument(c))
			key := make([]byte, 32)
			salt := make([]byte, 10)
			if _, err := rand.Read(key); err != nil {
				failOnError(c, err)
			}
			if _, err := rand.Read(salt); err != nil {
				failOnError(c, err)
			}
			fmt.Print("Email: ")
			var email string
			fmt.Scanf("%s\n", &email)
			fmt.Print("Password: "******"HMAC_SHA1", key, nil))
			u, err = getUserByIdentifier(u.Email)
			failOnError(c, err)
			fmt.Println(">> user created:")
			printUser(u)
		},
	}
}
Example #5
0
func TestEthash(t *testing.T) {
	seedHash := make([]byte, 32)
	_, err := rand.Read(seedHash)
	if err != nil {
		panic(err)
	}

	e := New(seedHash)

	miningHash := make([]byte, 32)
	if _, err := rand.Read(miningHash); err != nil {
		panic(err)
	}
	diff := big.NewInt(10000)
	log.Println("difficulty", diff)

	nonce := uint64(0)

	ghash_full := e.full(nonce, miningHash)
	log.Println("ethhash full (on nonce):", ghash_full, nonce)

	ghash_light := e.light(nonce, miningHash)
	log.Println("ethash light (on nonce)", ghash_light, nonce)

	if bytes.Compare(ghash_full, ghash_light) != 0 {
		t.Fatal(fmt.Sprintf("full: %x, light: %x", ghash_full, ghash_light))
	}
}
Example #6
0
func TestDeterministicWalletType2(t *testing.T) {
	secret := make([]byte, 32)
	rand.Read(secret)

	private_key := make([]byte, 32)
	rand.Read(private_key)

	public_key := PublicFromPrivate(private_key, true)
	for i := 0; i < 50; i++ {
		private_key = DeriveNextPrivate(private_key, secret)
		if private_key == nil {
			t.Fatal("DeriveNextPrivate fail")
		}

		public_key = DeriveNextPublic(public_key, secret)
		if public_key == nil {
			t.Fatal("DeriveNextPublic fail")
		}

		// verify the public key matching the private key
		pub2 := PublicFromPrivate(private_key, true)
		if !bytes.Equal(public_key, pub2) {
			t.Error(i, "public key mismatch", hex.EncodeToString(pub2), hex.EncodeToString(public_key))
		}

		// make sure that you can sign and verify with it
		if e := VerifyKeyPair(private_key, public_key); e != nil {
			t.Error(i, "verify key failed", e.Error())
		}
	}
}
Example #7
0
func TestExportKeysByID(t *testing.T) {
	setUp(t)
	tempBaseDir, err := ioutil.TempDir("", "notary-test-")
	require.NoError(t, err)
	defer os.RemoveAll(tempBaseDir)
	output, err := ioutil.TempFile("", "notary-test-import-")
	require.NoError(t, err)
	defer os.RemoveAll(output.Name())
	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			return v, nil
		},
	}
	k.outFile = output.Name()
	err = output.Close() // close so export can open
	require.NoError(t, err)
	k.exportKeyIDs = []string{"one", "three"}

	b := &pem.Block{}
	b.Bytes = make([]byte, 1000)
	rand.Read(b.Bytes)

	b2 := &pem.Block{}
	b2.Bytes = make([]byte, 1000)
	rand.Read(b2.Bytes)

	c := &pem.Block{}
	c.Bytes = make([]byte, 1000)
	rand.Read(c.Bytes)

	bBytes := pem.EncodeToMemory(b)
	b2Bytes := pem.EncodeToMemory(b2)
	cBytes := pem.EncodeToMemory(c)

	fileStore, err := store.NewPrivateKeyFileStorage(tempBaseDir, notary.KeyExtension)
	require.NoError(t, err)
	err = fileStore.Set("one", bBytes)
	require.NoError(t, err)
	err = fileStore.Set("two", b2Bytes)
	require.NoError(t, err)
	err = fileStore.Set("three", cBytes)
	require.NoError(t, err)

	err = k.exportKeys(&cobra.Command{}, nil)
	require.NoError(t, err)

	outRes, err := ioutil.ReadFile(k.outFile)
	require.NoError(t, err)

	block, rest := pem.Decode(outRes)
	require.Equal(t, b.Bytes, block.Bytes)
	require.Equal(t, "one", block.Headers["path"])

	block, rest = pem.Decode(rest)
	require.Equal(t, c.Bytes, block.Bytes)
	require.Equal(t, "three", block.Headers["path"])
	require.Len(t, rest, 0)
}
Example #8
0
func TestExportKeysByID(t *testing.T) {
	s := NewTestExportStore()

	b := &pem.Block{}
	b.Bytes = make([]byte, 1000)
	rand.Read(b.Bytes)

	c := &pem.Block{}
	c.Bytes = make([]byte, 1000)
	rand.Read(c.Bytes)

	bBytes := pem.EncodeToMemory(b)
	cBytes := pem.EncodeToMemory(c)

	s.data["ankh"] = bBytes
	s.data["morpork/identifier"] = cBytes

	buf := bytes.NewBuffer(nil)

	err := ExportKeysByID(buf, s, []string{"identifier"})
	require.NoError(t, err)

	out, err := ioutil.ReadAll(buf)
	require.NoError(t, err)

	cFinal, rest := pem.Decode(out)
	require.Equal(t, c.Bytes, cFinal.Bytes)
	require.Equal(t, "morpork/identifier", cFinal.Headers["path"])
	require.Len(t, rest, 0)
}
Example #9
0
func TestInit(t *testing.T) {
	AccessKeyId = DefaultAccessKeyId
	if os.Getenv("ACCESS_KEY_ID") != "" {
		AccessKeyId = os.Getenv("ACCESS_KEY_ID")
	}

	SecretAccessKey = DefaultSecretAccessKey
	if os.Getenv("SECRET_ACCESS_KEY") != "" {
		SecretAccessKey = os.Getenv("SECRET_ACCESS_KEY")
	}

	DebugHost = DefaultDebugHost
	if os.Getenv("DEBUG_HOST") != "" {
		DebugHost = os.Getenv("DEBUG_HOST")
	}

	fileSize := 256
	content := make([]byte, fileSize)
	rand.Read(content)
	err := ioutil.WriteFile(TestObjectName, content, 0644)
	if err != nil {
		t.Errorf("Write TestFile failed.")
	}

	fileSize = 1024*1024*5 + 1
	content = make([]byte, fileSize)
	rand.Read(content)
	err = ioutil.WriteFile(TestObjectName1, content, 0644)
	if err != nil {
		t.Errorf("Write TestFile failed.")
	}

}
Example #10
0
func benchmarkEncrypt(
	b *testing.B,
	size int) {
	var err error

	// Generate the appropriate amount of random data.
	plaintext := make([]byte, size)
	_, err = rand.Read(plaintext)
	if err != nil {
		b.Fatalf("rand.Read: %v", err)
	}

	// Create a random key.
	const keyLen = 32
	key := make([]byte, keyLen)

	_, err = rand.Read(key)
	if err != nil {
		b.Fatalf("rand.Read: %v", err)
	}

	// Repeatedly encrypt.
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_, err = siv.Encrypt(nil, key, plaintext, nil)
		if err != nil {
			b.Fatalf("Encrypt: %v", err)
		}
	}

	b.SetBytes(int64(size))
}
Example #11
0
func raw_passgenHandler(w http.ResponseWriter, r *http.Request) {
	renderTemplate(w, "raw", "raw")
	body := r.FormValue("body")

	if body == "" {
		return
	}

	rand_bytes := make([]byte, len(body))
	rand.Read(rand_bytes)
	rand_bytes2 := make([]byte, len(body))
	rand.Read(rand_bytes2)

	reduced_ascii := make([]byte, 94)
	for i := 0; i < 94; i++ {
		var tmp byte
		tmp = byte('!' + i)
		reduced_ascii[i] = tmp
	}

	pass := make([]byte, len(body))
	for i := 0; i < len(body); i++ {
		tmp := rand_bytes[i] % 94
		if tmp == 0 {
			tmp = 94
		}
		pass[i] = reduced_ascii[(body[i]+rand_bytes2[i])%tmp]

	}
	fmt.Fprint(w, string(pass))
}
Example #12
0
func passgenHandler(w http.ResponseWriter, r *http.Request) {
	body := r.FormValue("body")

	if body == "" {
		renderTemplate(w, "html", "PASS GENERATOR")
		return
	}
	rand_bytes := make([]byte, len(body))
	rand_bytes2 := make([]byte, len(body))
	rand.Read(rand_bytes)
	rand.Read(rand_bytes2)

	reduced_ascii := make([]byte, 94)
	for i := 0; i < 94; i++ {
		var tmp byte
		tmp = byte('!' + i)
		reduced_ascii[i] = tmp
	}
	pass := make([]byte, len(body))
	for i := 0; i < len(body); i++ {
		tmp := rand_bytes[i] % 94
		if tmp == 0 {
			tmp = 94
		}
		pass[i] = reduced_ascii[(body[i]+rand_bytes2[i])%tmp]
	}
	templates.Execute(w, &Page{Title: "PASS GENERATOR", R: string(pass)})
}
Example #13
0
func BenchmarkVerify(b *testing.B) {
	var entropy [32]byte
	_, err := rand.Read(entropy[:])
	if err != nil {
		panic(err)
	}
	sk, pk := GenerateKey(entropy)

	b.ResetTimer()
	message := make([]byte, 64)
	for i := 0; i < b.N; i++ {
		b.StopTimer()
		_, err := rand.Read(message)
		if err != nil {
			panic(err)
		}

		sig := Sign(sk, message)
		b.StartTimer()
		ver := Verify(pk, message, sig)
		if !ver {
			panic(err)
		}
	}
}
Example #14
0
func testProtect(mode int, context []byte, t *testing.T) {
	data_len, err := rand.Int(rand.Reader, big.NewInt(1024))
	if nil != err {
		t.Error(err)
	}

	data := make([]byte, int(data_len.Int64()))
	_, err = rand.Read(data)
	if nil != err {
		t.Error(err)
	}

	key := make([]byte, 32)
	_, err = rand.Read(key)
	if nil != err {
		t.Error(err)
	}

	sc := cell.New(key, mode)
	encData, addData, err := sc.Protect(data, context)
	if nil != err {
		t.Error(err)
	}

	if 0 == bytes.Compare(data, encData) {
		t.Error("Original data and encrypted data match")
	}

	decData, err := sc.Unprotect(encData, addData, context)

	if 0 != bytes.Compare(data, decData) {
		t.Error("Original data and decrypted do not match")
	}
}
Example #15
0
func TestSessionCookie(t *testing.T) {
	b := make([]byte, 16)
	k := make([]byte, 32)
	rand.Read(b)
	rand.Read(k)

	sc := Cookie{
		ID: ID(b),
	}
	cstr := sc.Encode(k)
	sc2, err := DecodeCookie(cstr, k)
	if err != nil {
		t.Error("failed to decode cookie: ", err)
		return
	}

	if sc2.ID != ID(b) {
		t.Errorf("wrong ID after decode, original: %+v, decoded: %+v, encoded: %s", hex.EncodeToString(b),
			hex.EncodeToString([]byte(sc2.ID)), cstr)
		return
	}

	if sc2.Epoch != sc.Epoch {
		t.Error("wrong epoch after decode")
		return
	}
}
// encrypt encrypts a value using the given Block in CTR mode.
//
// A random initialization vector is generated and prepended to the resulting
// ciphertext to be available for decryption. Also, a random salt with the
// length of the block size is prepended to the value before encryption.
func encrypt(block cipher.Block, value []byte) (rv []byte, err error) {
	// Recover in case block has an invalid key.
	defer func() {
		if r := recover(); r != nil {
			err = r.(error)
		}
	}()
	size := block.BlockSize()
	// Generate an initialization vector suitable for encryption.
	// http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Initialization_vector_.28IV.29
	iv := make([]byte, size)
	if _, err = rand.Read(iv); err != nil {
		return
	}
	// Create a salt.
	salt := make([]byte, size)
	if _, err = rand.Read(salt); err != nil {
		return
	}
	value = append(salt, value...)
	// Encrypt it.
	stream := cipher.NewCTR(block, iv)
	stream.XORKeyStream(value, value)
	// Return iv + ciphertext.
	rv = append(iv, value...)
	return
}
Example #17
0
func TestCBC(t *testing.T) {
	key := make([]byte, 16)
	_, _ = rand.Read(key)
	iv := make([]byte, 16)
	_, _ = rand.Read(iv)

	e, err := NewAES(key)
	if err != nil {
		t.Errorf("For NewAES got error %v", err)
	}

	tests := [][]byte{
		[]byte("Test block"),
		[]byte("Test plaintext for multi block CBC encryption test"),
	}

	for i := 0; i < len(tests); i++ {
		plaintext := tests[i]

		encrypted, err := e.EncryptCBC(plaintext, iv)
		if err != nil {
			t.Errorf("For e.EncryptCBC got error %v", err)
		}

		decrypted, err := e.DecryptCBC(encrypted, iv)
		if err != nil {
			t.Errorf("For e.DecryptCBC got error %v", err)
		}

		if bytes.Compare(plaintext, decrypted) != 0 {
			t.Errorf("Failed \"%s\"\nGot %v, expected %v", plaintext, decrypted, plaintext)
		}
	}

}
Example #18
0
// NewFileHeaders creates a new FileHeaders with good defaults
func NewFileHeaders() *FileHeaders {
	masterSeed := make([]byte, 32)
	rand.Read(masterSeed)

	transformSeed := make([]byte, 32)
	rand.Read(transformSeed)

	encryptionIV := make([]byte, 16)
	rand.Read(encryptionIV)

	protectedStreamKey := make([]byte, 32)
	rand.Read(protectedStreamKey)

	streamStartBytes := make([]byte, 32)
	rand.Read(streamStartBytes)

	return &FileHeaders{
		CipherID:            []byte(AESCipherID),
		CompressionFlags:    GzipCompressionFlag,
		MasterSeed:          masterSeed,
		TransformSeed:       transformSeed,
		TransformRounds:     6000,
		EncryptionIV:        encryptionIV,
		ProtectedStreamKey:  protectedStreamKey,
		StreamStartBytes:    streamStartBytes,
		InnerRandomStreamID: SalsaStreamID,
	}
}
Example #19
0
// opaqueChunk returns an opaque b chunk (e.g. padding 0xfe) with length n
// (total length, n+4 bytes).  practically useless but good enough for testing.
// the first 4-bytes of data are random to ensure checksums are not being
// verified.
func opaqueChunk(b byte, n int) []byte {
	if b == 0 {
		b = 0xfe
	}

	length := uint32(n)
	lengthle := []byte{byte(length), byte(length >> 8), byte(length >> 16)}
	checksum := make([]byte, 4)
	_, err := rand.Read(checksum)
	if err != nil {
		panic(err)
	}
	padbytes := make([]byte, n-4) // let this panic if n < 4
	_, err = rand.Read(padbytes)
	if err != nil {
		panic(err)
	}

	var h []byte
	h = append(h, b)
	h = append(h, lengthle...)
	h = append(h, checksum...)
	h = append(h, padbytes...)
	return h
}
Example #20
0
//NewSwizzle makes a Swizzle instance.
func NewSwizzle(key []byte, sectors int, prime *big.Int, primebits int) (Heartbeat, error) {
	if key == nil {
		key = make([]byte, 32)
		rand.Read(key)
	}
	if primebits <= 0 {
		primebits = defaultPrimebits
	}
	if sectors <= 0 {
		sectors = defaultSectors
	}
	if prime == nil {
		var err error
		prime, err = rand.Prime(rand.Reader, primebits)
		if err != nil {
			return nil, err
		}
	}

	m := Swizzle{key: key, prime: prime, sectors: sectors}
	m.fKey = make([]byte, 32)
	rand.Read(m.fKey)
	m.alphaKey = make([]byte, 32)
	rand.Read(m.alphaKey)
	return &m, nil
}
Example #21
0
func TestSaveBinary(t *testing.T) {
	fn := "test.bin"
	defer cleanup(fn)
	b := make([]byte, 128)
	rand.Read(b)
	err := SaveBinary(fn, b, 0644)
	assert.Nil(t, err)
	assertFileNotExists(t, fn+".tmp")
	assertFileNotExists(t, fn+".bak")
	assertFileExists(t, fn)
	assertFileContentsBinary(t, fn, b)
	assertFileMode(t, fn, 0644)

	b2 := make([]byte, 128)
	rand.Read(b2)
	assert.False(t, bytes.Equal(b, b2))

	err = SaveBinary(fn, b2, 0644)
	assertFileExists(t, fn)
	assertFileExists(t, fn+".bak")
	assertFileNotExists(t, fn+".tmp")
	assertFileContentsBinary(t, fn, b2)
	assertFileContentsBinary(t, fn+".bak", b)
	assertFileMode(t, fn, 0644)
	assertFileMode(t, fn+".bak", 0644)
}
Example #22
0
File: agent.go Project: logan/heim
func NewAgent(agentID []byte, accessKey *security.ManagedKey) (*Agent, error) {
	if accessKey.Encrypted() {
		return nil, security.ErrKeyMustBeDecrypted
	}

	iv := make([]byte, accessKey.KeySize())
	if _, err := rand.Read(iv); err != nil {
		return nil, err
	}

	if agentID == nil {
		agentID = make([]byte, AgentIDSize)
		if _, err := rand.Read(agentID); err != nil {
			return nil, err
		}
	}

	var (
		mac [16]byte
		key [32]byte
	)
	copy(key[:], accessKey.Plaintext)
	poly1305.Sum(&mac, iv, &key)

	agent := &Agent{
		ID:      agentID,
		IV:      iv,
		MAC:     mac[:],
		Created: time.Now(),
	}
	return agent, nil
}
Example #23
0
func newSession(serverid, clientid syncthingprotocol.DeviceID, sessionRateLimit, globalRateLimit *ratelimit.Bucket) *session {
	serverkey := make([]byte, 32)
	_, err := rand.Read(serverkey)
	if err != nil {
		return nil
	}

	clientkey := make([]byte, 32)
	_, err = rand.Read(clientkey)
	if err != nil {
		return nil
	}

	ses := &session{
		serverkey: serverkey,
		serverid:  serverid,
		clientkey: clientkey,
		clientid:  clientid,
		rateLimit: makeRateLimitFunc(sessionRateLimit, globalRateLimit),
		connsChan: make(chan net.Conn),
		conns:     make([]net.Conn, 0, 2),
	}

	if debug {
		log.Println("New session", ses)
	}

	sessionMut.Lock()
	pendingSessions[string(ses.serverkey)] = ses
	pendingSessions[string(ses.clientkey)] = ses
	sessionMut.Unlock()

	return ses
}
Example #24
0
func BenchmarkBackendPut(b *testing.B) {
	backend := New("test", 100*time.Millisecond, 10000)
	defer backend.Close()
	defer os.Remove("test")

	// prepare keys
	keys := make([][]byte, b.N)
	for i := 0; i < b.N; i++ {
		keys[i] = make([]byte, 64)
		rand.Read(keys[i])
	}
	value := make([]byte, 128)
	rand.Read(value)

	batchTx := backend.BatchTx()

	batchTx.Lock()
	batchTx.UnsafeCreateBucket([]byte("test"))
	batchTx.Unlock()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		batchTx.Lock()
		batchTx.UnsafePut([]byte("test"), keys[i], value)
		batchTx.Unlock()
	}
}
Example #25
0
// encrypts the given plaintext with the given key.
// It returns a base64-encoded string consisting of the nonce + aad + encryptedBytes
// Each piece is a single space delimited.
func AesEncrypt(secretKey []byte, plaintext []byte) (string, error) {
	aesCipher, err := aes.NewCipher(secretKey)
	if err != nil {
		log.Fatal("Error creating AES cipher" + err.Error())
	}

	gcm, err := cipher.NewGCM(aesCipher)
	if err != nil {
		log.Fatal("Error creating GCM cipher" + err.Error())
	}

	nonce := make([]byte, gcm.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		log.Fatal("Error generating AES nonce" + err.Error())
	}

	aad := make([]byte, 12)
	if _, err := rand.Read(aad); err != nil {
		log.Fatal("Error generating AES AAD" + err.Error())
	}

	ciphertext := gcm.Seal(nil, nonce, plaintext, aad)

	var buffer bytes.Buffer
	buffer.WriteString(base64.StdEncoding.EncodeToString(nonce))
	buffer.WriteString(aesDelimiter)
	buffer.WriteString(base64.StdEncoding.EncodeToString(aad))
	buffer.WriteString(aesDelimiter)
	buffer.WriteString(base64.StdEncoding.EncodeToString(ciphertext))

	return buffer.String(), nil
}
Example #26
0
func (request *VMessRequest) ToBytes(idHash user.CounterHash, randomRangeInt64 user.RandomInt64InRange) ([]byte, error) {
	buffer := make([]byte, 0, 300)

	counter := randomRangeInt64(time.Now().UTC().Unix(), 30)
	hash := idHash.Hash(request.UserId.Bytes, counter)

	log.Debug("Writing userhash: %v", hash)
	buffer = append(buffer, hash...)

	encryptionBegin := len(buffer)

	randomLength := mrand.Intn(32) + 1
	randomContent := make([]byte, randomLength)
	_, err := rand.Read(randomContent)
	if err != nil {
		return nil, err
	}
	buffer = append(buffer, byte(randomLength))
	buffer = append(buffer, randomContent...)

	buffer = append(buffer, request.Version)
	buffer = append(buffer, request.RequestIV[:]...)
	buffer = append(buffer, request.RequestKey[:]...)
	buffer = append(buffer, request.ResponseHeader[:]...)
	buffer = append(buffer, request.Command)
	buffer = append(buffer, request.Address.PortBytes()...)

	switch {
	case request.Address.IsIPv4():
		buffer = append(buffer, addrTypeIPv4)
		buffer = append(buffer, request.Address.IP()...)
	case request.Address.IsIPv6():
		buffer = append(buffer, addrTypeIPv6)
		buffer = append(buffer, request.Address.IP()...)
	case request.Address.IsDomain():
		buffer = append(buffer, addrTypeDomain)
		buffer = append(buffer, byte(len(request.Address.Domain())))
		buffer = append(buffer, []byte(request.Address.Domain())...)
	}

	paddingLength := mrand.Intn(32) + 1
	paddingBuffer := make([]byte, paddingLength)
	_, err = rand.Read(paddingBuffer)
	if err != nil {
		return nil, err
	}
	buffer = append(buffer, byte(paddingLength))
	buffer = append(buffer, paddingBuffer...)
	encryptionEnd := len(buffer)

	aesCipher, err := aes.NewCipher(request.UserId.CmdKey())
	if err != nil {
		return nil, err
	}
	aesStream := cipher.NewCFBEncrypter(aesCipher, user.Int64Hash(counter))
	aesStream.XORKeyStream(buffer[encryptionBegin:encryptionEnd], buffer[encryptionBegin:encryptionEnd])

	return buffer, nil
}
Example #27
0
// Connect initiates a connection to the target host
func (x *GoSNMP) Connect() error {
	if x.Logger == nil {
		x.Logger = log.New(ioutil.Discard, "", 0)
	} else {
		x.loggingEnabled = true
	}

	if x.MaxOids == 0 {
		x.MaxOids = MaxOids
	} else if x.MaxOids < 0 {
		return fmt.Errorf("MaxOids cannot be less than 0")
	}

	addr := net.JoinHostPort(x.Target, strconv.Itoa(int(x.Port)))
	var err error
	x.Conn, err = net.DialTimeout("udp", addr, x.Timeout)
	if err != nil {
		return fmt.Errorf("Error establishing connection to host: %s\n", err.Error())
	}
	if x.random == nil {
		x.random = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
	}
	// http://tools.ietf.org/html/rfc3412#section-6 - msgID only
	// uses the first 31 bits
	// msgID INTEGER (0..2147483647)
	x.msgID = uint32(x.random.Int31())
	// RequestID is Integer32 from SNMPV2-SMI and uses all 32 bits
	x.requestID = x.random.Uint32()

	x.rxBuf = new([rxBufSize]byte)

	if x.Version == Version3 {
		x.MsgFlags |= Reportable // tell the snmp server that a report PDU MUST be sent
		if x.SecurityModel == UserSecurityModel {
			secParams, ok := x.SecurityParameters.(*UsmSecurityParameters)
			if !ok || secParams == nil {
				return fmt.Errorf("&GoSNMP.SecurityModel indicates the User Security Model, but &GoSNMP.SecurityParameters is not of type &UsmSecurityParameters")
			}
			switch secParams.PrivacyProtocol {
			case AES:
				salt := make([]byte, 8)
				_, err = crand.Read(salt)
				if err != nil {
					return fmt.Errorf("Error creating a cryptographically secure salt: %s\n", err.Error())
				}
				secParams.localAESSalt = binary.BigEndian.Uint64(salt)
			case DES:
				salt := make([]byte, 4)
				_, err = crand.Read(salt)
				if err != nil {
					return fmt.Errorf("Error creating a cryptographically secure salt: %s\n", err.Error())
				}
				secParams.localDESSalt = binary.BigEndian.Uint32(salt)
			}
		}
	}

	return nil
}
Example #28
0
func (w *VMessRequestWriter) Write(writer io.Writer, request *VMessRequest) error {
	buffer := make([]byte, 0, 300)
	buffer = append(buffer, request.Version())
	buffer = append(buffer, request.UserHash()...)

	encryptionBegin := len(buffer)

	randomLength := mrand.Intn(32) + 1
	randomContent := make([]byte, randomLength)
	_, err := rand.Read(randomContent)
	if err != nil {
		return err
	}
	buffer = append(buffer, byte(randomLength))
	buffer = append(buffer, randomContent...)

	buffer = append(buffer, request.RequestIV()...)
	buffer = append(buffer, request.RequestKey()...)
	buffer = append(buffer, request.ResponseHeader()...)
	buffer = append(buffer, request.Command())
	buffer = append(buffer, request.portBytes()...)
	buffer = append(buffer, request.targetAddressType())
	buffer = append(buffer, request.targetAddressBytes()...)

	paddingLength := blockSize - 1 - (len(buffer)-encryptionBegin)%blockSize
	if paddingLength == 0 {
		paddingLength = blockSize
	}
	paddingBuffer := make([]byte, paddingLength)
	_, err = rand.Read(paddingBuffer)
	if err != nil {
		return err
	}
	buffer = append(buffer, byte(paddingLength))
	buffer = append(buffer, paddingBuffer...)
	encryptionEnd := len(buffer)

	userId, valid := w.vUserSet.IsValidUserId(request.UserHash())
	if !valid {
		return ErrorInvalidUser
	}
	aesCipher, err := aes.NewCipher(userId.Hash([]byte("PWD")))
	if err != nil {
		return err
	}
	aesMode := cipher.NewCBCEncrypter(aesCipher, make([]byte, blockSize))
	cWriter := v2io.NewCryptionWriter(aesMode, writer)

	_, err = writer.Write(buffer[0:encryptionBegin])
	if err != nil {
		return err
	}
	_, err = cWriter.Write(buffer[encryptionBegin:encryptionEnd])
	if err != nil {
		return err
	}

	return nil
}
//Test case for Set 2 Challenge 11
func TestDetectionOracle(t *testing.T) {
	//Simulating data i would send myself
	testcase := []byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")

	//Big ugly oracle function.
	oracle := func(plaintext []byte) (result []byte, mode string) {
		key := make([]byte, 16)
		_, err := rand.Read(key)
		if err != nil {
			t.Errorf("DetectionOracle: Reading random bytes failed.")
		}

		//"Coin flip"
		var number byte
		binary.Read(rand.Reader, binary.LittleEndian, &number)
		cbc := false
		if number%2 == 0 {
			cbc = true
		}

		//Random prefix and postfix
		var pre uint32
		var post uint32
		binary.Read(rand.Reader, binary.LittleEndian, &pre)
		binary.Read(rand.Reader, binary.LittleEndian, &post)
		predata := make([]byte, pre%10)
		postdata := make([]byte, post%10)
		rand.Read(predata)
		rand.Read(postdata)
		data := append(predata, plaintext...)
		data = append(data, postdata...)
		data = aes.Pad(data, 16)

		if cbc {
			iv := make([]byte, 16)
			_, err := rand.Read(iv)
			if err != nil {
				t.Errorf("DetectionOracle: Reading random bytes failed.")
			}
			result = aes.CBCEncrypt(key, iv, data)
			mode = "CBC"
			return
		} else {
			result = aes.ECBEncrypt(key, data)
			mode = "ECB"
			return
		}
	}

	//Iterate oracle
	for i := 0; i < 40; i++ {
		data, mode := oracle(testcase)
		if output := AESModeDetectionOracle(data); output != mode {
			t.Errorf("DetectionOracle: Detection oracle failed to guess correctly.")
			t.Errorf("\tExpected: %v", mode)
			t.Errorf("\tGuessed:  %v", output)
		}
	}
}
Example #30
-1
func encryptDESCBC(content []byte) ([]byte, *encryptedContentInfo, error) {
	// Create DES key & CBC IV
	key := make([]byte, 8)
	iv := make([]byte, des.BlockSize)
	_, err := rand.Read(key)
	if err != nil {
		return nil, nil, err
	}
	_, err = rand.Read(iv)
	if err != nil {
		return nil, nil, err
	}

	// Encrypt padded content
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, nil, err
	}
	mode := cipher.NewCBCEncrypter(block, iv)
	plaintext, err := pad(content, mode.BlockSize())
	cyphertext := make([]byte, len(plaintext))
	mode.CryptBlocks(cyphertext, plaintext)

	// Prepare ASN.1 Encrypted Content Info
	eci := encryptedContentInfo{
		ContentType: oidData,
		ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{
			Algorithm:  oidEncryptionAlgorithmDESCBC,
			Parameters: asn1.RawValue{Tag: 4, Bytes: iv},
		},
		EncryptedContent: marshalEncryptedContent(cyphertext),
	}

	return key, &eci, nil
}