Compare commits

..
1 Commits
Author SHA1 Message Date
gmp 30db960cc2 Fix animation code. Retry GPG agent password prompt and clear
cache if the passphrase does not work.
2019-09-06 13:36:06 -04:00
27 changed files with 419 additions and 2321 deletions
-3
View File
@@ -1,6 +1,3 @@
cmd/passgo/passgo cmd/passgo/passgo
cmd/passgo-gui/passgo-gui cmd/passgo-gui/passgo-gui
nohup.out nohup.out
*.apk
*.idsig
/passgo-gui
BIN
View File
Binary file not shown.
-91
View File
@@ -1,91 +0,0 @@
package st.wow.git.passgo;
import java.lang.Runnable;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.content.Context;
import android.util.Log;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.view.View;
// Requests the storage permissions the app needs to read the password
// store in shared storage. On Android 11+ (API 30+) the
// MANAGE_EXTERNAL_STORAGE ("All files access") permission cannot be
// requested with a dialog; the user must toggle it in the system
// settings, so we launch that settings screen directly for this app.
public class Permissions extends Fragment {
Context ctx;
Handler handler;
final int PERMISSIONS_REQUEST = 1;
public Permissions(View view) {
Log.d("passgo", "Permissions()");
this.ctx = view.getContext();
this.handler = new Handler(this.ctx.getMainLooper());
Permissions inst = this;
handler.post(new Runnable() {
public void run() {
Activity act = (Activity)ctx;
FragmentTransaction ft = act.getFragmentManager().beginTransaction();
ft.add(inst, "Permissions");
ft.commitNow();
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.d("passgo", "Permissions onAttach()");
if (!(context instanceof Activity)) {
Log.w("passgo", "Context is not an Activity");
return;
}
Activity activity = (Activity) context;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
if (context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSIONS_REQUEST
);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
&& !Environment.isExternalStorageManager()) {
Log.d("passgo", "Requesting all files access");
Intent intent = new Intent(
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
Uri.parse("package:" + activity.getPackageName())
);
if (intent.resolveActivity(activity.getPackageManager()) != null) {
startActivity(intent);
} else {
Intent fallback = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
if (fallback.resolveActivity(activity.getPackageManager()) != null) {
startActivity(fallback);
} else {
Log.e("passgo", "No activity found for all files access settings");
}
}
}
}
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("passgo", "Permissions onActivityResult(" + requestCode + "): " + resultCode);
super.onActivityResult(requestCode, resultCode, data);
}
}
BIN
View File
Binary file not shown.
-375
View File
@@ -1,375 +0,0 @@
package st.wow.git.passgo;
import java.lang.Runnable;
import java.lang.String;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import android.os.Handler;
import android.os.IBinder;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import org.openintents.openpgp.IOpenPgpService2;
import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.util.OpenPgpApi;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.content.Context;
import android.content.ClipboardManager;
import android.content.ClipData;
import android.content.Intent;
import android.util.Log;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.IntentSender;
import android.content.IntentSender.OnFinished;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.Context;
import android.view.View;
public class PgpConnect extends Fragment {
Context ctx;
Handler handler;
ClipboardManager cb;
IOpenPgpService2 mService;
final int PERMISSIONS_REQUEST = 1;
// The OpenPgpApi in openpgp-api.jar calls through the IOpenPgpService2
// AIDL interface, so we must bind the service that implements that
// descriptor: org.openintents.openpgp.IOpenPgpService2 (Keychain >= 11 /
// standalone 5.x-6.x). The v1 action (IOpenPgpService) does not implement
// the v2 descriptor and dies with a SecurityException; the very old
// org.openintents.openpgp.api.OpenPgpService action (used by
// OpenPgpServiceConnection) no longer exists. Try in that order.
static final String[] SERVICE_ACTIONS = {
"org.openintents.openpgp.IOpenPgpService2",
"org.openintents.openpgp.IOpenPgpService",
"org.openintents.openpgp.api.OpenPgpService",
};
final ServiceConnection mConnection = new ServiceConnection() {
@Override public void onServiceConnected(ComponentName name, IBinder service) {
mService = IOpenPgpService2.Stub.asInterface(service);
Log.d("gio", "OpenPGP service connected: " + name);
}
@Override public void onServiceDisconnected(ComponentName name) {
mService = null;
Log.d("gio", "OpenPGP service disconnected");
}
};
private void bindOpenPgp() {
Intent bindIntent = null;
for (String action : SERVICE_ACTIONS) {
Intent i = new Intent(action);
i.setPackage("org.sufficientlysecure.keychain");
if (ctx.getPackageManager().resolveService(i, 0) != null) {
bindIntent = i;
break;
}
}
if (bindIntent == null) {
Log.e("gio", "No OpenPGP service found in org.sufficientlysecure.keychain");
return;
}
Log.d("gio", "Binding OpenPGP service: " + bindIntent.getAction());
ctx.bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
}
// executeApi needs a live service; the bind is asynchronous, so if the
// service is not connected yet, retry on the main looper (up to ~10 s)
// instead of calling into a null service.
private void runWhenConnected(final int chint, final Runnable task, final int attempt) {
if (mService != null) {
task.run();
return;
}
if (attempt > 33) {
Log.e("gio", "OpenPGP service never connected");
stringResult(chint, null);
return;
}
handler.postDelayed(new Runnable() {
public void run() {
runWhenConnected(chint, task, attempt + 1);
}
}, 300);
}
public PgpConnect(View view) {
Log.d("gio", "PgpConnect()");
this.ctx = view.getContext();
this.handler = new Handler(this.ctx.getMainLooper());
PgpConnect inst = this;
handler.post(new Runnable() {
public void run() {
Activity act = (Activity)ctx;
FragmentTransaction ft = act.getFragmentManager().beginTransaction();
ft.add(inst, "PgpConnect");
ft.commitNow();
}
});
}
@Override public void onAttach(Context ctx) {
super.onAttach(ctx);
Log.d("gio", "onAttach()");
if (ctx instanceof Activity) {
Log.d("gio", "It's an Activity!");
}
bindOpenPgp();
cb = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
if (ctx.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ctx.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST);
}
System.loadLibrary("gio");
installComplete(this);
}
//For debugging:
/*private void printExtras(Intent data) {
Bundle bundle = data.getExtras();
if (bundle != null) {
for (String k : bundle.keySet()) {
Log.d("gio", "extra:" + k);
}
}
}*/
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("gio", "onActivityResult(" + requestCode + "): " + resultCode);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
Log.d("gio", "onActivityResult: not OK");
stringResult(requestCode, null);
return;
}
switch (data.getAction()) {
case OpenPgpApi.ACTION_DECRYPT_VERIFY: {
Log.d("gio", "action decrypt");
_decrypt(data, requestCode);
break;
}
case OpenPgpApi.ACTION_ENCRYPT: {
Log.d("gio", "action encrypt");
_encrypt(data, requestCode);
break;
}
case OpenPgpApi.ACTION_GET_KEY_IDS:
Log.d("gio", "action getid");
String[] ids = data.getStringArrayExtra("user_ids");
if (ids != null && ids.length > 0) {
Log.d("gio", "got some IDs");
stringResult(requestCode, ids[0]);
} else {
Log.d("gio", "no ids");
stringResult(requestCode, null);
}
break;
default: {
Log.d("gio", "some other action");
}
}
}
public void Clip(byte []dat) {
ClipData clip = ClipData.newPlainText("PgpConnect", new String(dat));
cb.setPrimaryClip(clip);
}
public void GetId(int chint) {
if (handler == null) {
stringResult(chint, null);
return;
}
Log.d("gio", "GetId()");
handler.post(new Runnable() {
public void run() {
Intent data = new Intent();
data.setAction(OpenPgpApi.ACTION_GET_KEY_IDS);
//data.setAction(OpenPgpApi.ACTION_ENCRYPT);
data.putExtra(OpenPgpApi.EXTRA_USER_IDS, new String[]{" "});
_getid(data, chint);
}
});
}
public void Decrypt(byte []dat, int chint) {
if (handler == null) {
stringResult(chint, null);
return;
}
handler.post(new Runnable() {
public void run() {
Intent data = new Intent();
data.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY);
data.putExtra("DATA", dat);
_decrypt(data, chint);
}
});
}
private void _getid(Intent data, int chint) {
Log.d("gio","_getid");
runWhenConnected(chint, new Runnable() {
public void run() { doGetid(data, chint); }
}, 0);
}
private void doGetid(Intent data, int chint) {
InputStream is = null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(this.ctx, mService);
Intent result = api.executeApi(data, is, os);
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
Log.d("gio","_getid: success");
try {
String ret = os.toString("UTF-8");
//Log.d(OpenPgpApi.TAG, "output: " + ret);
stringResult(chint, ret);
} catch (UnsupportedEncodingException e) {
Log.e("gio", "UnsupportedEncodingException", e);
stringResult(chint, null);
}
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
Log.d("gio","_getid: interaction required");
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
try {
startIntentSenderForResult(pi.getIntentSender(), chint, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
Log.e("gio", "SendIntentException", e);
stringResult(chint, null);
}
break;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
Log.d("gio","_getid: error");
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
stringResult(chint, null);
}
}
}
private void _decrypt(Intent data, int chint) {
Log.d("gio","_decrypt");
runWhenConnected(chint, new Runnable() {
public void run() { doDecrypt(data, chint); }
}, 0);
}
private void doDecrypt(Intent data, int chint) {
byte []dat = data.getByteArrayExtra("DATA");
InputStream is = new ByteArrayInputStream(dat);
ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(this.ctx, mService);
Intent result = api.executeApi(data, is, os);
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
try {
String ret = os.toString("UTF-8");
//Log.d(OpenPgpApi.TAG, "output: " + ret);
stringResult(chint, ret);
} catch (UnsupportedEncodingException e) {
Log.e("gio", "UnsupportedEncodingException", e);
stringResult(chint, null);
}
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
try {
startIntentSenderForResult(pi.getIntentSender(), chint, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
Log.e("gio", "SendIntentException", e);
stringResult(chint, null);
}
break;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
stringResult(chint, null);
}
}
}
public void Encrypt(byte[] id, byte[] dat, int chint) {
if (handler == null) {
stringResult(chint, null);
return;
}
handler.post(new Runnable() {
public void run() {
Intent data = new Intent();
data.setAction(OpenPgpApi.ACTION_ENCRYPT);
data.putExtra(OpenPgpApi.EXTRA_USER_IDS, new String[]{new String(id)});
data.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
data.putExtra("DATA", dat);
_encrypt(data, chint);
}
});
}
private void _encrypt(Intent data, int chint) {
Log.d("gio","_encrypt");
runWhenConnected(chint, new Runnable() {
public void run() { doEncrypt(data, chint); }
}, 0);
}
private void doEncrypt(Intent data, int chint) {
byte []dat = data.getByteArrayExtra("DATA");
InputStream is = new ByteArrayInputStream(dat);
ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(this.ctx, mService);
Intent result = api.executeApi(data, is, os);
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
try {
String ret = os.toString("UTF-8");
//Log.d(OpenPgpApi.TAG, "output: " + ret);
stringResult(chint, ret);
} catch (UnsupportedEncodingException e) {
Log.e("gio", "UnsupportedEncodingException", e);
stringResult(chint, null);
}
if (result.hasExtra(OpenPgpApi.RESULT_SIGNATURE)) {
OpenPgpSignatureResult sigResult
= result.getParcelableExtra(OpenPgpApi.RESULT_SIGNATURE);
}
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
try {
IntentSender sender = pi.getIntentSender();
//Log.d("PgpConnect", "IntentSender:" + sender.toString());
startIntentSenderForResult(sender, chint, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
Log.e("gio", "SendIntentException", e);
stringResult(chint, null);
}
break;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
stringResult(chint, null);
break;
}
}
}
static private native void installComplete(PgpConnect p);
static private native void stringResult(int requestCode, String result);
}
+5 -37
View File
@@ -4,9 +4,8 @@ This repository includes Go code to interact with pass, the Unix password
manager. Library code is provided to open a password store, list manager. Library code is provided to open a password store, list
saved passwords, and decrypt specified passwords. The library provides saved passwords, and decrypt specified passwords. The library provides
a simple passphrase input function, or, if gpg-agent is running (on MacOS), a simple passphrase input function, or, if gpg-agent is running (on MacOS),
it will connect automatically to request your GPG passphrase. On Android, it will connect automatically to request your GPG passphrase. MacOS users
`passgo` connects to OpenKeychain. MacOS and Android users can also ask passgo can also ask passgo to copy a password directly to the clipboard.
to copy a password directly to the clipboard.
```go ```go
store := passgo.Store{} store := passgo.Store{}
@@ -16,7 +15,7 @@ err := passgo.GetStore(&store)
if err != nil { ... } if err != nil { ... }
passlist := store.List() passlist := store.List()
for _,x := range passlist { for _,x := range passlist {
if x.Pathname == "myPass" { if x.Pathname = "myPass" {
p, err := store.Decrypt(x.Pathname) p, err := store.Decrypt(x.Pathname)
if err == nil { if err == nil {
passgo.Clip(p) // put on the clipboard passgo.Clip(p) // put on the clipboard
@@ -25,38 +24,7 @@ for _,x := range passlist {
} }
} }
} }
/// or just do:
p, err := store.Decrypt("myPass")
...
``` ```
Also included is a simple GUI front-end using [Gio](https://gioui.org) Also included is a simple GUI front-end using [Gio](https://gioui.org). See
that works on MacOS and Android. See `cmd/passgo-gui`. `cmd/passgo-gui`.
## Building the Android APK
Use `scripts/build.sh` — do not build by hand:
```sh
./scripts/build.sh phone # build + install on the phone
./scripts/build.sh phone --no-install
./scripts/build.sh emu # emulator build (amd64)
```
It outputs `cmd/passgo-gui/passgo-gui.apk` (APKs are git-ignored and
regenerated by the script). The script, in order:
1. `gogio -target android -targetsdk 34` (from `~/go/bin`; packages the
Go code plus the `*.jar` JNI classes found in `cmd/passgo-gui/`),
2. apktool decode → inject `MANAGE_EXTERNAL_STORAGE` into the manifest
(gogio's hardcoded permission table lacks it, and without it the
system "All files access" toggle is grayed out on Android 11+) →
apktool rebuild,
3. sign with the debug keystore (`~/.android/debug.keystore`),
4. `adb install -r`.
Prereqs: JDK, Go + gogio, Android SDK at `~/android-sdk`
(platform-tools + build-tools 35.0.0). apktool v3.0.3 is auto-downloaded
to `~/android-sdk/tools/apktool.jar` if missing. The script checks each
prereq and says what is missing. The phone is reached via adb over the
WireGuard address (see the global AGENTS.md).
-64
View File
@@ -1,64 +0,0 @@
//go:build android
package main
import (
"os"
"gioui.org/app"
"gioui.org/io/event"
"git.wow.st/gmp/passgo"
)
var (
noidLabelText = "Enter a GPG key ID above"
)
func init() {
log(Info, "Android start")
// Use a larger font on Android
fontSize = 24
}
func handleEvent(e event.Event) {
switch e := e.(type) {
case app.AndroidViewEvent:
// A zero View means the view is detached (e.g. the activity going
// away on a recents-wipe); there is nothing to register for a
// detached view. A re-attach arrives as a fresh event with a live
// view.
if e.View != 0 {
initPgp(e.View)
initPermissions(e.View)
}
}
}
func initPgp(view uintptr) {
passgo.InitPgp(view)
}
func initPermissions(view uintptr) {
passgo.InitPermissions(view)
}
func getConfDir() (string, error) {
ret, err := app.DataDir()
if err != nil {
log(Error, "Cannot get data directory:", err)
return "", err
}
if _, err := os.Stat(ret); os.IsNotExist(err) {
err = os.MkdirAll(ret, 0700)
if err != nil {
log(Error, "Cannot create configuration directory ", ret)
return "", err
} else {
log(Info, "Configuration directory created")
return ret, nil
}
} else {
log(Info, "Configuration directory found")
return ret, nil
}
}
+27 -29
View File
@@ -1,63 +1,61 @@
//go:build darwin //+build darwin
package main package main
import ( import (
"io"
"os" "os"
"os/user" "os/user"
"path" "path"
"gioui.org/font/opentype" "golang.org/x/image/font/gofont/goregular"
"golang.org/x/image/font/sfnt"
) )
var ( var (
noidLabelText = "No GPG ids available. Please create a private key or enter a key ID above" regular *sfnt.Font
confDir string
) )
func setFont() error { func setFont() error {
f, err := os.Open("/System/Library/Fonts/AppleSDGothicNeo.ttc") f, err := os.Open("/System/Library/Fonts/AppleSDGothicNeo.ttc")
if err != nil { if err != nil {
log(Info, "Cannot open system font collection") log(Info, "Cannot open system font.")
return err return err
} }
defer f.Close() collection, err := sfnt.ParseCollectionReaderAt(f)
data, err := io.ReadAll(f)
if err != nil { if err != nil {
log(Info, "Cannot read system font collection") log(Info, "Cannot parse system font.")
return err return err
} }
fnts, err := opentype.ParseCollection(data) regular, err = collection.Font(0)
if err != nil { if err != nil {
log(Info, "Cannot parse font collection") log(Info, "Cannot access first font in collection.")
return err return err
} }
collection = append(collection, fnts...)
return nil return nil
} }
func init() { func init() {
fontSize = 16 err := setFont()
setFont()
}
func getConfDir() (string, error) {
usr, err := user.Current()
if err != nil { if err != nil {
log(Error, "Cannot get current user: ", err) regular, err = sfnt.Parse(goregular.TTF)
return "", err
}
ret := path.Join(usr.HomeDir, ".config/passgo")
if _, err := os.Stat(ret); os.IsNotExist(err) {
err = os.MkdirAll(ret, 0700)
if err != nil { if err != nil {
log(Info, "Cannot create configuration directory ", confDir) log(Fatal, "Cannot parse default font: ", err)
return "", err }
} else { }
log(Info, "Configuration directory created") usr, err := user.Current()
return ret, nil if err != nil {
log(Fatal, "Cannot get current user: ", err)
}
confDir = path.Join(usr.HomeDir, ".config/passgo")
if _, err := os.Stat(confDir); os.IsNotExist(err) {
err = os.MkdirAll(confDir, 0700)
if err != nil {
log(Info, "Cannot create configuration directory ", confDir)
log(Fatal, err)
} else {
log(Info, "Configuration directory created")
} }
} }
return ret, nil
} }
-33
View File
@@ -1,33 +0,0 @@
//go:build linux && !android
package main
import (
"os"
"gioui.org/app"
)
var (
noidLabelText = "No GPG ids available"
)
func init() {
fontSize = 16
}
func getConfDir() (string, error) {
ret, err := app.DataDir()
if err != nil {
log(Error, "Cannot get data directory:", err)
return "", err
}
if _, err := os.Stat(ret); os.IsNotExist(err) {
err = os.MkdirAll(ret, 0700)
if err != nil {
log(Error, "Cannot create configuration directory ", ret)
return "", err
}
}
return ret, nil
}
+38
View File
@@ -0,0 +1,38 @@
//+build !darwin
package main
import (
"os"
"os/user"
"path"
"golang.org/x/image/font/gofont/goregular"
"golang.org/x/image/font/sfnt"
)
var (
regular *sfnt.Font
confDir string
)
func init() {
regular, err = sfnt.Parse(goregular.TTF)
if err != nil {
log(Fatal, "Cannot parse default font: ", err)
}
usr, err := user.Current()
if err != nil {
log(Fatal, "Cannot get current user: ", err)
}
confDir = path.Join(usr.HomeDir, ".config/passgo")
if _, err := os.Stat(confDir); os.IsNotExist(err) {
err = os.MkdirAll(confDir, 0700)
if err != nil {
log(Info, "Cannot create configuration directory ", confDir)
log(Fatal, err)
} else {
log(Info, "Configuration directory created")
}
}
}
-10
View File
@@ -1,10 +0,0 @@
//go:build !android
package main
import (
"gioui.org/io/event"
)
func handleEvent(e event.Event) {
}
+193 -730
View File
File diff suppressed because it is too large Load Diff
+94 -114
View File
@@ -4,147 +4,127 @@ import (
"image" "image"
"image/color" "image/color"
"gioui.org/gesture" "gioui.org/ui"
"gioui.org/io/event" "gioui.org/ui/f32"
"gioui.org/layout" "gioui.org/ui/gesture"
"gioui.org/op/clip" "gioui.org/ui/input"
"gioui.org/op/paint" "gioui.org/ui/layout"
"gioui.org/text" "gioui.org/ui/paint"
"gioui.org/unit" "gioui.org/ui/pointer"
"gioui.org/widget/material" "gioui.org/ui/text"
) )
var ( var (
black = color.NRGBA{A: 0xff, R: 0, G: 0, B: 0} black = color.RGBA{A: 0xff, R: 0, G: 0, B: 0}
white = color.NRGBA{A: 0xff, R: 0xff, G: 0xff, B: 0xff} white = color.RGBA{A: 0xff, R: 0xff, G: 0xff, B: 0xff}
gray = color.NRGBA{A: 0xff, R: 0xf0, G: 0xf0, B: 0xf0} gray = color.RGBA{A: 0xff, R: 0xf0, G: 0xf0, B: 0xf0}
darkgray = color.NRGBA{A: 0xff, R: 0xa0, G: 0xa0, B: 0xa0} darkgray = color.RGBA{A: 0xff, R: 0xa0, G: 0xa0, B: 0xa0}
) )
type Overlay struct { type Overlay struct {
Size unit.Sp Face text.Face
Text string Text string
Click gesture.Click Click gesture.Click
Color color.NRGBA Color color.RGBA
Background color.NRGBA Background color.RGBA
Alignment text.Alignment Alignment text.Alignment
} }
func (b *Overlay) Layout(gtx C) D { func (b *Overlay) Layout(c ui.Config, ops *ui.Ops, cs layout.Constraints) layout.Dimensions {
ins := layout.UniformInset(unit.Dp(1)) ins := layout.UniformInset(ui.Dp(1))
return ins.Layout(gtx, func(gtx C) D { cs = ins.Begin(c, ops, cs)
st := layout.Stack{} var dims layout.Dimensions
c2 := layout.Stacked(func(gtx C) D { st := layout.Stack{}
l := material.Label(th, b.Size, b.Text) st.Init(ops, cs)
ins := layout.UniformInset(unit.Dp(4)) {
l.Color = b.Color cs = st.Rigid()
return ins.Layout(gtx, func(gtx C) D { l := text.Label{
return l.Layout(gtx) Face: b.Face,
}) Text: b.Text,
}) Alignment: b.Alignment,
c1 := layout.Expanded(func(gtx C) D { }
return layoutRRect(b.Background, gtx) ins := layout.UniformInset(ui.Dp(4))
}) l.Material.Record(ops)
return st.Layout(gtx, c1, c2) paint.ColorOp{Color: b.Color}.Add(ops)
}) l.Material.Stop()
} dims = ins.End(l.Layout(ops, ins.Begin(c, ops, cs)))
pointer.RectAreaOp{image.Rect(0, 0, dims.Size.X, dims.Size.Y)}.Add(ops)
type SelButton struct { }
Button c2 := st.End(dims)
SelColor color.NRGBA c1 := st.End(layoutRRect(b.Background, c, ops, st.Expand()))
Selected bool dims = st.Layout(c1, c2)
return ins.End(dims)
} }
type Button struct { type Button struct {
Size unit.Sp Face text.Face
Label string Label string
Click gesture.Click Click gesture.Click
Color color.NRGBA Color color.RGBA
Background color.NRGBA Background color.RGBA
Alignment text.Alignment Alignment text.Alignment
clicked bool clicked bool
} }
func layoutRRect(col color.NRGBA, gtx C) D { func layoutRRect(col color.RGBA, c ui.Config, ops *ui.Ops, cs layout.Constraints) layout.Dimensions {
r := gtx.Dp(4) r := float32(c.Px(ui.Dp(4)))
sz := image.Point{X: gtx.Constraints.Min.X, Y: gtx.Constraints.Min.Y} sz := image.Point{X: cs.Width.Min, Y: cs.Height.Min}
// Push the rounded-rect clip, paint, then restore the previous clip. w, h := float32(sz.X), float32(sz.Y)
stk := clip.UniformRRect(image.Rectangle{Max: sz}, r).Push(gtx.Ops) rrect(ops, w, h, r, r, r, r)
paint.ColorOp{Color: col}.Add(gtx.Ops) paint.ColorOp{Color: col}.Add(ops)
paint.PaintOp{}.Add(gtx.Ops) paint.PaintOp{Rect: f32.Rectangle{Max: f32.Point{X: w, Y: h}}}.Add(ops)
stk.Pop()
return layout.Dimensions{Size: sz} return layout.Dimensions{Size: sz}
} }
func (b *Button) Layout(gtx C) D { // https://pomax.github.io/bezierinfo/#circles_cubic.
mwidth := gtx.Constraints.Min.X func rrect(ops *ui.Ops, width, height, se, sw, nw, ne float32) {
w, h := float32(width), float32(height)
const c = 0.55228475 // 4*(sqrt(2)-1)/3
var b paint.PathBuilder
b.Init(ops)
b.Move(f32.Point{X: w, Y: h - se})
b.Cube(f32.Point{X: 0, Y: se * c}, f32.Point{X: -se + se*c, Y: se}, f32.Point{X: -se, Y: se}) // SE
b.Line(f32.Point{X: sw - w + se, Y: 0})
b.Cube(f32.Point{X: -sw * c, Y: 0}, f32.Point{X: -sw, Y: -sw + sw*c}, f32.Point{X: -sw, Y: -sw}) // SW
b.Line(f32.Point{X: 0, Y: nw - h + sw})
b.Cube(f32.Point{X: 0, Y: -nw * c}, f32.Point{X: nw - nw*c, Y: -nw}, f32.Point{X: nw, Y: -nw}) // NW
b.Line(f32.Point{X: w - ne - nw, Y: 0})
b.Cube(f32.Point{X: ne * c, Y: 0}, f32.Point{X: ne, Y: ne - ne*c}, f32.Point{X: ne, Y: ne}) // NE
b.End()
}
func (b *Button) Layout(c ui.Config, q input.Queue, ops *ui.Ops, cs layout.Constraints) layout.Dimensions {
b.clicked = false b.clicked = false
ins := layout.UniformInset(unit.Dp(1)) for ev, ok := b.Click.Next(q); ok; ev, ok = b.Click.Next(q) {
return ins.Layout(gtx, func(gtx C) D { if ev.Type == gesture.TypeClick {
st := layout.Stack{} b.clicked = true
c2 := layout.Stacked(func(gtx C) D { }
l := material.Label(th, b.Size, b.Label) }
l.Color = b.Color ins := layout.UniformInset(ui.Dp(1))
ins := layout.UniformInset(unit.Dp(4)) cs = ins.Begin(c, ops, cs)
ret := ins.Layout(gtx, func(gtx C) D { var dims layout.Dimensions
return l.Layout(gtx) st := layout.Stack{}
}) st.Init(ops, cs)
// Register the click handler for the whole button area, not {
// just the label: otherwise buttons with short labels (in cs = st.Rigid()
// full-width rows, for example) have a tiny tap target. l := text.Label{
hit := ret.Size Face: b.Face,
if hit.X < gtx.Constraints.Max.X { Text: b.Label,
hit.X = gtx.Constraints.Max.X Alignment: b.Alignment,
} }
stk := clip.Rect(image.Rectangle{Max: hit}).Push(gtx.Ops) ins := layout.UniformInset(ui.Dp(4))
event.Op(gtx.Ops, b) paint.ColorOp{Color: b.Color}.Add(ops)
b.Click.Add(gtx.Ops) dims = ins.End(l.Layout(ops, ins.Begin(c, ops, cs)))
stk.Pop() pointer.RectAreaOp{image.Rect(0, 0, dims.Size.X, dims.Size.Y)}.Add(ops)
for { b.Click.Add(ops)
ev, ok := b.Click.Update(gtx.Source) }
if !ok { c2 := st.End(dims)
break c1 := st.End(layoutRRect(b.Background, c, ops, st.Expand()))
} dims = st.Layout(c1, c2)
if ev.Kind == gesture.KindClick { return ins.End(dims)
b.clicked = true
}
}
return ret
})
c1 := layout.Expanded(func(gtx C) D {
gtx.Constraints.Min.X = mwidth
return layoutRRect(b.Background, gtx)
})
return st.Layout(gtx, c1, c2)
})
} }
func (b *Button) Clicked() bool { func (b *Button) Clicked() bool {
return b.clicked return b.clicked
} }
func (b *SelButton) Toggle() {
b.Selected = !b.Selected
b.SelColor, b.Background = b.Background, b.SelColor
}
func (b *SelButton) Select() {
if !b.Selected {
b.Toggle()
}
}
func (b *SelButton) Deselect() {
if b.Selected {
b.Toggle()
}
}
func (b *SelButton) Clicked() bool {
if b.clicked {
b.Toggle()
return true
} else {
return false
}
}
+1 -1
View File
@@ -69,7 +69,7 @@ func main() {
if opts.clip { if opts.clip {
passgo.Clip(p) passgo.Clip(p)
} else { } else {
fmt.Println(p) fmt.Print(p)
} }
default: default:
usage() usage()
-23
View File
@@ -1,23 +0,0 @@
module git.wow.st/gmp/passgo
go 1.24.0
require (
gioui.org v0.10.2
git.wow.st/gmp/clip v0.0.0-20191001134149-1458ba6a7cf5
git.wow.st/gmp/rand v0.0.0-20191001220155-a81bebfaf8b0
github.com/fsnotify/fsnotify v1.8.0
github.com/jcmdev0/gpgagent v0.0.0-20180509014935-5601b32d936c
golang.org/x/crypto v0.46.0
gopkg.in/yaml.v2 v2.2.7
)
require (
gioui.org/shader v1.0.9 // indirect
github.com/go-text/typesetting v0.3.4 // indirect
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0 // indirect
golang.org/x/image v0.26.0 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/text v0.32.0 // indirect
)
-40
View File
@@ -1,40 +0,0 @@
eliasnaur.com/font v0.0.0-20230308162249-dd43949cb42d h1:ARo7NCVvN2NdhLlJE9xAbKweuI9L6UgfTbYb0YwPacY=
eliasnaur.com/font v0.0.0-20230308162249-dd43949cb42d/go.mod h1:OYVuxibdk9OSLX8vAqydtRPP87PyTFcT9uH3MlEGBQA=
gioui.org v0.10.2 h1:bZU5CORROwc51sNha0zYdE2qWVaDncOp5EjV5nrZQZ8=
gioui.org v0.10.2/go.mod h1:iKILKNq6+LHMWhP/HjGDW/wDidUzRnb7B6c7ZD9y1Mg=
gioui.org/cpu v0.0.0-20210808092351-bfe733dd3334/go.mod h1:A8M0Cn5o+vY5LTMlnRoK3O5kG+rH0kWfJjeKd9QpBmQ=
gioui.org/shader v1.0.9 h1:XxnqIfmClWpN49kizxH2W0JcCFrrEP4q3jZmNYaltbs=
gioui.org/shader v1.0.9/go.mod h1:mWdiME581d/kV7/iEhLmUgUK5iZ09XR5XpduXzbePVM=
git.wow.st/gmp/clip v0.0.0-20191001134149-1458ba6a7cf5 h1:OKeTjZST+/TKvtdA258NXJH+/gIx/xwyZxKrAezNFvk=
git.wow.st/gmp/clip v0.0.0-20191001134149-1458ba6a7cf5/go.mod h1:NLdpaBoMQNFqncwP8OVRNWUDw1Kt9XWm3snfT7cXu24=
git.wow.st/gmp/rand v0.0.0-20191001220155-a81bebfaf8b0 h1:08wP00wvbDINsct1fzKV1xGGLvvtNsSb2X4CtIdpBzM=
git.wow.st/gmp/rand v0.0.0-20191001220155-a81bebfaf8b0/go.mod h1:8+2Gwnrpc5yuk8Wp6cBhxvGcNLumYiPbQ7n0SQ8h29A=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-text/typesetting v0.3.4 h1:YYurUOtEb9kGSOz4uE3k4OpBGsp1dDL8+fjCeaFamAU=
github.com/go-text/typesetting v0.3.4/go.mod h1:4qZCQphq4KSgGTAeI0uMEkVbROgfah8BuyF5LRYr7XY=
github.com/go-text/typesetting-utils v0.0.0-20260223113751-2d88ac90dae3 h1:drBZzMgdYPbmyXqOto4YhhJGrFIQCX94FpR4MzTCsos=
github.com/go-text/typesetting-utils v0.0.0-20260223113751-2d88ac90dae3/go.mod h1:3/62I4La/HBRX9TcTpBj4eipLiwzf+vhI+7whTc9V7o=
github.com/jcmdev0/gpgagent v0.0.0-20180509014935-5601b32d936c h1:DCnjNrPDSEslcqqBgcZBxlLUIhk2elQVyf2V+HkyxJI=
github.com/jcmdev0/gpgagent v0.0.0-20180509014935-5601b32d936c/go.mod h1:vdJ2op9pzpbH8CbpYKYBD6zjURqDY13PmnVn2I/uYBs=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM=
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8=
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0 h1:tMSqXTK+AQdW3LpCbfatHSRPHeW6+2WuxaVQuHftn80=
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:ygj7T6vSGhhm/9yTpOQQNvuAUFziTH7RUiH74EoE2C8=
golang.org/x/image v0.26.0 h1:4XjIFEZWQmCZi6Wv8BoxsDhRU3RVnLX04dToTDAEPlY=
golang.org/x/image v0.26.0/go.mod h1:lcxbMFAovzpnJxzXS3nyL83K27tmqtKzIJpctK8YO5c=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo=
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-115
View File
@@ -1,115 +0,0 @@
//go:build android
// +build android
// Regenerate PgpConnect.jar and Permissions.jar (gogio dexes every *.jar in
// the repo root; the two classes must stay in separate jars). ANDROID_HOME
// must be set. Note: go generate skips this file on non-android hosts.
//go:generate sh -c 'mkdir -p classes && javac -nowarn -classpath "$ANDROID_HOME/platforms/android-35/android.jar:openpgp-api.jar" -d classes PgpConnect.java Permissions.java && (cd classes && jar cf ../../PgpConnect.jar st/wow/git/passgo/PgpConnect* && jar cf ../../Permissions.jar st/wow/git/passgo/Permissions*) && rm -rf classes'
package passgo
/*
#import <jni.h>
#import "jni_android.h"
*/
import "C"
import (
"fmt"
"io/ioutil"
"log"
"path"
"strings"
"sync"
"unsafe"
"gioui.org/app"
_ "gioui.org/app/permission/storage"
//"git.wow.st/gmp/jni"
)
var (
jvm uintptr
waitch chan struct{}
//w *app.Window
pgp PGP
installCompleteOnce sync.Once
)
func init() {
waitch = make(chan struct{})
}
//export Java_st_wow_git_passgo_PgpConnect_installComplete
func Java_st_wow_git_passgo_PgpConnect_installComplete(env *C.JNIEnv, class C.jclass, p C.jobject) {
log.Printf("InstallComplete()")
pgp = PGP(C.NewGlobalRef(env, p))
installCompleteOnce.Do(func() {
close(waitch)
})
}
func InitPgp(view uintptr) {
log.Printf("InitPgp()")
if view == 0 {
return // detach signal; nothing to register
}
jvm = app.JavaVM()
SetJVM(jvm) // why?
RunInJVM(func(env *JNIEnv) {
C.registerFragment(env, (C.jobject)(unsafe.Pointer(view)))
})
}
// InitPermissions registers the Permissions fragment, which requests the
// storage permissions (launching the system "All files access" settings
// screen on Android 11+) so the app can read the store in shared storage.
func InitPermissions(view uintptr) {
log.Printf("InitPermissions()")
if view == 0 {
return // detach signal; nothing to register
}
RunInJVM(func(env *JNIEnv) {
C.registerPermissionsFragment(env, (C.jobject)(unsafe.Pointer(view)))
})
}
func stopPgp() {
waitch = make(chan struct{})
}
func connect() {
<-waitch
}
// Clip copies a string to the clipboard
func Clip(x string) {
pgp.Clip(x)
}
func (s *Store) nativeDecrypt(name string) (string, error) {
connect()
data, err := ioutil.ReadFile(path.Join(s.Dir, strings.Join([]string{name, ".gpg"}, "")))
if err != nil {
return "", fmt.Errorf("Error reading file: %s", err)
}
ret, err := pgp.Decrypt(string(data))
return ret, err
}
func (s *Store) nativeEncrypt(pw string) ([]byte, error) {
connect()
ret, err := pgp.Encrypt(s.Id, pw)
return []byte(ret), err
}
func nativeIdentities() ([]string, error) {
//NOT IMPLEMENTED ON ANDROID
return []string{}, nil
log.Printf("nativeIdentities()")
connect()
log.Printf("calling pgp.GetId()")
id, err := pgp.GetId()
log.Printf("pgp.GetId() returned")
return []string{id}, err
}
+7 -41
View File
@@ -1,24 +1,16 @@
//go:build darwin //+build darwin
// +build darwin
package passgo package passgo
import ( import (
"bufio" "bufio"
"encoding/hex" "bytes"
"fmt" "fmt"
"os" "os"
"os/exec" "os/exec"
"os/user" "os/user"
"path" "path"
"strconv" "strconv"
"strings"
"git.wow.st/gmp/clip"
"golang.org/x/crypto/openpgp"
"github.com/jcmdev0/gpgagent"
) )
func setAgentInfo() { func setAgentInfo() {
@@ -85,42 +77,16 @@ func setAgentInfo() {
// gpg-agent is running, so use GPGPrompt as password prompt // gpg-agent is running, so use GPGPrompt as password prompt
ask = GPGPrompt ask = GPGPrompt
}
func GPGPrompt(keys []openpgp.Key, symmetric bool) ([]byte, error) {
conn, err := gpgagent.NewGpgAgentConn()
if err != nil {
return nil, err
}
defer conn.Close()
for _, key := range keys {
cacheId := strings.ToUpper(hex.EncodeToString(key.PublicKey.Fingerprint[:]))
request := gpgagent.PassphraseRequest{CacheKey: cacheId}
for i := 0; i < 3; i++ {
var passphrase string
passphrase, err = conn.GetPassphrase(&request)
if err != nil {
continue
}
err = key.PrivateKey.Decrypt([]byte(passphrase))
if err != nil {
conn.RemoveFromCache(cacheId)
continue
}
return []byte(passphrase), nil
}
return nil, err
}
return nil, fmt.Errorf("Unable to find key")
} }
func init() { func init() {
setAgentInfo() setAgentInfo()
} }
// Clip copies a string to the clipboard //Clip copies a string to the clipboard
func Clip(x string) { func Clip(x string) {
clip.Set(x) b := bytes.NewBuffer([]byte(x))
cmd := exec.Command("pbcopy")
cmd.Stdin = b
cmd.Run()
} }
-17
View File
@@ -1,17 +0,0 @@
//go:build !android && linux
// +build !android,linux
package passgo
import (
"bytes"
"os/exec"
)
// Clip copies a string to the clipboard
func Clip(x string) {
b := bytes.NewBuffer([]byte(x))
cmd := exec.Command("xclip")
cmd.Stdin = b
cmd.Run()
}
+12
View File
@@ -0,0 +1,12 @@
//+build !darwin
package passgo
import (
"log"
)
//Clip copies a string to the clipboard
func Clip(x string) {
log(Info,"Clipboard not implemented for this platform")
}
-77
View File
@@ -1,77 +0,0 @@
//go:build darwin || (!android && linux)
// +build darwin !android,linux
package passgo
import (
"bufio"
"bytes"
"fmt"
"os"
"os/exec"
"path"
"strings"
"sync"
)
func (s *Store) nativeDecrypt(name string) (string, error) {
fmt.Println("calling gpg -d")
file := path.Join(s.Dir, strings.Join([]string{name, ".gpg"}, ""))
if _, err := os.Stat(file); os.IsNotExist(err) {
return "", fmt.Errorf("Not in password store.")
}
output, err := exec.Command("gpg", "-d", file).Output()
if err != nil {
return "", fmt.Errorf("Error running gpg: %s", err)
}
return string(output[:len(output)-1]), nil
}
func (s *Store) nativeEncrypt(pw string) ([]byte, error) {
if s.Id == "" {
return nil, fmt.Errorf("No ID")
}
fmt.Printf("Calling gpg -e -r %s\n", s.Id)
cmd := exec.Command("gpg", "-e", "-r", s.Id)
cmd.Stdin = strings.NewReader(pw + "\n")
output, err := cmd.Output()
if err != nil {
fmt.Printf("Error running GPG: %s\n", err)
return nil, err
}
fmt.Println("success")
return output, nil
}
var (
idMux sync.Mutex
cachedIdentities []string
)
func nativeIdentities() ([]string, error) {
idMux.Lock()
defer idMux.Unlock()
if cachedIdentities != nil {
ret := make([]string, len(cachedIdentities))
copy(ret, cachedIdentities)
return ret, nil
}
ret := make([]string, 0)
fmt.Println("calling gpg")
output, err := exec.Command("gpg", "--list-secret-keys", "--with-colons").Output()
if err != nil {
return nil, fmt.Errorf("Error running gpg: %s", err)
}
scanner := bufio.NewScanner(bytes.NewBuffer(output))
for scanner.Scan() {
fs := strings.Split(scanner.Text(), ":")
if fs[0] == "uid" {
fmt.Printf("%s: %s\n", fs[0], fs[9])
ret = append(ret, fs[9])
}
}
if len(ret) > 0 {
cachedIdentities = ret
}
return ret, nil
}
-121
View File
@@ -1,121 +0,0 @@
//#include <stdlib.h>
#include <stdio.h>
#include <jni.h>
#include "jni_android.h"
#include "_cgo_export.h"
void
registerFragment(JNIEnv *env, jobject view) {
if (view == NULL) {
// Detach signal (Gio sends ViewEvent{View: 0} when the view is
// destroyed, e.g. on a recents-wipe); the Go side already
// filters these, but GetObjectClass(null) aborts the process.
return;
}
jclass cls = (*env)->GetObjectClass(env, view);
jmethodID mid = (*env)->GetMethodID(env, cls, "getContext", "()Landroid/content/Context;");
jobject ctx = (*env)->CallObjectMethod(env, view, mid);
cls = (*env)->GetObjectClass(env, ctx);
mid = (*env)->GetMethodID(env, cls, "getClassLoader", "()Ljava/lang/ClassLoader;");
jobject loader = (*env)->CallObjectMethod(env, ctx, mid);
cls = (*env)->GetObjectClass(env, loader);
mid = (*env)->GetMethodID(env, cls, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
jstring str = (*env)->NewStringUTF(env, "st/wow/git/passgo/PgpConnect");
cls = (*env)->CallObjectMethod(env, loader, mid, str);
mid = (*env)->GetMethodID(env, cls, "<init>", "(Landroid/view/View;)V");
jobject inst = (*env)->NewObject(env, cls, mid, view);
}
void
registerPermissionsFragment(JNIEnv *env, jobject view) {
if (view == NULL) {
return; // detach signal; see registerFragment
}
jclass cls = (*env)->GetObjectClass(env, view);
jmethodID mid = (*env)->GetMethodID(env, cls, "getContext", "()Landroid/content/Context;");
jobject ctx = (*env)->CallObjectMethod(env, view, mid);
cls = (*env)->GetObjectClass(env, ctx);
mid = (*env)->GetMethodID(env, cls, "getClassLoader", "()Ljava/lang/ClassLoader;");
jobject loader = (*env)->CallObjectMethod(env, ctx, mid);
cls = (*env)->GetObjectClass(env, loader);
mid = (*env)->GetMethodID(env, cls, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
jstring str = (*env)->NewStringUTF(env, "st/wow/git/passgo/Permissions");
cls = (*env)->CallObjectMethod(env, loader, mid, str);
mid = (*env)->GetMethodID(env, cls, "<init>", "(Landroid/view/View;)V");
jobject inst = (*env)->NewObject(env, cls, mid, view);
}
void
GetId(JNIEnv* env, jobject p, int chint) {
jclass cls = (*env)->GetObjectClass(env, p);
jmethodID mid = (*env)->GetMethodID(env, cls, "GetId", "(I)V");
(*env)->CallObjectMethod(env, p, mid, chint);
}
void
Decrypt(JNIEnv* env, jobject p, char* cdata, int datalen, int chint) {
jbyteArray data = (*env)->NewByteArray(env, datalen);
if (datalen > 0) {
(*env)->SetByteArrayRegion(env, data, 0, datalen, cdata);
}
jclass cls = (*env)->GetObjectClass(env, p);
jmethodID mid = (*env)->GetMethodID(env, cls, "Decrypt", "([BI)V");
(*env)->CallVoidMethod(env, p, mid, data, chint);
}
void Java_st_wow_git_passgo_PgpConnect_stringResult(JNIEnv* env, jclass cls, jint requestCode, jobject response) {
if (response == 0) {
goStringResult(env, cls, requestCode, 0);
} else {
char* str = (*env)->GetStringUTFChars(env, response, NULL);
goStringResult(env, cls, requestCode, str);
}
}
void
Encrypt(JNIEnv* env, jobject p, char* cid, int idlen, char* cdata, int datalen, int chint) {
jbyteArray id = (*env)->NewByteArray(env, idlen);
if (idlen > 0) {
(*env)->SetByteArrayRegion(env, id, 0, idlen, cid);
}
jbyteArray data = (*env)->NewByteArray(env, datalen);
if (datalen > 0) {
(*env)->SetByteArrayRegion(env, data, 0, datalen, cdata);
}
jclass cls = (*env)->GetObjectClass(env, p);
jmethodID mid = (*env)->GetMethodID(env, cls, "Encrypt", "([B[BI)V");
(*env)->CallVoidMethod(env, p, mid, id, data, chint);
}
void
Clip(JNIEnv* env, jobject p, char* cdata, int datalen) {
jbyteArray data = (*env)->NewByteArray(env, datalen);
if (datalen > 0) {
(*env)->SetByteArrayRegion(env, data, 0, datalen, cdata);
}
jclass cls = (*env)->GetObjectClass(env, p);
jmethodID mid = (*env)->GetMethodID(env, cls, "Clip", "([B)V");
(*env)->CallVoidMethod(env, p, mid, data);
}
void CallVoidMethod(JNIEnv *env, jobject obj, jmethodID methodID) {
(*env)->CallVoidMethod(env, obj, methodID);
}
jint GetEnv(JavaVM *vm, JNIEnv **env, jint version) {
return (*vm)->GetEnv(vm, (void **)env, version);
}
jint AttachCurrentThread(JavaVM *vm, JNIEnv **p_env, void *thr_args) {
return (*vm)->AttachCurrentThread(vm, p_env, thr_args);
}
jint DetachCurrentThread(JavaVM *vm) {
return (*vm)->DetachCurrentThread(vm);
}
jobject
NewGlobalRef(JNIEnv *env, jobject o) {
return (*env)->NewGlobalRef(env, o);
}
-154
View File
@@ -1,154 +0,0 @@
package passgo
/*
#cgo LDFLAGS: -landroid -llog
#include <stdlib.h>
#include "jni_android.h"
*/
import "C"
import (
"errors"
"fmt"
"log"
"runtime"
"sync"
"unsafe"
)
var theJVM *C.JavaVM
type JNIEnv = C.JNIEnv
func SetJVM(jvm uintptr) {
log.Print("set theJVM")
theJVM = (*C.JavaVM)(unsafe.Pointer(jvm))
}
func JniCallVoidMethod(env *C.JNIEnv, obj C.jobject, methodID C.jmethodID) {
C.CallVoidMethod(env, obj, methodID)
}
type PGP C.jobject
var (
fragChans map[int]chan string
chmux sync.Mutex
chint int
)
func (p PGP) GetId() (string, error) {
ch := make(chan string)
chmux.Lock()
if fragChans == nil {
fragChans = make(map[int]chan string)
}
fragChans[chint] = ch
curint := chint
chint++
chmux.Unlock()
RunInJVM(func(env *JNIEnv) {
C.GetId(env, (C.jobject)(p), C.int(curint))
})
log.Printf("GetId(): waiting for response")
switch x := <-ch; {
case x == "":
log.Printf("GetId(): failed")
return "", fmt.Errorf("GetId failed")
default:
log.Printf("GetId(): got %s", x)
return x, nil
}
}
func (p PGP) Decrypt(data string) (string, error) {
ch := make(chan string)
chmux.Lock()
if fragChans == nil {
fragChans = make(map[int]chan string)
}
fragChans[chint] = ch
curint := chint
chint++
chmux.Unlock()
cdata := C.CString(data)
defer C.free(unsafe.Pointer(cdata))
RunInJVM(func(env *JNIEnv) {
C.Decrypt(env, (C.jobject)(p), (*C.char)(unsafe.Pointer(cdata)), (C.int)(len(data)), C.int(curint))
})
switch x := <-ch; {
case x == "":
return "", fmt.Errorf("Decryption failed")
default:
return x, nil
}
}
func (p PGP) Encrypt(id, data string) (string, error) {
ch := make(chan string)
chmux.Lock()
if fragChans == nil {
fragChans = make(map[int]chan string)
}
fragChans[chint] = ch
curint := chint
chint++
chmux.Unlock()
cid := C.CString(id)
defer C.free(unsafe.Pointer(cid))
cdata := C.CString(data)
defer C.free(unsafe.Pointer(cdata))
RunInJVM(func(env *JNIEnv) {
C.Encrypt(env, (C.jobject)(p), (*C.char)(unsafe.Pointer(cid)), (C.int)(len(id)), (*C.char)(unsafe.Pointer(cdata)), (C.int)(len(data)), C.int(curint))
})
switch x := <-ch; {
case x == "":
return "", fmt.Errorf("Encryption failed")
default:
return x, nil
}
}
func (p PGP) Clip(data string) {
cdata := C.CString(data)
defer C.free(unsafe.Pointer(cdata))
RunInJVM(func(env *JNIEnv) {
C.Clip(env, (C.jobject)(p), (*C.char)(unsafe.Pointer(cdata)), (C.int)(len(data)))
})
}
func RunInJVM(f func(env *C.JNIEnv)) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var env *C.JNIEnv
var detach bool
if res := C.GetEnv(theJVM, &env, C.JNI_VERSION_1_6); res != C.JNI_OK {
if res != C.JNI_EDETACHED {
panic(fmt.Errorf("JNI GetEnv failed with error %d", res))
}
if C.AttachCurrentThread(theJVM, &env, nil) != C.JNI_OK {
panic(errors.New("runInJVM: AttachCurrentThread failed"))
}
detach = true
}
if detach {
defer func() {
C.DetachCurrentThread(theJVM)
}()
}
f(env)
}
//export goStringResult
func goStringResult(env *C.JNIEnv, class C.jclass, request C.jint, str *C.char) {
fragChans[int(request)] <- C.GoString(str)
C.free(unsafe.Pointer(str))
chmux.Lock()
delete(fragChans, int(request))
chmux.Unlock()
}
-14
View File
@@ -1,14 +0,0 @@
#include <jni.h>
void registerFragment(JNIEnv *env, jobject view);
void registerPermissionsFragment(JNIEnv *env, jobject view);
void GetId(JNIEnv* env, jobject p, int chint);
void Decrypt(JNIEnv* env, jobject p, char* cdata, int datalen, int chint);
void Encrypt(JNIEnv* env, jobject p, char* cid, int idlen, char* cdata, int datalen, int chint);
void Clip(JNIEnv* env, jobject p, char* cdata, int datalen);
void stringResult(JNIEnv* env, jclass cls, jint requestCode, jobject response);
void CallVoidMethod(JNIEnv *env, jobject obj, jmethodID methodID);
jint GetEnv(JavaVM *vm, JNIEnv **env, jint version);
jint AttachCurrentThread(JavaVM *vm, JNIEnv **p_env, void *thr_args);
jint DetachCurrentThread(JavaVM *vm);
jobject NewGlobalRef(JNIEnv *env, jobject o);
+42 -120
View File
@@ -2,17 +2,18 @@ package passgo
import ( import (
"bufio" "bufio"
"encoding/hex"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"log"
"os" "os"
"os/user" "os/user"
"path" "path"
"regexp" "regexp"
"sort" "sort"
"strings" "strings"
"time"
"github.com/jcmdev0/gpgagent"
"golang.org/x/crypto/openpgp" "golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/armor"
@@ -20,23 +21,17 @@ import (
) )
var ( var (
basename *regexp.Regexp basename *regexp.Regexp
ask openpgp.PromptFunction ask openpgp.PromptFunction
Keyring openpgp.KeyRing
krTime time.Time
useNative bool
homeDir string
) )
func init() { func init() {
useNative = true // default unless we can get the Go openpgp code to work
basename = regexp.MustCompile(".gpg$") basename = regexp.MustCompile(".gpg$")
} }
type Store struct { type Store struct {
Dir string Dir string
Id string keyring openpgp.KeyRing
Empty bool
} }
func GetStore(store *Store) error { func GetStore(store *Store) error {
@@ -47,85 +42,20 @@ func GetStore(store *Store) error {
if store.Dir == "" { if store.Dir == "" {
store.Dir = path.Join(u.HomeDir, ".password-store") store.Dir = path.Join(u.HomeDir, ".password-store")
} }
if _, err := os.Stat(store.Dir); os.IsNotExist(err) {
store.Empty = true
} else {
store.Empty = false
}
id, err := ioutil.ReadFile(path.Join(store.Dir, ".gpg-id"))
if err != nil {
return fmt.Errorf("Can't read .gpg-id: %s", err)
}
// extract only the email address portion of the ID (required
// for Android)
if id[len(id)-1] == '\n' {
id = id[:len(id)-1]
}
for i := len(id) - 1; i > 0; i-- {
if id[i] == '>' {
for j := i - 1; j > 0; j-- {
if id[j] == '<' {
id = id[j+1 : i]
}
}
break
}
}
store.Id = string(id)
log.Printf("ID = %s", store.Id)
return getKeyring()
}
func getKeyring() error { fd, err := os.Open(path.Join(u.HomeDir, ".gnupg/secring.gpg"))
u, err := user.Current()
homeDir = u.HomeDir
krfile := path.Join(homeDir, ".gnupg/secring.gpg")
if fi, err := os.Stat(krfile); os.IsNotExist(err) {
return nil
} else {
if krTime.Sub(fi.ModTime()) > 0 { // already loaded
return nil
}
}
fmt.Println("Loading secring.gpg")
fd, err := os.Open(krfile)
defer fd.Close() defer fd.Close()
if err != nil { if err != nil {
return nil return fmt.Errorf("Can't open keyring file")
} }
kr, err := openpgp.ReadKeyRing(fd) kr, err := openpgp.ReadKeyRing(fd)
if err != nil { if err != nil {
//return fmt.Errorf("Can't open gnupg keyring.") return fmt.Errorf("Can't open gnupg keyring.")
return nil
} }
useNative = false store.keyring = kr
Keyring = kr
krTime = time.Now()
return nil return nil
} }
func (s *Store) Mkdir() error {
err := os.MkdirAll(s.Dir, 0700)
if err != nil {
fmt.Printf("Cannot create store directory.")
return err
}
s.Empty = false
return nil
}
func (s *Store) SetID(id string) error {
s.Id = id
if _, err := os.Stat(s.Dir); os.IsNotExist(err) {
fmt.Printf("store directory does not exist.\n")
err := s.Mkdir()
if err != nil {
return err
}
}
return ioutil.WriteFile(path.Join(s.Dir, ".gpg-id"), []byte(id+"\n"), 0644)
}
type caseInsensitive []os.FileInfo type caseInsensitive []os.FileInfo
func (fs caseInsensitive) Len() int { return len(fs) } func (fs caseInsensitive) Len() int { return len(fs) }
@@ -150,8 +80,6 @@ func (s *Store) list(level int, p string) ([]Pass, error) {
fd, err := os.Open(dir) fd, err := os.Open(dir)
defer fd.Close() defer fd.Close()
if err != nil { if err != nil {
log.Printf("password store directory = %s", dir)
log.Printf("error is %s", err)
return nil, fmt.Errorf("Cannot open password store") return nil, fmt.Errorf("Cannot open password store")
} }
files, err := fd.Readdir(0) files, err := fd.Readdir(0)
@@ -234,10 +162,36 @@ func AskPass(prompts ...func() []byte) openpgp.PromptFunction {
return ret return ret
} }
func (s *Store) Decrypt(name string, prompts ...func() []byte) (string, error) { //https://github.com/jcmdev0/gpgagent/blob/master/example/example.go
if useNative { func GPGPrompt(keys []openpgp.Key, symmetric bool) ([]byte, error) {
return s.nativeDecrypt(name) conn, err := gpgagent.NewGpgAgentConn()
if err != nil {
return nil, err
} }
defer conn.Close()
for _, key := range keys {
cacheId := strings.ToUpper(hex.EncodeToString(key.PublicKey.Fingerprint[:]))
request := gpgagent.PassphraseRequest{CacheKey: cacheId}
for i := 0; i < 3; i++ {
var passphrase string
passphrase, err = conn.GetPassphrase(&request)
if err != nil {
continue
}
err = key.PrivateKey.Decrypt([]byte(passphrase))
if err != nil {
conn.RemoveFromCache(cacheId)
continue
}
return []byte(passphrase), nil
}
return nil, err
}
return nil, fmt.Errorf("Unable to find key")
}
func (s *Store) Decrypt(name string, prompts ...func() []byte) (string, error) {
if ask == nil { if ask == nil {
ask = AskPass(prompts...) ask = AskPass(prompts...)
} }
@@ -263,7 +217,7 @@ func (s *Store) Decrypt(name string, prompts ...func() []byte) (string, error) {
} }
reader = fd reader = fd
} }
md, err := openpgp.ReadMessage(reader, Keyring, ask, nil) md, err := openpgp.ReadMessage(reader, s.keyring, ask, nil)
if err != nil { if err != nil {
fmt.Println("Error reading message") fmt.Println("Error reading message")
return "", err return "", err
@@ -272,37 +226,5 @@ func (s *Store) Decrypt(name string, prompts ...func() []byte) (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
if len(ra) > 1 { return string(ra), nil
return string(ra[:len(ra)-1]), nil
} else {
return "", fmt.Errorf("Password is empty")
}
}
func Identities() ([]string, error) {
log.Printf("Identities()")
getKeyring()
if useNative {
return nativeIdentities()
}
ret := make([]string, 0)
for _, k := range Keyring.DecryptionKeys() {
for n, _ := range k.Entity.Identities {
ret = append(ret, n)
}
}
return ret, nil
}
func (s *Store) Insert(name, value string) error {
var enc []byte
var err error
//if useNative { // golang openpgp code not implemented yet
fmt.Println("Calling nativeEncrypt")
enc, err = s.nativeEncrypt(value)
if err != nil {
return err
}
//}
return ioutil.WriteFile(path.Join(s.Dir, name+".gpg"), enc, 0644)
} }
BIN
View File
Binary file not shown.
-112
View File
@@ -1,112 +0,0 @@
#!/usr/bin/env bash
# Build (and optionally install) the passgo-gui Android APK.
#
# Usage:
# ./scripts/build.sh [phone|emu] # build + install (default: phone)
# ./scripts/build.sh phone --no-install # build only
#
# Output: cmd/passgo-gui/passgo-gui.apk
#
# Prereqs on this workstation:
# - JDK (java on PATH)
# - Go + gogio (~/go/bin)
# - Android SDK at ~/android-sdk (platform-tools, build-tools 35.0.0)
# - debug keystore at ~/.android/debug.keystore
# apktool is not a prerequisite: if it is missing, the script downloads
# v3.0.3 to the stable location ~/android-sdk/tools/apktool.jar.
#
# Why the apktool detour: gogio's manifest permissions come from a hardcoded
# table (only the legacy READ/WRITE_EXTERNAL_STORAGE). On Android 11+ the
# "All files access" settings toggle is grayed out unless the app declares
# MANAGE_EXTERNAL_STORAGE, which Permissions.java opens at startup. So we
# decode the gogio APK, inject the permission, rebuild, and re-sign with
# the debug key.
set -euo pipefail
REPO=$(cd "$(dirname "$0")/.." && pwd)
export ANDROID_HOME=${ANDROID_HOME:-$HOME/android-sdk}
export PATH=$PATH:$ANDROID_HOME/platform-tools:$ANDROID_HOME/build-tools/35.0.0:$HOME/go/bin
MODE=${1:-phone}
INSTALL=1
[ "${2:-}" = "--no-install" ] && INSTALL=0
case "$MODE" in
phone) ARCH="arm64,arm";;
emu) ARCH="amd64";;
*) echo "usage: $0 [phone|emu] [--no-install]" >&2; exit 1;;
esac
die() { echo "ERROR: $*" >&2; exit 1; }
command -v java >/dev/null 2>&1 || die "java not found"
command -v gogio >/dev/null 2>&1 || die "gogio not found (need ~/go/bin)"
command -v apksigner >/dev/null 2>&1 || die "apksigner not found (need $ANDROID_HOME/build-tools/35.0.0)"
command -v adb >/dev/null 2>&1 || die "adb not found (need $ANDROID_HOME/platform-tools)"
[ -f "$HOME/.android/debug.keystore" ] || die "debug keystore missing: $HOME/.android/debug.keystore"
# apktool: auto-download to a stable location if missing.
APKTOOL="$ANDROID_HOME/tools/apktool.jar"
if [ ! -f "$APKTOOL" ]; then
echo "=== apktool missing; downloading v3.0.3 to $APKTOOL ==="
mkdir -p "$ANDROID_HOME/tools"
curl -fsSL -o "$APKTOOL" \
https://github.com/iBotPeaches/Apktool/releases/download/v3.0.3/apktool_3.0.3.jar \
|| die "apktool download failed"
fi
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
echo "=== gogio (Go -> APK) ==="
# targetSdk 34: targeting 35 makes Android 15 force edge-to-edge, which the
# app does not handle.
(cd "$REPO/cmd/passgo-gui" && gogio -target android -targetsdk 34 -arch "$ARCH" -o "$WORK/passgo-raw.apk" .)
[ -f "$WORK/passgo-raw.apk" ] || die "gogio did not produce an APK"
echo "=== apktool decode + inject MANAGE_EXTERNAL_STORAGE ==="
java -jar "$APKTOOL" d "$WORK/passgo-raw.apk" -o "$WORK/decoded" -f >/dev/null
python3 - "$WORK/decoded/AndroidManifest.xml" << 'PYEOF'
import sys, pathlib
p = pathlib.Path(sys.argv[1])
t = p.read_text()
perm = '<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>'
if perm not in t:
t = t.replace(" <application", " " + perm + "\n <application", 1)
if perm not in t:
sys.exit("ERROR: failed to inject MANAGE_EXTERNAL_STORAGE")
# Android 11+ package visibility: without <queries> the app cannot even
# resolve (let alone bind) Keychain's OpenPGP service.
queries = """ <queries>
<package android:name="org.sufficientlysecure.keychain"/>
<intent>
<action android:name="org.openintents.openpgp.IOpenPgpService2"/>
</intent>
</queries>
"""
if "<queries>" not in t:
t = t.replace(" <application", queries + " <application", 1)
if "<queries>" not in t:
sys.exit("ERROR: failed to inject <queries>")
p.write_text(t)
print("manifest: MANAGE_EXTERNAL_STORAGE + <queries> present")
PYEOF
echo "=== apktool rebuild ==="
java -jar "$APKTOOL" b "$WORK/decoded" -o "$WORK/passgo-unsigned.apk" >/dev/null
echo "=== sign ==="
apksigner sign \
--ks "$HOME/.android/debug.keystore" --ks-pass pass:android \
--key-pass pass:android --ks-key-alias androiddebugkey \
--out "$REPO/cmd/passgo-gui/passgo-gui.apk" "$WORK/passgo-unsigned.apk"
# ADB_SERIAL selects the device when several are attached (adb devices).
ADB="adb${ADB_SERIAL:+ -s $ADB_SERIAL}"
if [ "$INSTALL" = "1" ]; then
echo "=== install ==="
$ADB get-state >/dev/null 2>&1 || die "no adb device (connect the phone; set ADB_SERIAL if several are attached)"
$ADB install -r "$REPO/cmd/passgo-gui/passgo-gui.apk"
fi
echo "=== DONE: $REPO/cmd/passgo-gui/passgo-gui.apk ==="