client.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. package main
  2. /*
  3. #cgo CFLAGS: -O2
  4. #cgo LDFLAGS: -lcrypto -lm
  5. #include "../c/dpf.h"
  6. #include "../c/okvClient.h"
  7. #include "../c/dpf.c"
  8. #include "../c/okvClient.c"
  9. */
  10. import "C"
  11. //sssssssssssss
  12. import (
  13. lib "2PPS/lib"
  14. "bytes"
  15. "crypto/rand"
  16. "crypto/sha256"
  17. "crypto/tls"
  18. "encoding/json"
  19. "fmt"
  20. "math/big"
  21. mr "math/rand"
  22. "net"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "time"
  28. "unsafe"
  29. "golang.org/x/crypto/nacl/box"
  30. )
  31. type tweet struct {
  32. Topics []string
  33. Text string
  34. }
  35. const leader string = "127.0.0.1:4441"
  36. //needs to be changed at leader/follower/client at the same time
  37. const neededSubscriptions = 1
  38. const numClients = 1
  39. const dataLength int = 128
  40. const numThreads int = 12
  41. var dbWriteSize int = 100
  42. var round int
  43. var topicList []string
  44. var archiveTopicList []string
  45. //todo! expand this for multiple clients
  46. var archiveInterests = make([]int, 1)
  47. var sharedSecret [numClients][2][32]byte = createSharedSecret()
  48. var wantsArchive = make([]byte, 1)
  49. var leaderPublicKey *[32]byte
  50. var followerPublicKey *[32]byte
  51. var clientPrivateKey *[32]byte
  52. var clientPublicKey *[32]byte
  53. func main() {
  54. wg := &sync.WaitGroup{}
  55. for i := 0; i < numClients; i++ {
  56. wg.Add(1)
  57. go client(i)
  58. }
  59. wg.Wait()
  60. }
  61. func client(clientNumber int) {
  62. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  63. if err != nil {
  64. panic(err)
  65. }
  66. clientPrivateKey = generatedPrivateKey
  67. clientPublicKey = generatedPublicKey
  68. C.initializeCipher()
  69. //initializes the connection to the leader
  70. conf := &tls.Config{
  71. InsecureSkipVerify: true,
  72. }
  73. leaderConn, err := tls.Dial("tcp", leader, conf)
  74. if err != nil {
  75. panic(err)
  76. }
  77. leaderConn.SetDeadline(time.Time{})
  78. //receives topics first so client can participate asap
  79. receiveTopicLists(leaderConn)
  80. //gets the public keys of both servers
  81. var tmpLeaderPubKey [32]byte
  82. _, err = leaderConn.Read(tmpLeaderPubKey[:])
  83. if err != nil {
  84. panic(err)
  85. }
  86. leaderPublicKey = &tmpLeaderPubKey
  87. var tmpFollowerPubKey [32]byte
  88. _, err = leaderConn.Read(tmpFollowerPubKey[:])
  89. if err != nil {
  90. panic(err)
  91. }
  92. followerPublicKey = &tmpFollowerPubKey
  93. //sends own public key
  94. writeTo(leaderConn, clientPublicKey[:])
  95. //setup ends above
  96. //while client is active he is always connected and has to participate
  97. for {
  98. //gets current phase
  99. phase := readFrom(leaderConn, 1)
  100. fmt.Println("Phase ", phase[0])
  101. if phase[0] == 1 {
  102. //gets current dbWriteSize from leader
  103. dbWriteSizeBytes := readFrom(leaderConn, 4)
  104. dbWriteSize = byteToInt(dbWriteSizeBytes)
  105. //todo! put into tweet creation
  106. //roundAsBytes := readFrom(leaderConn, 4)
  107. roundAsBytes := make([]byte, 4)
  108. _, err = leaderConn.Read(roundAsBytes)
  109. if err != nil {
  110. panic(err)
  111. }
  112. round = byteToInt(roundAsBytes)
  113. //request virtualAddress from leader via pirQuery
  114. encryptedQueryLeader, encryptedQueryFollower := createAuditPIRQuery(clientNumber)
  115. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, false)
  116. pos := receiveVirtualAddress(sharedSecret[clientNumber], leaderConn)
  117. tweet := getTweet(clientNumber)
  118. //prep the query
  119. dataSize := len(tweet)
  120. querySize := make([]byte, 4)
  121. cQuerySize := C.int(byteToInt(querySize))
  122. var dpfQueryA *C.uchar
  123. var dpfQueryB *C.uchar
  124. C.prepQuery(C.int(pos), C.int(dbWriteSize), (*C.uchar)(&tweet[0]), C.int(dataSize), &cQuerySize, &dpfQueryA, &dpfQueryB)
  125. intQuerySize := int(cQuerySize) //byteToInt(querySize)
  126. //write the query
  127. queryAPlaintext := C.GoBytes(unsafe.Pointer(dpfQueryA), C.int(intQuerySize))
  128. //encrypts queryA and appends it to message
  129. var nonce [24]byte
  130. //fill nonce with randomness
  131. _, err = rand.Read(nonce[:])
  132. if err != nil {
  133. panic("couldn't get randomness for nonce!")
  134. }
  135. dpfQueryAEncrypted := box.Seal(nonce[:], queryAPlaintext, &nonce, leaderPublicKey, clientPrivateKey)
  136. //encrypts queryB and appends it to message
  137. queryBPlaintext := C.GoBytes(unsafe.Pointer(dpfQueryB), C.int(intQuerySize))
  138. //fill nonce with randomness
  139. _, err = rand.Read(nonce[:])
  140. if err != nil {
  141. panic("couldn't get randomness for nonce!")
  142. }
  143. dpfQueryBEncrypted := box.Seal(nonce[:], queryBPlaintext, &nonce, followerPublicKey, clientPrivateKey)
  144. //writes the dpfQuery to the leader
  145. dpfLengthBytes := intToByte(len(dpfQueryAEncrypted))
  146. writeTo(leaderConn, dpfLengthBytes)
  147. writeTo(leaderConn, dpfQueryAEncrypted)
  148. writeTo(leaderConn, dpfQueryBEncrypted)
  149. C.free(unsafe.Pointer(dpfQueryA))
  150. C.free(unsafe.Pointer(dpfQueryB))
  151. } else if phase[0] == 3 {
  152. /*
  153. possible Values
  154. 0 : new client
  155. leader expects sharedSecrets, expects pirQuery
  156. 1 : update needed
  157. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  158. 2 : no update needed
  159. nothing
  160. */
  161. subPhase := readFrom(leaderConn, 1)
  162. var encryptedQueryLeader, encryptedQueryFollower []byte
  163. //first time participating
  164. if subPhase[0] == 0 {
  165. receiveTopicLists(leaderConn)
  166. encryptedQueryLeader, encryptedQueryFollower = createPIRQuery(int(subPhase[0]), clientNumber)
  167. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, false)
  168. }
  169. //updates the topic list and what client is interested in
  170. if subPhase[0] == 1 {
  171. receiveTopicLists(leaderConn)
  172. //updates local secret
  173. for index := 0; index < 2; index++ {
  174. sharedSecret[clientNumber][index] = sha256.Sum256(sharedSecret[clientNumber][index][:])
  175. }
  176. encryptedQueryLeader, encryptedQueryFollower = createPIRQuery(int(subPhase[0]), clientNumber)
  177. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, false)
  178. }
  179. receiveTweets(sharedSecret[clientNumber], leaderConn, false)
  180. if len(archiveTopicList) > 0 {
  181. wantsArchive[0] = 0 //archive test
  182. } else {
  183. wantsArchive[0] = 0
  184. }
  185. writeTo(leaderConn, wantsArchive)
  186. if wantsArchive[0] == 1 && len(archiveTopicList) > 0 {
  187. encryptedQueryLeader, encryptedQueryFollower = createPIRQuery(-1, clientNumber)
  188. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, true)
  189. receiveTweets(sharedSecret[clientNumber], leaderConn, true)
  190. }
  191. } else {
  192. panic("somethin went wrong")
  193. }
  194. }
  195. }
  196. //creates and sends the pirQuerys for each server
  197. func createPIRQuery(subPhase int, clientNumber int) ([]byte, []byte) {
  198. //later this will be taken from gui, this is only for testing
  199. topicsOfInterest := make([]int, 1)
  200. topicsOfInterest[0] = 1
  201. archiveInterests[0] = 1
  202. tmptopicsOfInterest := make([]int, len(topicsOfInterest))
  203. copy(tmptopicsOfInterest, topicsOfInterest)
  204. tmpNeededSubscriptions := neededSubscriptions
  205. if tmpNeededSubscriptions > len(topicList) {
  206. tmpNeededSubscriptions = len(topicList)
  207. }
  208. tmpTopicList := make([]string, len(topicList))
  209. copy(tmpTopicList, topicList)
  210. if wantsArchive[0] == 1 && subPhase == -1 {
  211. tmpNeededSubscriptions = len(archiveInterests)
  212. if tmpNeededSubscriptions > len(archiveTopicList) {
  213. tmpNeededSubscriptions = len(archiveTopicList)
  214. }
  215. copy(tmptopicsOfInterest, archiveInterests) //archiveInterests from gui
  216. copy(tmpTopicList, archiveTopicList)
  217. }
  218. topicsOfInterestAsBytes := make([][]byte, tmpNeededSubscriptions)
  219. for i := range topicsOfInterestAsBytes {
  220. topicsOfInterestAsBytes[i] = make([]byte, len(tmpTopicList))
  221. }
  222. //creates fake topicsOfInterest if client is boooring
  223. if len(tmptopicsOfInterest) < tmpNeededSubscriptions && subPhase != -1 {
  224. tmptopicsOfInterest = addFakeInterests(len(tmpTopicList), tmptopicsOfInterest, false)
  225. }
  226. for topic, position := range tmptopicsOfInterest {
  227. topicsOfInterestAsBytes[topic][position] = 1
  228. }
  229. //pirQuery [serverAmount][topicsofinterest][topicAmount]byte
  230. pirQuerys := make([][][]byte, 2)
  231. for i := range pirQuerys {
  232. pirQuerys[i] = make([][]byte, len(tmptopicsOfInterest))
  233. for j := range pirQuerys[i] {
  234. pirQuerys[i][j] = make([]byte, len(tmpTopicList))
  235. }
  236. }
  237. //for leader
  238. //pirQuery will be filled with random bits
  239. for topic := range tmptopicsOfInterest {
  240. for index := range tmpTopicList {
  241. bit, err := rand.Int(rand.Reader, big.NewInt(2))
  242. if err != nil {
  243. panic(err)
  244. }
  245. pirQuerys[0][topic][index] = byte(bit.Int64())
  246. }
  247. }
  248. //creating last manually with result and wanted
  249. //if position random result correct -> 0, not correct -> 1
  250. for topic := range tmptopicsOfInterest {
  251. for index := range tmpTopicList {
  252. if pirQuerys[0][topic][index] == topicsOfInterestAsBytes[topic][index] {
  253. pirQuerys[1][topic][index] = 0
  254. } else {
  255. pirQuerys[1][topic][index] = 1
  256. }
  257. }
  258. }
  259. //flattens the querys to be able to send them more efficently
  260. messagesFlattened := make([][]byte, 2)
  261. //adds the sharedSecret to the first pirQuery when first time participating
  262. if subPhase == 0 {
  263. for server := 0; server < 2; server++ {
  264. messagesFlattened[server] = append(messagesFlattened[server], sharedSecret[clientNumber][server][:]...)
  265. }
  266. }
  267. for server := 0; server < 2; server++ {
  268. for topic := range pirQuerys[server] {
  269. messagesFlattened[server] = append(messagesFlattened[server], pirQuerys[server][topic][:]...)
  270. }
  271. }
  272. var nonce [24]byte
  273. _, err := rand.Read(nonce[:])
  274. if err != nil {
  275. panic("couldn't get randomness for nonce!")
  276. }
  277. encryptedQueryLeader := box.Seal(nonce[:], messagesFlattened[0], &nonce, leaderPublicKey, clientPrivateKey)
  278. _, err = rand.Read(nonce[:])
  279. if err != nil {
  280. panic("couldn't get randomness for nonce!")
  281. }
  282. encryptedQueryFollower := box.Seal(nonce[:], messagesFlattened[1], &nonce, followerPublicKey, clientPrivateKey)
  283. return encryptedQueryLeader, encryptedQueryFollower
  284. }
  285. func sendQuerys(encryptedQueryLeader, encryptedQueryFollower []byte, leaderConn net.Conn, getArchive bool) {
  286. encryptedLength := len(encryptedQueryLeader)
  287. //sends the pirQuerysLength to the leader
  288. writeTo(leaderConn, intToByte(encryptedLength))
  289. //sends the pirQuerys to the leader
  290. writeTo(leaderConn, encryptedQueryLeader)
  291. writeTo(leaderConn, encryptedQueryFollower)
  292. if getArchive {
  293. writeTo(leaderConn, intToByte(len(archiveInterests)))
  294. }
  295. }
  296. func receiveVirtualAddress(sharedSecret [2][32]byte, leaderConn net.Conn) int {
  297. virtualAddressByte := readFrom(leaderConn, 4)
  298. //xores the sharedSecret
  299. for h := 0; h < 2; h++ {
  300. for i := 0; i < 4; i++ {
  301. virtualAddressByte[i] = virtualAddressByte[i] ^ sharedSecret[h][i]
  302. }
  303. }
  304. return byteToInt(virtualAddressByte)
  305. }
  306. func receiveTweets(sharedSecret [2][32]byte, leaderConn net.Conn, getArchive bool) {
  307. tmpNeededSubscriptions := neededSubscriptions
  308. if tmpNeededSubscriptions > len(topicList) {
  309. tmpNeededSubscriptions = len(topicList)
  310. }
  311. if getArchive {
  312. tmpNeededSubscriptions = len(archiveInterests)
  313. if tmpNeededSubscriptions > len(archiveTopicList) {
  314. tmpNeededSubscriptions = len(archiveTopicList)
  315. }
  316. }
  317. for i := 0; i < tmpNeededSubscriptions; i++ {
  318. //client receives tweets
  319. tweetsLengthBytes := readFrom(leaderConn, 4)
  320. tweetsLength := byteToInt(tweetsLengthBytes)
  321. tweets := readFrom(leaderConn, tweetsLength)
  322. //expand sharedSecret so it is of right length
  323. expandBy := len(tweets) / 32
  324. expandedSharedSecrets := make([][]byte, 2)
  325. for i := 0; i < 2; i++ {
  326. for j := 0; j < expandBy; j++ {
  327. expandedSharedSecrets[i] = append(expandedSharedSecrets[i], sharedSecret[i][:]...)
  328. }
  329. }
  330. //xors the received messge into the message to display
  331. for i := 0; i < 2; i++ {
  332. lib.Xor(expandedSharedSecrets[i][:], tweets)
  333. }
  334. index := strings.Index(string(tweets), ";;;")
  335. if index != -1 {
  336. //text := string(tweets)[:index]
  337. //fmt.Println(text)
  338. } else {
  339. fmt.Println("received text not of correct format", round, string(tweets))
  340. }
  341. }
  342. }
  343. //creates a shared secret for each server
  344. func createSharedSecret() [numClients][2][32]byte {
  345. var tmpSharedSecret [numClients][2][32]byte
  346. for i := 0; i < numClients; i++ {
  347. for j := 0; j < 2; j++ {
  348. _, err := rand.Read(tmpSharedSecret[i][j][:])
  349. if err != nil {
  350. panic("couldn't get randomness for sharedSecret!")
  351. }
  352. }
  353. }
  354. return tmpSharedSecret
  355. }
  356. func createAuditPIRQuery(clientNumber int) ([]byte, []byte) {
  357. //pirQuery [serverAmount][dbWriteSize]byte
  358. pirQuerys := make([][]byte, 2)
  359. for i := range pirQuerys {
  360. pirQuerys[i] = make([]byte, dbWriteSize)
  361. }
  362. //for leader
  363. //pirQuery will be filled with random bits
  364. for index := range pirQuerys[0] {
  365. bit := mr.Intn(2)
  366. pirQuerys[0][index] = byte(bit)
  367. }
  368. copy(pirQuerys[1], pirQuerys[0])
  369. //the positon the virtual address will be taken from
  370. pos := mr.Intn(dbWriteSize)
  371. pirQuerys[0][pos] = 1
  372. pirQuerys[1][pos] = 0
  373. //flattens the querys to be able to send them more efficently
  374. messagesFlattened := make([][]byte, 2)
  375. //adds the sharedSecret to the pirQuery
  376. for server := 0; server < 2; server++ {
  377. messagesFlattened[server] = append(messagesFlattened[server], sharedSecret[clientNumber][server][:]...)
  378. }
  379. for server := 0; server < 2; server++ {
  380. messagesFlattened[server] = append(messagesFlattened[server], pirQuerys[server][:]...)
  381. }
  382. var nonce [24]byte
  383. _, err := rand.Read(nonce[:])
  384. if err != nil {
  385. panic("couldn't get randomness for nonce!")
  386. }
  387. encryptedQueryLeader := box.Seal(nonce[:], messagesFlattened[0], &nonce, leaderPublicKey, clientPrivateKey)
  388. _, err = rand.Read(nonce[:])
  389. if err != nil {
  390. panic("couldn't get randomness for nonce!")
  391. }
  392. encryptedQueryFollower := box.Seal(nonce[:], messagesFlattened[1], &nonce, followerPublicKey, clientPrivateKey)
  393. return encryptedQueryLeader, encryptedQueryFollower
  394. }
  395. //generates a topicOfInterest array with random values
  396. func addFakeInterests(max int, topicsOfInterest []int, doAuditing bool) []int {
  397. tmpNeededSubscriptions := neededSubscriptions
  398. if tmpNeededSubscriptions > len(topicList) {
  399. tmpNeededSubscriptions = len(topicList)
  400. }
  401. fakeTopicsOfInterest := make([]int, tmpNeededSubscriptions)
  402. maxInt := max
  403. //fills the array with unique random ascending values ranging from 0 to max
  404. for i := 0; i < tmpNeededSubscriptions; i++ {
  405. fakeTopicsOfInterest[i] = mr.Intn(maxInt)
  406. for j := 0; j < i; j++ {
  407. if fakeTopicsOfInterest[i] == fakeTopicsOfInterest[j] {
  408. i--
  409. break
  410. }
  411. }
  412. }
  413. if doAuditing {
  414. sort.Ints(fakeTopicsOfInterest)
  415. return fakeTopicsOfInterest
  416. }
  417. //adds unique and new random numbers to topicOfInterests until length is satisfied
  418. for _, number := range fakeTopicsOfInterest {
  419. if !inList(number, topicsOfInterest) {
  420. topicsOfInterest = append(topicsOfInterest, number)
  421. }
  422. if len(topicsOfInterest) == tmpNeededSubscriptions {
  423. break
  424. }
  425. }
  426. sort.Ints(topicsOfInterest)
  427. return topicsOfInterest
  428. }
  429. func inList(number int, list []int) bool {
  430. for _, element := range list {
  431. if element == number {
  432. return true
  433. }
  434. }
  435. return false
  436. }
  437. func receiveTopicLists(leaderConn net.Conn) {
  438. for i := 0; i < 2; i++ {
  439. topicListLength := readFrom(leaderConn, 4)
  440. recTopicList := readFrom(leaderConn, byteToInt(topicListLength))
  441. var tmpTopicList []string
  442. arrayReader := bytes.NewReader(recTopicList[:])
  443. json.NewDecoder(arrayReader).Decode(&tmpTopicList)
  444. if i == 0 {
  445. topicList = tmpTopicList
  446. } else {
  447. archiveTopicList = tmpTopicList
  448. }
  449. }
  450. }
  451. func getTweet(clientNumber int) []byte {
  452. var tweet []byte
  453. r := mr.New(mr.NewSource(time.Now().UnixNano()))
  454. maxTopics := r.Intn(4)
  455. if maxTopics == 0 {
  456. maxTopics = 1
  457. }
  458. maxInt := 10
  459. topics := make([]byte, maxTopics)
  460. //fills the array with unique random ascending values ranging from 0 to max
  461. for i := 0; i < maxTopics; i++ {
  462. topics[i] = byte(mr.Intn(maxInt))
  463. for j := 0; j < i; j++ {
  464. if topics[i] == topics[j] {
  465. i--
  466. break
  467. }
  468. }
  469. }
  470. fmt.Println("topics", topics)
  471. text := []byte("I am a house in a mouse " + strconv.Itoa(r.Intn(100)) + ";")
  472. tweet = append(tweet, topics...)
  473. tweet = append(tweet, text...)
  474. tweet = append(tweet, []byte(";")[0])
  475. //adds padding
  476. length := dataLength - len(tweet)
  477. padding := make([]byte, length)
  478. rand.Read(padding)
  479. tweet = append(tweet, padding...)
  480. return tweet
  481. }
  482. //sends the array to the connection
  483. func writeTo(connection net.Conn, array []byte) {
  484. _, err := connection.Write(array)
  485. if err != nil {
  486. panic(err)
  487. }
  488. }
  489. //reads an array which is returned and of size "size" from the connection
  490. func readFrom(connection net.Conn, size int) []byte {
  491. array := make([]byte, size)
  492. _, err := connection.Read(array)
  493. if err != nil {
  494. panic(err)
  495. }
  496. return array
  497. }
  498. func intToByte(myInt int) (retBytes []byte) {
  499. retBytes = make([]byte, 4)
  500. retBytes[3] = byte((myInt >> 24) & 0xff)
  501. retBytes[2] = byte((myInt >> 16) & 0xff)
  502. retBytes[1] = byte((myInt >> 8) & 0xff)
  503. retBytes[0] = byte(myInt & 0xff)
  504. return
  505. }
  506. func byteToInt(myBytes []byte) (x int) {
  507. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  508. return
  509. }