Commit ec974155 authored by Jakob Lerch's avatar Jakob Lerch
Browse files

initial commit

parent 0aeb0401
# FeM WiFiSetup
# FeMCAT
For further description see `DESCRIPTION.md`
* configuration assistant tool
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.fem-net.de/technik/fem-wifisetup.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.fem-net.de/technik/fem-wifisetup/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
* configure wifi
* fem.1x
* fem.psk
* turn off mac randomization
* introduced in android 8
* turned on per default in 10
/build
\ No newline at end of file
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.fem_wifisetup"
minSdk 21
targetSdk 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.annotation:annotation:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1'
implementation 'androidx.test:core-ktx:1.4.0'
implementation 'com.github.kittinunf.fuel:fuel:2.3.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
\ No newline at end of file
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
\ No newline at end of file
package com.example.fem_wifisetup
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.fem_wifisetup", appContext.packageName)
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fem_wifisetup">
<uses-feature android:name="android.hardware.touchscreen" android:required="false"/>
<uses-feature android:name="android.hardware.wifi" android:required="true"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.FeMWiFiSetup">
<activity
android:name=".MainActivity"
android:exported="false" />
<activity
android:name=".ui.login.LoginActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
\ No newline at end of file
package com.example.fem_wifisetup
import android.content.Intent
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiEnterpriseConfig
import android.net.wifi.WifiEnterpriseConfig.Eap
import android.net.wifi.WifiEnterpriseConfig.Phase2
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.example.fem_wifisetup.ui.login.LoginActivity
import com.github.kittinunf.fuel.Fuel
import java.io.*
import java.lang.Byte.decode
import java.net.URL
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import java.util.*
class MainActivity : AppCompatActivity() {
companion object {
private const val ANONYMOUS_IDENTITY = "eap"
private const val USERNAME = "eap"
private const val PASSWORD = "eap"
private const val PSK = "b2f822d2a87c7f70"
private const val SUBJECT_MATCH = "eap"
private const val ALTSUBJECT_MATCH = "eap"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// BUTTON: logout
val logout = findViewById<Button>(R.id.logout)
// write, what should happen at click
logout.setOnClickListener {
// logout
// start login activity (switch to login activity)
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
// BUTTON: configureFem1X
val configureFem1X = findViewById<Button>(R.id.fem1x)
configureFem1X.setOnClickListener {
val ssid = "FeM.PSK"
val wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
var config = WifiConfiguration()
// enable WiFi
wifiManager.isWifiEnabled = true
// TODO: start stuff in new thread
if (android.os.Build.VERSION.SDK_INT < 26) {
while (wifiManager.pingSupplicant() != true) {/* wait */}
}
while (wifiManager.wifiState != WifiManager.WIFI_STATE_ENABLED) {/* wait */}
// TODO: check, if the time waited suffices to view every configurations
// Use the existing profile for ssid if it exists
// ..read existing ssid profiles
val configs = wifiManager.configuredNetworks
// ..search for existing config for given ssid
var ssidExists = false
if (configs != null) {
for (c in configs) {
if (c.SSID == quote(ssid)) {
config = c
ssidExists = true
break
}
}
}
System.out.println(ssidExists)
// General purpose
config.SSID = quote(ssid)
// ..network is no hidden SSID
config.hiddenSSID = false;
// ..network is disabled initially
config.status = WifiConfiguration.Status.DISABLED // TODO: maybe enable it later?
// KeyManagement
config.allowedKeyManagement.clear()
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X)
// GroupCiphers
config.allowedGroupCiphers.clear()
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP)
// PairwiseCiphers
config.allowedPairwiseCiphers.clear()
// ..CCMP = WPA2 only
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP)
// Authentication Algorithms
config.allowedAuthAlgorithms.clear()
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN)
// Protocols
config.allowedProtocols.clear()
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN) // == WPA2
//config.preSharedKey = quote(PSK)
if (android.os.Build.VERSION.SDK_INT < 26) {
config.priority = 40
}
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
// Manage the CA certificate.
// ..check if required certificate is installed on system
// TODO
// ..if not: download certificate
// TODO
// ..and install certificate
// TODO
// ..get certificate as object
// TODO
// ..for debugging: download, read, use certificate without installation
// TODO: take crt-file if it is saved. if not download and save it
val cf = CertificateFactory.getInstance("X.509")
var decodedCert : String = ""
val response =
Fuel.get("https://info.fem.tu-ilmenau.de/admindb-php/downloads/1x-ca-cert.crt")
.response { request, response, result ->
val (bytes, error) = result
if (bytes != null) {
// ..read
//cert = cf.generateCertificate(bytes.inputStream()) as X509Certificate
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
decodedCert = Base64.getDecoder().decode(bytes).toString()
} else {
TODO("VERSION.SDK_INT < O")
}
} else {
// TODO: error treatment
println("error")
}
}
println(decodedCert)
var cert = cf.generateCertPath(decodedCert.byteInputStream()) as X509Certificate
// Create enterpriseConfig
// ..It has to be set as a member of a WifiConfiguration object
// ..to configure some more credentials.
val enterpriseConfig = WifiEnterpriseConfig()
enterpriseConfig.eapMethod = Eap.TTLS
enterpriseConfig.phase2Method = Phase2.PAP
enterpriseConfig.identity = USERNAME
enterpriseConfig.password = PASSWORD
enterpriseConfig.caCertificate = cert
enterpriseConfig.anonymousIdentity = Companion.ANONYMOUS_IDENTITY
// TODO: domain?
if (android.os.Build.VERSION.SDK_INT < 23) {
enterpriseConfig.subjectMatch = SUBJECT_MATCH
} else {
enterpriseConfig.altSubjectMatch = ALTSUBJECT_MATCH
}
config.enterpriseConfig = enterpriseConfig
// Enable network
// TODO: has been tested: good config was created by configuring manually.
// this config was copied and used for programmatically confuration with addNetwork.
// this did not work out. the config is good. issue is the call of addNetwork
if (!ssidExists) {
val networkId = wifiManager.addNetwork(config)
System.out.println(config)
System.out.println(networkId)
// TODO: error message if networkId == -1
wifiManager.enableNetwork(networkId, false)
} else {
System.out.println(config)
wifiManager.updateNetwork(config)
wifiManager.enableNetwork(config.networkId, false)
}
if (android.os.Build.VERSION.SDK_INT < 26) {
val saveConfiguration = wifiManager.saveConfiguration()
assert(!saveConfiguration)
}
}
}
}
/** automatically generated config
I/System.out: * ID: 9 SSID: "FeM.PSK" PROVIDER-NAME: null BSSID: null FQDN: null PRIO: 0 HIDDEN: false
I/System.out: NetworkSelectionStatus NETWORK_SELECTION_ENABLED
I/System.out: hasEverConnected: true
I/System.out: numAssociation 2
I/System.out: validatedInternetAccess
I/System.out: KeyMgmt: WPA_PSK Protocols: WPA RSN
I/System.out: AuthAlgorithms: OPEN
I/System.out: PairwiseCiphers: TKIP CCMP
I/System.out: GroupCiphers: WEP40 WEP104 TKIP CCMP
I/System.out: PSK: *
I/System.out: Enterprise config:
I/System.out: IP config:
I/System.out: IP assignment: DHCP
I/System.out: Proxy settings: NONE
I/System.out: cuid=1000 cname=android.uid.system:1000 luid=1000 lname=android.uid.system:1000 lcuid=1000 userApproved=USER_UNSPECIFIED noInternetAccessExpected=false roamingFailureBlackListTimeMilli: 1000
I/System.out: recentFailure: Association Rejection code: 0
*/
\ No newline at end of file
package com.example.fem_wifisetup
/**
* prevent instantiation (private constructor)
* prevent inheritance (final)
* reach methods from everywhere (public)
* methods are part of class, not object
*/
fun quote(string: String): String {
return "\"" + string + "\""
}
package com.example.fem_wifisetup.data
import com.example.fem_wifisetup.data.model.LoggedInUser
import java.io.IOException
/**
* Class that handles authentication w/ login credentials and retrieves user information.
*/
class LoginDataSource {
fun login(username: String, password: String): Result<LoggedInUser> {
try {
// TODO: handle loggedInUser authentication
val fakeUser = LoggedInUser(java.util.UUID.randomUUID().toString(), "Jane Doe")
return Result.Success(fakeUser)
} catch (e: Throwable) {
return Result.Error(IOException("Error logging in", e))
}
}
fun logout() {
// TODO: revoke authentication
}
}
\ No newline at end of file
package com.example.fem_wifisetup.data
import com.example.fem_wifisetup.data.model.LoggedInUser
/**
* Class that requests authentication and user information from the remote data source and
* maintains an in-memory cache of login status and user credentials information.
*/
class LoginRepository(val dataSource: LoginDataSource) {
// in-memory cache of the loggedInUser object
var user: LoggedInUser? = null
private set
val isLoggedIn: Boolean
get() = user != null
init {
// If user credentials will be cached in local storage, it is recommended it be encrypted
// @see https://developer.android.com/training/articles/keystore
user = null
}
fun logout() {
user = null
dataSource.logout()
}
fun login(username: String, password: String): Result<LoggedInUser> {
// handle login
val result = dataSource.login(username, password)
if (result is Result.Success) {
setLoggedInUser(result.data)
}
return result
}
private fun setLoggedInUser(loggedInUser: LoggedInUser) {
this.user = loggedInUser
// If user credentials will be cached in local storage, it is recommended it be encrypted
// @see https://developer.android.com/training/articles/keystore
}
}
\ No newline at end of file
package com.example.fem_wifisetup.data
/**
* A generic class that holds a value with its loading status.
* @param <T>
*/
sealed class Result<out T : Any> {
data class Success<out T : Any>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
override fun toString(): String {
return when (this) {
is Success<*> -> "Success[data=$data]"
is Error -> "Error[exception=$exception]"
}
}
}
\ No newline at end of file
package com.example.fem_wifisetup.data.model
/**
* Data class that captures user information for logged in users retrieved from LoginRepository
*/
data class LoggedInUser(
val userId: String,
val displayName: String
)
\ No newline at end of file
package com.example.fem_wifisetup.ui.login
/**
* User details post authentication that is exposed to the UI
*/
data class LoggedInUserView(
val displayName: String
//... other data fields that may be accessible to the UI
)
\ No newline at end of file
package com.example.fem_wifisetup.ui.login
import android.app.Activity
import android.content.Intent
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.fem_wifisetup.MainActivity