Пример #1
0
/*
 * Create Dummy Devices
 */
func (t *Developer) createdevice(response http.ResponseWriter, request *http.Request) {
	//We Need to Create or update the Device for this Lease...
	deviceHelper, err := datastore.GetDeviceHelper()
	if err != nil {
		log.Println("Error: Getting Helper Error:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	macAddress, err := net.ParseMAC(mux.Vars(request)["macaddress"])
	if err != nil {
		log.Println("Error: Invalid MACAddress :" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	device, err := deviceHelper.GetDevice(macAddress)
	if err != nil {
		log.Println("Error: Getting Device Error:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	device.Hostname = mux.Vars(request)["hostname"]

	err = deviceHelper.SetDevice(&device)
	if err != nil {
		log.Println("Error: Setting Device To Datastore:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}
}
Пример #2
0
/*
 * Manually Assign an IP to a Mac Address
 */
func (t *Developer) assignip(response http.ResponseWriter, request *http.Request) {
	deviceHelper, err := datastore.GetDeviceHelper()
	if err != nil {
		log.Println("Error: Getting Helper Error:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	macAddress, err := net.ParseMAC(mux.Vars(request)["macaddress"])
	if err != nil {
		log.Println("Error: Invalid MACAddress :" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	device, err := deviceHelper.GetDevice(macAddress)
	if err != nil {
		log.Println("Error: Getting Device Error:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	device.IPAddress = net.ParseIP(mux.Vars(request)["ip"])

	err = deviceHelper.SetDevice(&device)
	if err != nil {
		log.Println("Error: Setting Device To Datastore:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}
}
Пример #3
0
func (t *Device) removeuser(response http.ResponseWriter, request *http.Request) {
	// Load the device with the MAC Address
	macAddress := mux.Vars(request)["macAddress"]
	deviceDataStoreHelper, err := datastore.GetDeviceHelper()
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	MACAddressHardware, err := net.ParseMAC(macAddress)
	if err != nil {
		log.Println("Mac Error:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	myDevice, err := deviceDataStoreHelper.GetDevice(MACAddressHardware)
	if err != nil {
		log.Println("Error Getting Device:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	myDevice.CurrentUser = nil

	err = deviceDataStoreHelper.SetDevice(&myDevice)
	// Check for error when deleting device.
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	http.Redirect(response, request, "/", http.StatusMovedPermanently)
}
Пример #4
0
func (t *Device) save(response http.ResponseWriter, request *http.Request) {
	// Load the device with the MAC Address.
	macAddress := request.FormValue("macAddress")
	deviceHelper, err := datastore.GetDeviceHelper()
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	MACAddressHardware, err := net.ParseMAC(macAddress)
	if err != nil {
		log.Println("Mac Error:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	device, err := deviceHelper.GetDevice(MACAddressHardware)

	// Check for error when loading device.
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	device.Nickname = request.FormValue("nickname")

	if request.FormValue("defaultUser") != "" {
		userHelper, err := datastore.GetUserHelper()
		if err != nil {
			log.Println("Error: Getting User Helper :" + err.Error())
			http.Error(response, err.Error(), 500)
			return
		}

		user, err := userHelper.GetUser(request.FormValue("defaultUser"))
		if err != nil {
			log.Println("Error: Getting User:"******"" {
			device.DefaultUser = &user
		} else {
			device.DefaultUser = nil
		}
	} else {
		device.DefaultUser = nil
	}

	err = deviceHelper.SetDevice(&device)
	// Check for error when saving device.
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	http.Redirect(response, request, t.Base()+"?savecomplete=true", http.StatusMovedPermanently)
}
Пример #5
0
func (t *Device) edit(response http.ResponseWriter, request *http.Request) {
	// Get the current session user.
	myuser := t.Sessions.CurrentUser(response, request)

	// Get the device.
	macAddress := mux.Vars(request)["macAddress"]
	deviceDataStoreHelper, err := datastore.GetDeviceHelper()
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	MACAddressHardware, err := net.ParseMAC(macAddress)
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	mydevice, err := deviceDataStoreHelper.GetDevice(MACAddressHardware)

	// Check for error when loading device.
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	// Get all users.
	userDataStoreHelper, err := datastore.GetUserHelper()
	if err != nil {
		log.Println("DB Error:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	allUsers, err := userDataStoreHelper.GetUsers()

	// Check for error when loading users.
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	// Setup the data structure to pass to the page.
	data := struct {
		Action   string
		Device   datastore.Device
		User     datastore.User
		AllUsers []datastore.User
	}{
		"deviceSettings",
		mydevice,
		myuser,
		allUsers,
	}

	// Parse the page and execute the template.
	tpl, err := template.ParseFiles("static/main.tpl", "static/main_authenticated.tpl", "static/devices/edit.tpl")
	tpl.Execute(response, data)
}
Пример #6
0
/**
 * Displays the device list.
 */
func (t *Device) index(response http.ResponseWriter, request *http.Request) {
	// Get the current session user.
	myuser := t.Sessions.CurrentUser(response, request)

	// If there isn't a current session user, redirect to login.
	if myuser.Username == "" {
		http.Redirect(response, request, "/login", http.StatusMovedPermanently)
		return
	}

	// Get the devices.
	deviceHelper, err := datastore.GetDeviceHelper()
	if err != nil {
		log.Println("DB Error:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	allDevices, err := deviceHelper.GetDevices()

	// Check for error when loading devices.
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	// Retrieve the savecomplete parameter from the URL and determine if it is true or not.
	saveCompleteParam := request.URL.Query().Get("savecomplete")
	saveComplete := saveCompleteParam == "true"

	// Setup the data structure to pass to the page.
	data := struct {
		Action       string
		User         datastore.User
		AllDevices   []datastore.Device
		SaveComplete bool
	}{
		"deviceSettings",
		myuser,
		allDevices,
		saveComplete,
	}

	// Parse the page and execute the template.
	tpl, err := template.ParseFiles("static/main.tpl", "static/main_authenticated.tpl", "static/devices/index.tpl")

	// Check for error when loading devices.
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	tpl.Execute(response, data)
}
Пример #7
0
func (t *Root) index(response http.ResponseWriter, request *http.Request) {
	// Get the current session user.
	user := t.Sessions.CurrentUser(response, request)

	// If there isn't a current session user, redirect to login.
	if user.Username == "" {
		http.Redirect(response, request, "/login", http.StatusMovedPermanently)
		return
	}

	// Get the devices for this user.
	deviceDataStoreHelper, err := datastore.GetDeviceHelper()
	if err != nil {
		log.Println("DB Error:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	currentUserDevices, defaultUserDevices, err := deviceDataStoreHelper.GetDevicesForUser(user.Username)

	// Check for an error when loading devices.
	if err != nil {
		log.Println("Error Getting Devices:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	// Setup the data structure to pass to the page.
	data := struct {
		Action         string
		User           datastore.User
		CurrentDevices []datastore.Device
		DefaultDevices []datastore.Device
	}{
		"index",
		user,
		currentUserDevices,
		defaultUserDevices,
	}

	// Parse the page and execute the template.
	tpl, _ := template.ParseFiles("static/main.tpl", "static/main_authenticated.tpl", "static/index.tpl")
	tpl.Execute(response, data)
}
Пример #8
0
func (this *Hosts) Get(hostname string) (bool, net.IP, error) {
	ip := this.Devices[hostname]

	if ip != nil {
		return true, ip, nil
	} else {
		//So we need to check the Device Record to see if the hostname is there also.
		helper, err := datastore.GetDeviceHelper()
		if err != nil {
			log.Println("Error Getting Datastore Helper:" + err.Error())
			return false, ip, err
		}
		device, err := helper.GetDeviceByHostname(hostname)
		if err != nil {
			log.Println("Error Looking Up Hostname:" + hostname + ":Error:" + err.Error())
			return false, ip, err
		}

		return false, device.IPAddress, err
	}
}
Пример #9
0
func Hijack(response dns.ResponseWriter, message *dns.Msg) (bool, error) {

	if (message.Question[0].Qtype == dns.TypeA || message.Question[0].Qtype == dns.TypeAAAA) && message.Question[0].Qclass == dns.ClassINET {

		ipString, _, err := net.SplitHostPort(response.RemoteAddr().String())
		if err != nil {
			log.Println("Warning: Received No IP4 Address:" + response.RemoteAddr().String())
			return false, err
		}

		ip := net.ParseIP(ipString)
		deviceHelper, err := datastore.GetDeviceHelper()
		if err != nil {
			log.Println("Error: Datastore Error (Open Access):" + err.Error())
			return false, err
		}

		device, err := deviceHelper.GetDeviceByIP(ip)
		if err != nil {
			log.Println("Error: Datastore Error (Open Access):" + err.Error())
			return false, err
		}

		if bytes.Equal(device.MACAddress, net.HardwareAddr{}) {
			//Device Doesn't exists?
			log.Println("Warning: IP:" + ipString + " MAC:" + device.MACAddress.String() + " Doesn't Exists As A Local Device But is Using Our DNS??")
			return false, nil
		} else {
			if activeUser := device.GetActiveUser(); activeUser != nil {
				//User is active check they have access.
				userFiltercollectionsHelper, err := datastore.GetUserFilterCollectionsHelper()
				if err != nil {
					return false, err
				}

				usersFiltercollection, err := userFiltercollectionsHelper.GetUserFilterCollections(activeUser.Username)
				if err != nil {
					return false, err
				}

				if usersFiltercollection.Username != "" {
					//Get the collections helper.
					filterCollectionsHelper, err := datastore.GetFilterCollectionHelper()
					if err != nil {
						return false, err
					}

					//Start Moving down the domain (i.e. removing subdomains etc)
					collections := make([]datastore.FilterCollection, 0)

					domain := strings.TrimSuffix(message.Question[0].Name, ".")

					for {
						additionalCollections, err := filterCollectionsHelper.GetFilterCollectionsWithDomain(domain)
						if err != nil {
							return false, err
						}

						if len(additionalCollections) > 0 {
							collections = append(collections, additionalCollections...)
						}

						if len(strings.SplitAfterN(domain, ".", 2)) == 2 {
							domain = strings.SplitAfterN(domain, ".", 2)[1]
						} else {
							break
						}
					}

					//Does the domain appear in any collections??
					for _, collection := range collections {
						if usersFiltercollection.ContainsCollection(collection.Name) {
							//The Url Should be blocked...
							//For Now lets just not respond with a DNS record...

							//localResponse := new(dns.Msg)
							//localResponse.SetReply(message)

							//rr_header := dns.RR_Header{Name: message.Question[0].Name, Class: dns.ClassINET, Ttl: 0}

							//Main Active IP
							//mainIPNetwork, err := networktools.MainActiveIPNetwork()
							//if err != nil {
							//	return false, err
							//}

							//switch message.Question[0].Qtype {

							//case dns.TypeA:
							//	rr_header.Rrtype = dns.TypeA
							//	a := &dns.A{rr_header, mainIPNetwork.IP}
							//	localResponse.Answer = append(localResponse.Answer, a)

							//case dns.TypeAAAA:
							//	rr_header.Rrtype = dns.TypeAAAA
							//}

							//err = response.WriteMsg(localResponse)
							//if err != nil {
							//	return false, err
							//}
							return true, nil
						}
					}

					return false, nil
				}
			} else {
				//User is not active redirect to login page.
				localResponse := new(dns.Msg)
				localResponse.SetReply(message)
				rr_header := dns.RR_Header{Name: message.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0}
				//Main Active IP
				mainIPNetwork, err := networktools.MainActiveIPNetwork()
				if err != nil {
					return false, err
				}
				a := &dns.A{rr_header, mainIPNetwork.IP}
				localResponse.Answer = append(localResponse.Answer, a)
				err = response.WriteMsg(localResponse)
				if err != nil {
					return false, err
				}
				return true, nil
			}
		}
	}

	return false, nil
}
Пример #10
0
func (t *connectionManager) Process() error {

	var wg sync.WaitGroup

	for i := 0; i < t.configuration.Manager.Agents; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()

			for {
				message := <-t.reader.output

				ipheader, err := ipv4.ParseHeader(message)
				if err != nil {
					log.Println("Error: Parsing IPHeader:" + err.Error())
					log.Printf("Message:%v\n", message)
					continue
				}

				if int(ipheader.Flags) < 2 {
					log.Printf("Warning: More Fragments Flag Is Set\n")
				}

				tcpheader, err := tcp.ParseHeader(message[ipheader.Len:])
				if err != nil {
					log.Println("Error: Parsing TCPHeader:" + err.Error())
					log.Printf("Message:%v\n", message)
					continue
				}

				connectionhelper, err := datastore.GetConnectionHelper()
				if err != nil {
					log.Printf("Error: Getting Connection Helper: %v\n", err.Error())
					return
				}

				connectionhelper.Lock()
				connection, err := connectionhelper.GetConnection(ipheader.Src, tcpheader.SourcePort, ipheader.Dst, tcpheader.DestinationPort)
				if err != nil {
					log.Printf("Error: Getting Connection: %v\n", err.Error())
					connectionhelper.Unlock()
					return
				}

				if bytes.Equal(connection.SourceIP(), net.IP{}) {
					//No connection found
					connection, err = datastore.NewConnectionFromPacketAndIPHeaderAndTCPHeader(message, ipheader, tcpheader)
					if err != nil {
						log.Printf("Error: Creating New Connection: %v\n", err.Error())
						connectionhelper.Unlock()
						continue
					}

					err = connectionhelper.SetConnection(connection)
					if err != nil {
						log.Printf("Error: Saving New Connection: %v\n", err.Error())
						connectionhelper.Unlock()
						continue
					}

				} else {
					//Connection found
					//We need to find out if the connection is still for this device and user
					devicehelper, err := datastore.GetDeviceHelper()
					if err != nil {
						log.Printf("Error: Getting Device Helper: %v\n", err.Error())
						connectionhelper.Unlock()
						return
					}

					device, err := devicehelper.GetDeviceByIP(ipheader.Src)
					if err != nil {
						log.Printf("Error: Getting Source Device By IP(%v) \"%v\"\n", ipheader.Src.String(), err.Error())
					}

					if bytes.Equal(device.MACAddress, net.HardwareAddr{}) {
						device, err = devicehelper.GetDeviceByIP(ipheader.Dst)
						if err != nil {
							log.Printf("Error: Getting Destination Device By IP(%v) \"%v\"\n", ipheader.Dst.String(), err.Error())
						}
					}

					//If we have a device, is now or it's empty
					currentuser := ""
					if device.GetActiveUser() != nil {
						currentuser = device.GetActiveUser().Username
					}

					//Device, User or Number of In Memory Packets Breached...
					if !bytes.Equal(device.MACAddress, connection.DeviceID()) || (connection.Username() != currentuser) || connection.NumberOfPackets() >= t.configuration.Manager.MaxPackets {
						//Device or User has changed.
						err = connectionhelper.RemoveConnection(connection)
						if err != nil {
							log.Printf("Error: Removing Connection: %v\n", err.Error())
							connectionhelper.Unlock()
							continue
						}

						//If a channel is registered and we had no errors closing it.
						if t.manager.output != nil {
							select {
							case t.manager.output <- connection:
							default:
								log.Println("Error: Manager Queue is full! Discarding Closed Connection..")
							}

						}

						//Create A New Connection
						connection, err := datastore.NewConnectionFromPacketAndIPHeaderAndTCPHeader(message, ipheader, tcpheader)
						if err != nil {
							log.Printf("Error: Creating New Connection After Remove: %v\n", err.Error())
							connectionhelper.Unlock()
							continue
						}

						err = connectionhelper.SetConnection(connection)
						if err != nil {
							log.Printf("Error: Saving New Connection After Remove: %v\n", err.Error())
							connectionhelper.Unlock()
							continue
						}
					} else {
						err = connection.AddPacket(message)
						if err != nil {
							log.Printf("Error: Adding Packet: %v\n", err.Error())
							connectionhelper.Unlock()
							continue
						}

						err = connectionhelper.SetConnection(connection)
						if err != nil {
							log.Printf("Error: Saving Packet after adding packet: %v\n", err.Error())
							connectionhelper.Unlock()
							continue
						}
					}

				}
				connectionhelper.Unlock()
			}

		}()
	}

	wg.Wait()
	log.Println("Error: We seem to be existing packet processing??")
	return errors.New("Error: Packet Processing Exited?")
}
Пример #11
0
func (t *Internet) index(response http.ResponseWriter, request *http.Request) {
	// Get the current session user.
	myuser := t.Sessions.CurrentUser(response, request)

	connectionhelper, err := datastore.GetConnectionHelper()
	if err != nil {
		log.Printf("Error: Failed to get Connections Helper \"%v\"", err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	// Get the devices.
	deviceHelper, err := datastore.GetDeviceHelper()
	if err != nil {
		log.Println("Error: DB Error:" + err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	connections, err := connectionhelper.GetConnections()
	if err != nil {
		log.Printf("Error: Failed to get Connections \"%v\"", err.Error())
		http.Error(response, err.Error(), 500)
		return
	}

	//TODO: Remove.
	connections = datastore.GetExampleConnections()

	devices, err := deviceHelper.GetDevices()
	// Check for error when loading devices.
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	mappedDevices := make(map[string]datastore.Device)

	for _, device := range devices {
		mappedDevices[device.MACAddress.String()] = device
	}

	hostnames := make(map[string]string)
	cache, err := dnsimplementation.GetCache()
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	for _, connection := range connections {
		//Lookup Source IP
		hostname, err := cache.GetHostname(connection.SourceIP())

		if err != nil {
			log.Printf("Error: Looking Up Hostname \"%v\"", err.Error())
		} else if hostname == "" {
			hostnames[connection.SourceIP().To4().String()] = connection.SourceIP().To4().String()
		} else {
			hostnames[connection.SourceIP().To4().String()] = hostname
		}

		//Lookup Destination IP
		hostname, err = cache.GetHostname(connection.DestinationIP())

		if err != nil {
			log.Printf("Error: Looking Up Hostname \"%v\"", err.Error())
		} else if hostname == "" {
			hostnames[connection.DestinationIP().To4().String()] = connection.DestinationIP().To4().String()
		} else {
			hostnames[connection.DestinationIP().To4().String()] = hostname
		}
	}

	connections = datastore.Connections(connections)

	// Setup the data structure to pass to the page.
	data := struct {
		Action      string
		User        datastore.User
		Connections datastore.Connections
		Devices     map[string]datastore.Device
		Hostnames   map[string]string
	}{
		"internet",
		myuser,
		connections,
		mappedDevices,
		hostnames,
	}

	// Parse the page and execute the template.
	tpl, err := template.ParseFiles("static/main.tpl", "static/main_authenticated.tpl", "static/internet/index.tpl")
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	err = tpl.Execute(response, data)
	if err != nil {
		log.Println(err)
		return
	}

}
Пример #12
0
func (t *Root) login(response http.ResponseWriter, request *http.Request) {
	if request.Method != "POST" {
		// Retrieve the loginFailed parameter from the URL and determine if it is true or not.
		loginFailedParam := request.URL.Query().Get("loginFailed")
		loginFailed := loginFailedParam == "true"

		// Add the loginFailed value to a data struct to pass to the template.
		data := struct {
			LoginFailed bool
		}{
			loginFailed,
		}

		tpl, _ := template.ParseFiles("static/main.tpl", "static/login.tpl")
		tpl.Execute(response, data)
	} else {

		request.ParseForm()

		hash := sha1.New()
		hash.Write([]byte(request.FormValue("password")))

		passwordHash := fmt.Sprintf("%x", hash.Sum(nil))

		helper, err := datastore.GetUserHelper()
		if err != nil {
			log.Println("DB Error:" + err.Error())
			http.Error(response, err.Error(), 500)
			return
		}

		myuser, err := helper.GetUser(request.FormValue("username"))
		if err != nil {
			log.Println("Error Looking Up User:"******"" && myuser.Username == request.FormValue("username") && myuser.Password == passwordHash {
			//Setup our session here.
			t.Sessions.SetCurrentUser(response, request, myuser)

			remoteIP, _, err := net.SplitHostPort(request.RemoteAddr)

			//We now need to assosiate the user with the current device :D
			deviceHelper, err := datastore.GetDeviceHelper()
			if err != nil {
				log.Println("DB Error:" + err.Error())
				http.Error(response, err.Error(), 500)
				return
			}

			device, err := deviceHelper.GetDeviceByIP(net.ParseIP(remoteIP))

			if err != nil {
				log.Println("Error Looking Up Device:" + err.Error())
				http.Error(response, err.Error(), 500)
				return
			}

			//Make sure the device is within our network.
			if device.MACAddress.String() != "" {
				//Device is within our network (It might have been external)
				device.CurrentUser = &myuser
				deviceHelper.SetDevice(&device)
			}

			// Login successful, display the user dashboard.
			t.Sessions.SessionInfo.SaveSession(response, request)
			http.Redirect(response, request, "/", http.StatusMovedPermanently)
			return
		} else {
			// Login unsuccessful, return to login screen.
			log.Println("Login Failed:" + myuser.Username)
			http.Redirect(response, request, "/login?loginFailed=true", http.StatusMovedPermanently)
			return
		}

	}
}