@eyeauras/insight-cli 0.5.8 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.cli-package-build.json +1 -1
- package/SKILL.md +1 -1
- package/dist/src/artifacts.d.ts +1 -1
- package/dist/src/artifacts.js +3 -3
- package/dist/src/cli.js +74 -15
- package/dist/src/contexts.d.ts +120 -10
- package/dist/src/contexts.js +510 -107
- package/dist/src/legacy-migration.d.ts +37 -0
- package/dist/src/legacy-migration.js +238 -0
- package/dist/src/lifecycle.d.ts +16 -5
- package/dist/src/lifecycle.js +43 -6
- package/dist/src/merge.d.ts +1 -1
- package/dist/src/merge.js +2 -2
- package/dist/src/model.d.ts +5 -0
- package/dist/src/model.js +2 -0
- package/dist/src/native-inputs.js +12 -2
- package/dist/src/native-merge-patches.d.ts +6 -0
- package/dist/src/native-merge-patches.js +100 -0
- package/dist/src/persistent-client.d.ts +8 -2
- package/dist/src/persistent-client.js +30 -8
- package/dist/src/projects.js +5 -4
- package/dist/src/research.d.ts +77 -14
- package/dist/src/research.js +99 -123
- package/dist/src/sdk-files.js +3 -3
- package/dist/src/server.d.ts +5 -1
- package/dist/src/server.js +46 -6
- package/dist/src/storage-gc.d.ts +23 -0
- package/dist/src/storage-gc.js +358 -0
- package/dist/src/sync-policy.js +4 -2
- package/dist/src/version-tracking.js +2 -1
- package/dist/src/workspace.d.ts +35 -2
- package/dist/src/workspace.js +91 -7
- package/package.json +1 -1
- package/references/native/APACHE-2.0.txt +202 -0
- package/references/native/HeadlessProgramMergeManager.java +86 -0
- package/references/native/InsightGuiMain.java +1 -0
- package/references/native/InsightHeadlessMain.java +1 -0
- package/references/native/InsightInitialImport.java +1 -1
- package/references/native/InsightNativeCheckout.java +214 -0
- package/references/native/InsightNativeFingerprint.java +53 -0
- package/references/native/InsightNativeMigration.java +155 -0
- package/references/native/InsightNativeRead.java +57 -0
- package/references/native/InsightNativeView.java +29 -0
- package/references/native/InsightOfflineAuthenticator.java +20 -0
- package/references/native/InsightSdkFiles.java +4 -0
- package/references/native/InsightSnapshotFields.java +17 -11
- package/references/native/InsightSnapshotInspect.java +4 -2
- package/references/native/NATIVE-MERGE-NOTICE.txt +15 -0
- package/references/persistent-client.mjs +30 -8
- package/references/persistent.md +47 -7
- package/references/recovery.md +50 -12
- package/references/research.md +25 -22
- package/references/setup.md +13 -3
- package/skill-bundle/insight-artifacts/SKILL.md +1 -1
- package/skill-bundle/insight-artifacts/references/recovery.md +50 -12
- package/skill-bundle/insight-binary/SKILL.md +1 -1
- package/skill-bundle/insight-capture/SKILL.md +1 -1
- package/skill-bundle/insight-cli/SKILL.md +1 -1
- package/skill-bundle/insight-cli/references/persistent-client.mjs +30 -8
- package/skill-bundle/insight-cli/references/persistent.md +47 -7
- package/skill-bundle/insight-cli/references/recovery.md +50 -12
- package/skill-bundle/insight-cli/references/setup.md +13 -3
- package/skill-bundle/insight-die/SKILL.md +1 -1
- package/skill-bundle/insight-dnspy/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
- package/skill-bundle/insight-frida/SKILL.md +1 -1
- package/skill-bundle/insight-ghidra/SKILL.md +8 -1
- package/skill-bundle/insight-ghidra/references/persistent-client.mjs +30 -8
- package/skill-bundle/insight-ghidra/references/persistent.md +47 -7
- package/skill-bundle/insight-ghidra/references/recovery.md +50 -12
- package/skill-bundle/insight-ghidra/references/research.md +25 -22
- package/skill-bundle/insight-ghidra/references/setup.md +13 -3
- package/skill-bundle/insight-ilspy/SKILL.md +1 -1
- package/skill-bundle/insight-interop/SKILL.md +1 -1
- package/skill-bundle/insight-lldb/SKILL.md +1 -1
- package/skill-bundle/insight-llvm/SKILL.md +1 -1
- package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
- package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
- package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
- package/skill-bundle/insight-overview/SKILL.md +1 -1
- package/skill-bundle/insight-procmon/SKILL.md +1 -1
- package/skill-bundle/insight-re/SKILL.md +1 -1
- package/skill-bundle/insight-re/references/persistent-client.mjs +30 -8
- package/skill-bundle/insight-re/references/persistent.md +47 -7
- package/skill-bundle/insight-re/references/recovery.md +50 -12
- package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
- package/skill-bundle/insight-strace/SKILL.md +1 -1
- package/skill-bundle/insight-tshark/SKILL.md +1 -1
- package/skill-bundle/insight-windbg/SKILL.md +1 -1
- package/skill-bundle/manifest.json +1 -1
- package/skills/insight-artifacts/SKILL.md +1 -1
- package/skills/insight-artifacts/references/recovery.md +50 -12
- package/skills/insight-binary/SKILL.md +1 -1
- package/skills/insight-capture/SKILL.md +1 -1
- package/skills/insight-die/SKILL.md +1 -1
- package/skills/insight-dnspy/SKILL.md +1 -1
- package/skills/insight-dotnet-dump/SKILL.md +1 -1
- package/skills/insight-dotnet-stack/SKILL.md +1 -1
- package/skills/insight-dotnet-trace/SKILL.md +1 -1
- package/skills/insight-frida/SKILL.md +1 -1
- package/skills/insight-ghidra/SKILL.md +8 -1
- package/skills/insight-ghidra/references/persistent-client.mjs +30 -8
- package/skills/insight-ghidra/references/persistent.md +47 -7
- package/skills/insight-ghidra/references/recovery.md +50 -12
- package/skills/insight-ghidra/references/research.md +25 -22
- package/skills/insight-ghidra/references/setup.md +13 -3
- package/skills/insight-ilspy/SKILL.md +1 -1
- package/skills/insight-interop/SKILL.md +1 -1
- package/skills/insight-lldb/SKILL.md +1 -1
- package/skills/insight-llvm/SKILL.md +1 -1
- package/skills/insight-managed-heap/SKILL.md +1 -1
- package/skills/insight-managed-metadata/SKILL.md +1 -1
- package/skills/insight-mitmproxy/SKILL.md +1 -1
- package/skills/insight-overview/SKILL.md +1 -1
- package/skills/insight-procmon/SKILL.md +1 -1
- package/skills/insight-re/SKILL.md +1 -1
- package/skills/insight-re/references/persistent-client.mjs +30 -8
- package/skills/insight-re/references/persistent.md +47 -7
- package/skills/insight-re/references/recovery.md +50 -12
- package/skills/insight-sevenzip/SKILL.md +1 -1
- package/skills/insight-strace/SKILL.md +1 -1
- package/skills/insight-tshark/SKILL.md +1 -1
- package/skills/insight-windbg/SKILL.md +1 -1
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import insight.nativecheckout.InsightSnapshotFields;
|
|
2
|
+
import insight.nativecheckout.InsightSnapshotInspect;
|
|
3
|
+
import com.google.gson.*;
|
|
4
|
+
import com.xebyte.headless.GhidraServerManager;
|
|
5
|
+
import ghidra.GhidraApplicationLayout;
|
|
6
|
+
import ghidra.framework.*;
|
|
7
|
+
import ghidra.framework.client.RepositoryAdapter;
|
|
8
|
+
import ghidra.framework.model.*;
|
|
9
|
+
import ghidra.framework.project.DefaultProjectManager;
|
|
10
|
+
import ghidra.framework.data.*;
|
|
11
|
+
import ghidra.program.database.ProgramDB;
|
|
12
|
+
import ghidra.program.model.listing.Program;
|
|
13
|
+
import ghidra.util.task.TaskMonitor;
|
|
14
|
+
import insight.nativecheckout.HeadlessProgramMergeManager;
|
|
15
|
+
import db.InsightNativeFingerprint;
|
|
16
|
+
import java.nio.file.*;
|
|
17
|
+
import java.nio.channels.FileChannel;
|
|
18
|
+
import java.util.*;
|
|
19
|
+
|
|
20
|
+
/** Service-only native lifecycle. Native checkouts and their native change sets are never synthesized. */
|
|
21
|
+
public final class InsightNativeCheckout {
|
|
22
|
+
static final TaskMonitor MONITOR=TaskMonitor.DUMMY;
|
|
23
|
+
static final Object CONSUMER=new Object();
|
|
24
|
+
static boolean permitMerge=true;
|
|
25
|
+
static class Projects extends DefaultProjectManager {Projects(){super();}}
|
|
26
|
+
static final class HeadChanged extends RuntimeException {HeadChanged(){super("Shared head changed before native check-in");}}
|
|
27
|
+
static class Factory extends ghidra.program.database.GhidraProgramMultiUserMergeManagerFactory {
|
|
28
|
+
@Override protected DomainObjectMergeManager doGetMergeManager(DomainObject result,DomainObject mine,DomainObject original,DomainObject latest){
|
|
29
|
+
// Check-in must commit the already journaled candidate. A server race aborts, never silently changes that candidate.
|
|
30
|
+
if(!permitMerge)throw new HeadChanged();
|
|
31
|
+
return new HeadlessProgramMergeManager((Program)result,(Program)mine,(Program)original,(Program)latest,
|
|
32
|
+
((ProgramDB)latest).getChanges(),((ProgramDB)mine).getChanges());
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
static void require(boolean value,String reason){if(!value)throw new IllegalStateException(reason);}
|
|
36
|
+
static String text(JsonObject q,String name){return q.get(name).getAsString();}
|
|
37
|
+
static final Gson GSON=new GsonBuilder().serializeNulls().create();
|
|
38
|
+
static void write(Path path,Object value)throws Exception {
|
|
39
|
+
Path temporary=path.resolveSibling(path.getFileName()+".new-"+UUID.randomUUID());
|
|
40
|
+
try(var channel=FileChannel.open(temporary,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){
|
|
41
|
+
var bytes=java.nio.ByteBuffer.wrap(GSON.toJson(value).getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
|
42
|
+
while(bytes.hasRemaining())channel.write(bytes);channel.force(true);
|
|
43
|
+
}
|
|
44
|
+
Files.move(temporary,path,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);
|
|
45
|
+
if(!System.getProperty("os.name").startsWith("Windows"))try(var channel=FileChannel.open(path.getParent(),StandardOpenOption.READ)){channel.force(true);}
|
|
46
|
+
}
|
|
47
|
+
static void source(Program p,JsonObject owner){
|
|
48
|
+
require(p.getExecutableSHA256().equals(text(owner,"sourceSha")),"Native source identity changed");
|
|
49
|
+
if(!p.getOptions("Insight").getString("Publication Engine","").equals("native-checkout-v1"))throw new InsightNativeMigration.Required();
|
|
50
|
+
}
|
|
51
|
+
static Map<String,Object> saved(DomainFile file,JsonObject owner)throws Exception {
|
|
52
|
+
Program p=(Program)file.getDomainObject(CONSUMER,false,false,MONITOR);
|
|
53
|
+
try{source(p,owner);return Map.of("fingerprint",InsightNativeFingerprint.of(p),"version",file.getVersion(),"fileId",file.getFileID(),
|
|
54
|
+
"language",p.getLanguageID().toString(),"compiler",p.getCompilerSpec().getCompilerSpecID().toString(),"imageBase",p.getImageBase().toString());}
|
|
55
|
+
finally{p.release(CONSUMER);}
|
|
56
|
+
}
|
|
57
|
+
/** Every file with local bytes, at any depth; unmodified server items have none. */
|
|
58
|
+
static void local(DomainFolder folder,Set<String> names){
|
|
59
|
+
for(DomainFile f:folder.getFiles())if(!f.isVersioned()||f.isCheckedOut()||f.isHijacked()||f.canRecover())names.add(f.getPathname().substring(1));
|
|
60
|
+
for(DomainFolder child:folder.getFolders())if(!child.isLinked())local(child,names);
|
|
61
|
+
}
|
|
62
|
+
static boolean released(Path root,JsonObject q)throws Exception {
|
|
63
|
+
Path path=root.resolve("released.json");if(!Files.exists(path))return false;
|
|
64
|
+
var released=JsonParser.parseString(Files.readString(path)).getAsJsonObject();
|
|
65
|
+
return text(released,"state").equals("released")&&released.get("checkoutId").equals(q.get("checkoutId"))&&
|
|
66
|
+
released.get("fingerprint").equals(q.get("fingerprint"))&&released.get("version").equals(q.get("verifiedVersion"));
|
|
67
|
+
}
|
|
68
|
+
static void deleteReleased(Path root,ProjectLocator locator)throws Exception {
|
|
69
|
+
for(Path target:List.of(locator.getProjectDir().toPath(),locator.getMarkerFile().toPath())){
|
|
70
|
+
if(!Files.exists(target,LinkOption.NOFOLLOW_LINKS))continue;
|
|
71
|
+
require(!Files.isSymbolicLink(target)&&target.toRealPath().getParent().equals(root),"Native deletion escaped owned project");
|
|
72
|
+
// Validate the whole tree first: a Windows junction is a directory whose children live elsewhere.
|
|
73
|
+
List<Path> entries=new ArrayList<>();
|
|
74
|
+
Files.walkFileTree(target,new SimpleFileVisitor<Path>(){
|
|
75
|
+
FileVisitResult visit(Path path,java.nio.file.attribute.BasicFileAttributes at){require(!at.isSymbolicLink()&&!at.isOther(),"Native deletion met a link");entries.add(path);return FileVisitResult.CONTINUE;}
|
|
76
|
+
@Override public FileVisitResult preVisitDirectory(Path path,java.nio.file.attribute.BasicFileAttributes at)throws java.io.IOException{require(path.toRealPath().startsWith(root),"Native deletion escaped owned project");return visit(path,at);}
|
|
77
|
+
@Override public FileVisitResult visitFile(Path path,java.nio.file.attribute.BasicFileAttributes at){return visit(path,at);}
|
|
78
|
+
});
|
|
79
|
+
Collections.reverse(entries);for(Path entry:entries)Files.delete(entry);
|
|
80
|
+
}
|
|
81
|
+
require(!locator.getMarkerFile().exists()&&!locator.getProjectDir().exists(),"Native project remains");
|
|
82
|
+
}
|
|
83
|
+
static void history(RepositoryAdapter repository,String path,Map<String,Object> out)throws Exception {
|
|
84
|
+
String name=path.substring(1);
|
|
85
|
+
out.put("versions",Arrays.stream(repository.getVersions("/",name)).map(v->Map.of("version",v.getVersion(),"comment",Objects.toString(v.getComment(),""))).toList());
|
|
86
|
+
out.put("checkouts",Arrays.stream(repository.getCheckouts("/",name)).map(c->Map.of("id",c.getCheckoutId(),"version",c.getCheckoutVersion(),"user",c.getUser())).toList());
|
|
87
|
+
out.put("checkinActive",repository.isCheckinActive("/",name));
|
|
88
|
+
}
|
|
89
|
+
public static void main(String[] args){
|
|
90
|
+
var output=System.out;System.setOut(System.err);Project project=null;GhidraServerManager server=null;
|
|
91
|
+
Map<String,Object> out=new LinkedHashMap<>();
|
|
92
|
+
try {
|
|
93
|
+
require(args.length==1,"Owned request required");
|
|
94
|
+
JsonObject q=JsonParser.parseString(Files.readString(Path.of(args[0]))).getAsJsonObject();
|
|
95
|
+
Path root=Path.of(text(q,"root")).toRealPath();JsonObject owner=JsonParser.parseString(Files.readString(root.resolve("native-owner.json"))).getAsJsonObject();
|
|
96
|
+
require(owner.equals(q.getAsJsonObject("owner")),"Native owner receipt changed");
|
|
97
|
+
require(text(owner,"protocol").equals("native-checkout-v1")&&text(owner,"path").equals("/"+text(owner,"target")+".bin"),"Malformed native binding");
|
|
98
|
+
String operation=text(q,"operation"),path=text(owner,"path"),name=path.substring(1);
|
|
99
|
+
Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
|
|
100
|
+
Class.forName("ghidra.program.database.ProgramMultiUserMergeManagerFactory");
|
|
101
|
+
PluggableServiceRegistry.registerPluggableService(ghidra.program.database.ProgramMultiUserMergeManagerFactory.class,new Factory());
|
|
102
|
+
server=new GhidraServerManager();server.connect();require(server.isConnected(),"Native repository disconnected");
|
|
103
|
+
RepositoryAdapter repository=server.server().getRepository(text(owner,"repository"));repository.connect();
|
|
104
|
+
require(repository.getUser().hasWritePermission()&&repository.getUser().getName().equals(System.getenv("GHIDRA_SERVER_USER")),"Publisher authority required");
|
|
105
|
+
ProjectLocator locator=new ProjectLocator(root.toString(),"view");Projects manager=new Projects();
|
|
106
|
+
// After a proved release the project is never reopened: an interrupted deletion can leave it unreadable.
|
|
107
|
+
if((operation.equals("release")||operation.equals("drop"))&&released(root,q)){
|
|
108
|
+
require(Arrays.stream(repository.getCheckouts("/",name)).noneMatch(c->c.getCheckoutId()==q.get("checkoutId").getAsLong()),"Owned checkout remains");
|
|
109
|
+
if(operation.equals("drop"))deleteReleased(root,locator);
|
|
110
|
+
repository.disconnect();server.disconnect();output.println("{\"state\":\""+(operation.equals("drop")?"dropped":"released")+"\"}");System.exit(0);
|
|
111
|
+
}
|
|
112
|
+
if(operation.equals("create")&&!locator.getMarkerFile().exists())project=manager.createProject(locator,repository,false);
|
|
113
|
+
else project=manager.openProject(locator,false,false);
|
|
114
|
+
require(locator.getProjectDir().toPath().toRealPath().getParent().equals(root),"Native project moved outside owned storage");
|
|
115
|
+
var bound=project.getProjectData().getRepository();
|
|
116
|
+
require(bound!=null&&bound.isConnected()&&bound.getName().equals(repository.getName())&&bound.getServerInfo().equals(repository.getServerInfo()),"Saved native repository binding changed");
|
|
117
|
+
DomainFile file=project.getProjectData().getFile(path);require(file!=null,"Native file missing");
|
|
118
|
+
if(operation.equals("create")&&!file.isCheckedOut()){
|
|
119
|
+
String projectPath=ghidra.framework.store.ItemCheckoutStatus.getProjectPath(locator.toString(),false);
|
|
120
|
+
require(Arrays.stream(repository.getCheckouts("/",name)).noneMatch(c->projectPath.equals(c.getProjectPath())),"Uncertain checkout creation must be reconciled");
|
|
121
|
+
saved(file,owner);require(file.checkout(false,MONITOR),"Native checkout denied");
|
|
122
|
+
}
|
|
123
|
+
require(!file.isCheckedOutExclusive(),"Ordinary native checkout required");
|
|
124
|
+
if(q.has("fileId"))require(file.getFileID().equals(text(q,"fileId")),"Native file ID changed");
|
|
125
|
+
if(q.has("checkoutId")&&file.isCheckedOut())require(file.getCheckoutStatus().getCheckoutId()==q.get("checkoutId").getAsLong(),"Native checkout owner changed");
|
|
126
|
+
Path operations=root.resolve("operations");Files.createDirectories(operations);
|
|
127
|
+
if(operation.equals("update")||operation.equals("checkin")||operation.equals("discard")){
|
|
128
|
+
String request=text(q,"request");require(request.matches("q_[a-f0-9-]{36}"),"Native request identity required");
|
|
129
|
+
Path journal=operations.resolve(request+"-"+operation+".json");
|
|
130
|
+
if(Files.exists(journal)){
|
|
131
|
+
JsonObject prior=JsonParser.parseString(Files.readString(journal)).getAsJsonObject();
|
|
132
|
+
require(prior.getAsJsonObject("request").equals(q),"Native request changed");
|
|
133
|
+
require(prior.has("result"),"Native outcome is unknown; do not retry");
|
|
134
|
+
out=new Gson().fromJson(prior.get("result"),LinkedHashMap.class);
|
|
135
|
+
}else{
|
|
136
|
+
require(file.isCheckedOut(),"Native checkout missing");
|
|
137
|
+
var before=saved(file,owner);long checkout=file.getCheckoutStatus().getCheckoutId();int base=file.getCheckoutStatus().getCheckoutVersion(),head=file.getLatestVersion();
|
|
138
|
+
Map<String,Object> intent=new LinkedHashMap<>();intent.put("request",q);intent.put("before",before);intent.put("checkoutId",checkout);intent.put("baseVersion",base);intent.put("headVersion",head);
|
|
139
|
+
if(operation.equals("discard")){
|
|
140
|
+
write(journal,intent);
|
|
141
|
+
boolean dirty=file.modifiedSinceCheckout();file.undoCheckout(dirty);
|
|
142
|
+
file=project.getProjectData().getFile(path);require(file.checkout(false,MONITOR),"Native checkout after discard was refused");
|
|
143
|
+
out.put("state","discarded");out.put("retainedKeepFile",dirty?name+".keep":"");
|
|
144
|
+
}else if(operation.equals("update")){
|
|
145
|
+
write(journal,intent);
|
|
146
|
+
try{if(head>base)file.merge(false,MONITOR);
|
|
147
|
+
require(file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()>=head,"Native Update did not establish the requested ancestry");
|
|
148
|
+
out.put("state","updated");}
|
|
149
|
+
catch(HeadlessProgramMergeManager.UnresolvedNativeConflict conflict){
|
|
150
|
+
require(before.equals(saved(file,owner))&&file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base,"Native conflict did not preserve local state");
|
|
151
|
+
out.put("state","conflict");out.put("conflict",conflict.getMessage());
|
|
152
|
+
}
|
|
153
|
+
}else{
|
|
154
|
+
require(before.get("fingerprint").equals(text(q,"fingerprint")),"Prepared native publication changed");
|
|
155
|
+
if(head!=base||head!=q.get("expectedVersion").getAsInt()){
|
|
156
|
+
// A known pre-call head race is not an unknown check-in: none was issued.
|
|
157
|
+
out.put("state","conflict");out.put("conflict","Shared head changed before native check-in");
|
|
158
|
+
intent.put("result",out);write(journal,intent);
|
|
159
|
+
}else if(!file.modifiedSinceCheckout()){
|
|
160
|
+
intent.put("marker","insight native "+request);write(journal,intent);out.put("state","empty");
|
|
161
|
+
}else{
|
|
162
|
+
intent.put("marker","insight native "+request);write(journal,intent);
|
|
163
|
+
permitMerge=false;
|
|
164
|
+
try{file.checkin(new DefaultCheckinHandler("insight native "+request,true,false),MONITOR);out.put("state","checked_in");}
|
|
165
|
+
catch(HeadChanged changed){
|
|
166
|
+
require(before.equals(saved(file,owner))&&Arrays.stream(repository.getVersions("/",name)).noneMatch(v->("insight native "+request).equals(v.getComment())),"Check-in outcome is unknown");
|
|
167
|
+
out.put("state","conflict");out.put("conflict",changed.getMessage());
|
|
168
|
+
}finally{permitMerge=true;}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
out.put("saved",saved(file,owner));out.put("checkoutId",file.getCheckoutStatus().getCheckoutId());out.put("baseVersion",file.getCheckoutStatus().getCheckoutVersion());
|
|
172
|
+
out.put("modified",file.modifiedSinceCheckout());out.put("nativeMergeInvocations",HeadlessProgramMergeManager.invocations);out.put("nativePhases",HeadlessProgramMergeManager.phases);
|
|
173
|
+
intent.put("result",out);write(journal,intent);
|
|
174
|
+
}
|
|
175
|
+
}else if(operation.equals("release")){
|
|
176
|
+
Path releaseFile=root.resolve("released.json");
|
|
177
|
+
Map<String,Object> release=new LinkedHashMap<>(Map.of("checkoutId",q.get("checkoutId").getAsLong(),"version",q.get("verifiedVersion").getAsInt(),"fingerprint",text(q,"fingerprint")));
|
|
178
|
+
if(file.isCheckedOut()){
|
|
179
|
+
require(!file.modifiedSinceCheckout()&&file.getCheckoutStatus().getCheckoutVersion()==q.get("verifiedVersion").getAsInt(),"Unpublished native work must be retained");
|
|
180
|
+
require(saved(file,owner).get("fingerprint").equals(text(q,"fingerprint")),"Verified native buffers changed");
|
|
181
|
+
release.put("state","release_intent");write(releaseFile,release);file.undoCheckout(false);
|
|
182
|
+
}else{
|
|
183
|
+
var prior=JsonParser.parseString(Files.readString(releaseFile)).getAsJsonObject();
|
|
184
|
+
require(prior.get("checkoutId").equals(q.get("checkoutId"))&&prior.get("version").equals(q.get("verifiedVersion"))&&prior.get("fingerprint").equals(q.get("fingerprint")),"Release intent changed");
|
|
185
|
+
}
|
|
186
|
+
require(Arrays.stream(repository.getCheckouts("/",name)).noneMatch(c->c.getCheckoutId()==q.get("checkoutId").getAsLong()),"Owned checkout remains");
|
|
187
|
+
release.put("state","released");write(releaseFile,release);out.put("state","released");
|
|
188
|
+
}else if(operation.equals("drop")){
|
|
189
|
+
require(false,"Verified release receipt differs");
|
|
190
|
+
}else if(operation.equals("inspect")||operation.equals("fields")||operation.equals("export")){
|
|
191
|
+
require(saved(file,owner).get("fingerprint").equals(text(q,"fingerprint")),"Saved native view changed");
|
|
192
|
+
ProgramDB p=(ProgramDB)file.getDomainObject(CONSUMER,false,false,MONITOR);
|
|
193
|
+
try{
|
|
194
|
+
if(operation.equals("export")){
|
|
195
|
+
Path target=Path.of(text(q,"output"));require(target.getParent().toRealPath().startsWith(root)&&!Files.exists(target),"Native export escaped owned storage");
|
|
196
|
+
p.saveToPackedFile(target.toFile(),MONITOR);require(InsightNativeFingerprint.of(p).equals(text(q,"fingerprint")),"Native export changed saved buffers");
|
|
197
|
+
}else out.put("value",operation.equals("fields")?InsightSnapshotFields.inspect(p,q.getAsJsonArray("selectors")):InsightSnapshotInspect.inspect(p,q.getAsJsonObject("parameters")));
|
|
198
|
+
}
|
|
199
|
+
finally{p.release(CONSUMER);}
|
|
200
|
+
}else require(operation.equals("create")||operation.equals("status"),"Unknown native operation");
|
|
201
|
+
if(project!=null){
|
|
202
|
+
out.put("saved",saved(file,owner));out.put("modified",file.modifiedSinceCheckout());out.put("fileId",file.getFileID());out.put("checkedOut",file.isCheckedOut());
|
|
203
|
+
out.put("recoverable",file.canRecover());
|
|
204
|
+
var local=new TreeSet<String>();local(project.getProjectData().getRootFolder(),local);out.put("projectFiles",local);
|
|
205
|
+
if(file.isCheckedOut()){out.put("checkoutId",file.getCheckoutStatus().getCheckoutId());out.put("baseVersion",file.getCheckoutStatus().getCheckoutVersion());}
|
|
206
|
+
}
|
|
207
|
+
history(repository,path,out);out.putIfAbsent("state","ready");out.put("guiWindows",java.awt.Window.getWindows().length);
|
|
208
|
+
require(java.awt.Window.getWindows().length==0,"Unexpected GUI window");
|
|
209
|
+
if(project!=null){project.close();project=null;}repository.disconnect();server.disconnect();server=null;
|
|
210
|
+
output.println(GSON.toJson(out));System.exit(0);
|
|
211
|
+
}catch(Throwable failure){failure.printStackTrace(System.err);if(project!=null)project.close();if(server!=null)server.disconnect();
|
|
212
|
+
output.println(GSON.toJson(Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()),"code",failure instanceof InsightNativeMigration.Required?"migration":"unknown")));System.exit(0);}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
package db;
|
|
2
|
+
|
|
3
|
+
import db.buffers.InsightBlockTransfer;
|
|
4
|
+
import ghidra.program.database.ProgramDB;
|
|
5
|
+
import ghidra.program.model.listing.Program;
|
|
6
|
+
|
|
7
|
+
/** Saved native buffers only; never fabricates or replaces native ancestry/change sets. */
|
|
8
|
+
public final class InsightNativeFingerprint {
|
|
9
|
+
public static String of(Program p)throws Exception {
|
|
10
|
+
if(p.isChanged())throw new IllegalStateException("Program has unsaved changes");
|
|
11
|
+
return InsightBlockTransfer.fingerprint(((ProgramDB)p).getDBHandle().getBufferMgr().getSourceFile());
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Every saved record except what opening a program writes by itself: the derived Metadata table, rebuilt
|
|
15
|
+
* from options on save, and the GUI's "Should Ask To Analyze" flag. Stored file bytes are included; memory
|
|
16
|
+
* block bytes are in chained buffers too, so callers also require an equal program identity.
|
|
17
|
+
*/
|
|
18
|
+
public static String content(Program p)throws Exception {
|
|
19
|
+
DBHandle db=((ProgramDB)p).getDBHandle();
|
|
20
|
+
var hash=java.security.MessageDigest.getInstance("SHA-256");
|
|
21
|
+
var tables=new java.util.TreeMap<String,Table>();
|
|
22
|
+
for(Table table:db.getTables())if(!table.getName().equals("Metadata"))tables.put(table.getName(),table);
|
|
23
|
+
for(Table table:tables.values()){
|
|
24
|
+
boolean properties=table.getName().equals("Property Table");Schema schema=table.getSchema();
|
|
25
|
+
add(hash,table.getName().getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
|
26
|
+
add(hash,(schema.getVersion()+"|"+schema.getKeyName()+"|"+String.join("|",schema.getFieldNames())+"|"+java.util.Arrays.stream(schema.getFields()).map(f->f.getClass().getName()).toList()).getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
|
27
|
+
var records=table.iterator();
|
|
28
|
+
while(records.hasNext()){
|
|
29
|
+
DBRecord record=records.next();
|
|
30
|
+
if(properties&&record.getKeyField() instanceof StringField key&&"Program Information.Should Ask To Analyze".equals(key.getString()))continue;
|
|
31
|
+
add(hash,record.getKeyField().getBinaryData());
|
|
32
|
+
for(int i=0;i<record.getColumnCount();i++){Field field=record.getFieldValue(i);add(hash,field==null||field.isNull()?null:field.getBinaryData());}
|
|
33
|
+
}
|
|
34
|
+
hash.update((byte)2);
|
|
35
|
+
}
|
|
36
|
+
var files=p.getMemory().getAllFileBytes();
|
|
37
|
+
for(int i=0;i<files.size();i++){
|
|
38
|
+
var file=files.get(i);long size=file.getSize();
|
|
39
|
+
add(hash,(i+"|"+file.getFilename()+"|"+size).getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
|
40
|
+
for(long at=0;at<size;at+=1<<20){
|
|
41
|
+
byte[] original=new byte[(int)Math.min(1<<20,size-at)],modified=new byte[original.length];
|
|
42
|
+
if(file.getOriginalBytes(at,original)!=original.length||file.getModifiedBytes(at,modified)!=modified.length)throw new java.io.IOException("Incomplete stored file bytes");
|
|
43
|
+
add(hash,original);add(hash,modified);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return java.util.HexFormat.of().formatHex(hash.digest());
|
|
47
|
+
}
|
|
48
|
+
private static void add(java.security.MessageDigest hash,byte[] value){
|
|
49
|
+
hash.update((byte)(value==null?0:1));if(value==null)return;
|
|
50
|
+
hash.update(java.nio.ByteBuffer.allocate(4).putInt(value.length).array());hash.update(value);
|
|
51
|
+
}
|
|
52
|
+
public static String of(DBHandle db)throws Exception{return InsightBlockTransfer.fingerprint(db.getBufferMgr().getSourceFile());}
|
|
53
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import com.google.gson.*;
|
|
2
|
+
import com.xebyte.headless.GhidraServerManager;
|
|
3
|
+
import ghidra.GhidraApplicationLayout;
|
|
4
|
+
import ghidra.framework.*;
|
|
5
|
+
import ghidra.framework.model.*;
|
|
6
|
+
import ghidra.framework.project.DefaultProjectManager;
|
|
7
|
+
import ghidra.framework.data.DefaultCheckinHandler;
|
|
8
|
+
import ghidra.program.model.listing.Program;
|
|
9
|
+
import ghidra.util.task.TaskMonitor;
|
|
10
|
+
import db.InsightNativeFingerprint;
|
|
11
|
+
import java.nio.file.*;
|
|
12
|
+
import java.nio.channels.*;
|
|
13
|
+
import java.security.MessageDigest;
|
|
14
|
+
import java.nio.charset.StandardCharsets;
|
|
15
|
+
import java.util.*;
|
|
16
|
+
|
|
17
|
+
/** Explicit legacy promotion only. Ordinary opens never enter this writer. */
|
|
18
|
+
public final class InsightNativeMigration {
|
|
19
|
+
public static final class Required extends IllegalStateException {public Required(){super("Legacy model requires explicit migration; run ghidra migrate --target <target> --dry-run, then ghidra migrate --target <target>");}}
|
|
20
|
+
static final Object CONSUMER=new Object();static final TaskMonitor MONITOR=TaskMonitor.DUMMY;
|
|
21
|
+
static class Projects extends DefaultProjectManager {Projects(){super();}}
|
|
22
|
+
static String text(JsonObject q,String k){return q.get(k).getAsString();}
|
|
23
|
+
static void require(boolean ok,String message){if(!ok)throw new IllegalStateException(message);}
|
|
24
|
+
public static String programIdentity(Program p)throws Exception {
|
|
25
|
+
MessageDigest hash=MessageDigest.getInstance("SHA-256");
|
|
26
|
+
for(String value:List.of(p.getExecutableSHA256(),p.getLanguageID().toString(),p.getCompilerSpec().getCompilerSpecID().toString(),p.getImageBase().toString()))hash.update((value+"\n").getBytes(StandardCharsets.UTF_8));
|
|
27
|
+
byte[] bytes=new byte[1024*1024];
|
|
28
|
+
for(var block:p.getMemory().getBlocks()){
|
|
29
|
+
hash.update((block.getStart()+":"+block.getSize()+":"+block.isInitialized()+"\n").getBytes(StandardCharsets.UTF_8));
|
|
30
|
+
if(block.isInitialized())for(long at=0;at<block.getSize();){int n=(int)Math.min(bytes.length,block.getSize()-at);int read=p.getMemory().getBytes(block.getStart().add(at),bytes,0,n);require(read==n,"Incomplete program memory read");hash.update(bytes,0,n);at+=n;}
|
|
31
|
+
}
|
|
32
|
+
return HexFormat.of().formatHex(hash.digest());
|
|
33
|
+
}
|
|
34
|
+
static void identity(Program p,JsonObject q)throws Exception {
|
|
35
|
+
require(p.getExecutableSHA256().equals(text(q,"sourceSha")),"Migration source SHA256 differs");
|
|
36
|
+
require(programIdentity(p).equals(text(q,"programIdentity")),"Migration program bytes or load identity differ");
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A process born after its import/publication receipt is presumed to reuse that PID; a missing birth blocks.
|
|
40
|
+
* Those workers also hold their target lock until exit, checked above. process.json always uses the bare PID.
|
|
41
|
+
*/
|
|
42
|
+
static boolean mayBeWorker(long pid,java.time.Instant receipt){
|
|
43
|
+
return ProcessHandle.of(pid).filter(ProcessHandle::isAlive).map(process->process.info().startInstant()
|
|
44
|
+
.map(birth->receipt.equals(java.time.Instant.MAX)||!birth.isAfter(receipt.plusSeconds(60))).orElse(true)).orElse(false);
|
|
45
|
+
}
|
|
46
|
+
static void quiescent(Path root)throws Exception {
|
|
47
|
+
if(!Files.exists(root))return;
|
|
48
|
+
var channels=new ArrayList<FileChannel>();var locks=new ArrayList<FileLock>();
|
|
49
|
+
try(var paths=Files.walk(root)){
|
|
50
|
+
for(Path path:paths.toList()){
|
|
51
|
+
String name=path.getFileName().toString();
|
|
52
|
+
if(!Files.isRegularFile(path,LinkOption.NOFOLLOW_LINKS))continue;
|
|
53
|
+
if(name.equals("lock")){
|
|
54
|
+
var channel=FileChannel.open(path,StandardOpenOption.WRITE);channels.add(channel);
|
|
55
|
+
var lock=channel.tryLock();require(lock!=null,"Retained initial-model lock is held; no takeover");locks.add(lock);
|
|
56
|
+
}
|
|
57
|
+
if(!List.of("process.json","import.json","publication.json").contains(name))continue;
|
|
58
|
+
JsonObject receipt=JsonParser.parseString(Files.readString(path)).getAsJsonObject();
|
|
59
|
+
if(!receipt.has("pid"))continue;
|
|
60
|
+
boolean stopped=false;Path stop=path.resolveSibling("stopped.json");
|
|
61
|
+
if(name.equals("process.json")&&receipt.has("tokenSecret")&&Files.exists(stop)){
|
|
62
|
+
var saved=JsonParser.parseString(Files.readString(stop)).getAsJsonObject();
|
|
63
|
+
stopped=receipt.get("pid").equals(saved.get("pid"))&&receipt.get("tokenSecret").equals(saved.get("tokenSecret"));
|
|
64
|
+
}
|
|
65
|
+
long pid=receipt.get("pid").getAsLong();require(pid>0,"Invalid retained worker PID");
|
|
66
|
+
require(stopped||!mayBeWorker(pid,name.equals("process.json")?java.time.Instant.MAX:Files.getLastModifiedTime(path).toInstant()),"Retained native worker is live; no takeover");
|
|
67
|
+
}
|
|
68
|
+
}finally{for(var lock:locks)lock.close();for(var channel:channels)channel.close();}
|
|
69
|
+
}
|
|
70
|
+
public static void main(String[] args){
|
|
71
|
+
var output=System.out;System.setOut(System.err);Project project=null;GhidraServerManager server=null;
|
|
72
|
+
try {
|
|
73
|
+
JsonObject q=JsonParser.parseString(Files.readString(Path.of(args[0]))).getAsJsonObject();
|
|
74
|
+
if(text(q,"operation").equals("quiescence")){
|
|
75
|
+
quiescent(Path.of(text(q,"nativeRoot")));output.println("{\"state\":\"verified\"}");System.exit(0);
|
|
76
|
+
}
|
|
77
|
+
if(text(q,"operation").equals("snapshots")){
|
|
78
|
+
Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
|
|
79
|
+
var items=new ArrayList<Map<String,Object>>();
|
|
80
|
+
for(JsonElement path:q.getAsJsonArray("snapshots")){
|
|
81
|
+
var db=ghidra.framework.store.db.PackedDatabase.getPackedDatabase(Path.of(path.getAsString()).toFile(),true,MONITOR).open(MONITOR);
|
|
82
|
+
var p=new ghidra.program.database.ProgramDB(db,ghidra.framework.data.OpenMode.IMMUTABLE,MONITOR,CONSUMER);
|
|
83
|
+
try{items.add(Map.of("state","verified","fingerprint",InsightNativeFingerprint.of(p),"content",InsightNativeFingerprint.content(p),"sourceSha",p.getExecutableSHA256(),"programIdentity",programIdentity(p)));}finally{p.release(CONSUMER);}
|
|
84
|
+
}
|
|
85
|
+
output.println(new Gson().toJson(Map.of("state","verified","items",items)));System.exit(0);
|
|
86
|
+
}
|
|
87
|
+
if(text(q,"operation").equals("snapshot")){
|
|
88
|
+
Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
|
|
89
|
+
var db=ghidra.framework.store.db.PackedDatabase.getPackedDatabase(Path.of(text(q,"snapshot")).toFile(),true,MONITOR).open(MONITOR);
|
|
90
|
+
var p=new ghidra.program.database.ProgramDB(db,ghidra.framework.data.OpenMode.IMMUTABLE,MONITOR,CONSUMER);
|
|
91
|
+
try{output.println(new Gson().toJson(Map.of("state","verified","fingerprint",InsightNativeFingerprint.of(p),"content",InsightNativeFingerprint.content(p),"sourceSha",p.getExecutableSHA256(),"programIdentity",programIdentity(p))));}finally{p.release(CONSUMER);}
|
|
92
|
+
System.exit(0);
|
|
93
|
+
}
|
|
94
|
+
Path root=Path.of(text(q,"root")).toRealPath(),ownerPath=root.resolve("migration-owner.json"),journal=root.resolve("native-migration.json");
|
|
95
|
+
require(JsonParser.parseString(Files.readString(ownerPath)).equals(q.get("owner")),"Migration owner changed");
|
|
96
|
+
JsonObject owner=q.getAsJsonObject("owner");String path=text(owner,"path"),name=path.substring(1),marker=text(owner,"marker");
|
|
97
|
+
require(path.equals("/"+text(owner,"target")+".bin")&&marker.matches("insight migration [a-f0-9-]{36}"),"Invalid migration binding");
|
|
98
|
+
Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
|
|
99
|
+
Class.forName("ghidra.program.database.ProgramMultiUserMergeManagerFactory");
|
|
100
|
+
PluggableServiceRegistry.registerPluggableService(ghidra.program.database.ProgramMultiUserMergeManagerFactory.class,new InsightNativeCheckout.Factory());
|
|
101
|
+
server=new GhidraServerManager();server.connect();var repository=server.server().getRepository(text(owner,"repository"));repository.connect();
|
|
102
|
+
require(repository.getUser().hasWritePermission()&&repository.getUser().getName().equals(System.getenv("GHIDRA_SERVER_USER")),"Migration needs publisher authority");
|
|
103
|
+
var item=repository.getItem("/",name);require(item!=null&&item.getFileID().equals(text(owner,"fileId")),"Migration file identity differs");
|
|
104
|
+
JsonObject saved=Files.exists(journal)?JsonParser.parseString(Files.readString(journal)).getAsJsonObject():new JsonObject();
|
|
105
|
+
String phase=saved.has("phase")?text(saved,"phase"):"reserved";
|
|
106
|
+
if(text(q,"operation").equals("run")&&(phase.equals("commit_intent")||phase.equals("checked_in")||phase.equals("released"))){output.println(saved);System.exit(0);}
|
|
107
|
+
Projects manager=new Projects();ProjectLocator locator=new ProjectLocator(root.toString(),"migration");
|
|
108
|
+
project=locator.getMarkerFile().exists()?manager.openProject(locator,false,false):manager.createProject(locator,repository,false);
|
|
109
|
+
var bound=project.getProjectData().getRepository();require(bound!=null&&bound.getName().equals(repository.getName())&&bound.getServerInfo().equals(repository.getServerInfo()),"Migration project repository differs");
|
|
110
|
+
DomainFile file=project.getProjectData().getFile(path);require(file!=null&&file.getFileID().equals(text(owner,"fileId")),"Migration local identity differs");
|
|
111
|
+
if(text(q,"operation").equals("release")){
|
|
112
|
+
require(phase.equals("commit_intent")||phase.equals("checked_in")||phase.equals("released"),"No migration check-in intent");
|
|
113
|
+
require(q.get("fingerprint").equals(saved.get("fingerprint"))&&q.get("version").getAsInt()==owner.get("version").getAsInt()+1,"Migration release proof differs");
|
|
114
|
+
if(file.isCheckedOut()){require(file.getCheckoutStatus().getCheckoutId()==saved.get("checkoutId").getAsLong(),"Migration checkout changed");require(!file.modifiedSinceCheckout(),"Migration private buffers changed after check-in");file.undoCheckout(false);}
|
|
115
|
+
require(Arrays.stream(repository.getCheckouts("/",name)).noneMatch(c->c.getCheckoutId()==saved.get("checkoutId").getAsLong()),"Migration checkout release is unproved");
|
|
116
|
+
saved.addProperty("phase","released");InsightNativeCheckout.write(journal,saved);output.println(saved);
|
|
117
|
+
}else{
|
|
118
|
+
require(text(q,"operation").equals("run"),"Unsupported migration operation");
|
|
119
|
+
require(item.getVersion()==owner.get("version").getAsInt()&&!repository.isCheckinActive("/",name),"Migration shared head changed");
|
|
120
|
+
if(!file.isCheckedOut()){
|
|
121
|
+
require(phase.equals("reserved"),"Migration checkout disappeared");
|
|
122
|
+
require(repository.getCheckouts("/",name).length==0,"Migration requires no existing checkouts");
|
|
123
|
+
Program p=(Program)file.getDomainObject(CONSUMER,false,false,MONITOR);
|
|
124
|
+
try{identity(p,owner);require(InsightNativeFingerprint.of(p).equals(text(owner,"fingerprint")),"Migration original saved buffers differ");require(p.getOptions("Insight").getString("Publication Engine","").isEmpty(),"Migration requires an unmarked legacy program");}finally{p.release(CONSUMER);}
|
|
125
|
+
require(file.checkout(false,MONITOR),"Migration checkout denied");
|
|
126
|
+
}
|
|
127
|
+
require(!file.isCheckedOutExclusive(),"Migration requires an ordinary native checkout");
|
|
128
|
+
long checkout=file.getCheckoutStatus().getCheckoutId();
|
|
129
|
+
if(saved.has("checkoutId"))require(checkout==saved.get("checkoutId").getAsLong(),"Migration checkout owner changed");
|
|
130
|
+
String projectPath=file.getCheckoutStatus().getProjectPath();
|
|
131
|
+
require(Arrays.stream(repository.getCheckouts("/",name)).allMatch(c->c.getCheckoutId()==checkout&&projectPath.equals(c.getProjectPath())),"Another checkout prevents migration");
|
|
132
|
+
saved.addProperty("phase","checkout");saved.addProperty("checkoutId",checkout);InsightNativeCheckout.write(journal,saved);
|
|
133
|
+
Program p=(Program)file.getDomainObject(CONSUMER,false,false,MONITOR);
|
|
134
|
+
try{
|
|
135
|
+
identity(p,owner);var options=p.getOptions("Insight");String engine=options.getString("Publication Engine","");
|
|
136
|
+
if(engine.isEmpty()){
|
|
137
|
+
require(InsightNativeFingerprint.of(p).equals(text(owner,"fingerprint")),"Migration checkout buffers changed before conversion");
|
|
138
|
+
int tx=p.startTransaction("Explicit native migration");boolean ok=false;
|
|
139
|
+
try{options.setString("Publication Engine","native-checkout-v1");options.setString("Migration Request",marker);ok=true;}finally{p.endTransaction(tx,ok);}
|
|
140
|
+
p.save("Explicit native migration",MONITOR);
|
|
141
|
+
}else require(engine.equals("native-checkout-v1")&&options.getString("Migration Request","").equals(marker),"Foreign migration marker");
|
|
142
|
+
identity(p,owner);saved.addProperty("fingerprint",InsightNativeFingerprint.of(p));
|
|
143
|
+
}finally{p.release(CONSUMER);}
|
|
144
|
+
require(file.getLatestVersion()==owner.get("version").getAsInt(),"Migration head changed before check-in");
|
|
145
|
+
saved.addProperty("phase","commit_intent");InsightNativeCheckout.write(journal,saved);
|
|
146
|
+
InsightNativeCheckout.permitMerge=false;
|
|
147
|
+
file.checkin(new DefaultCheckinHandler(marker,true,false),MONITOR);
|
|
148
|
+
saved.addProperty("phase","checked_in");InsightNativeCheckout.write(journal,saved);output.println(saved);
|
|
149
|
+
}
|
|
150
|
+
project.close();project=null;repository.disconnect();server.disconnect();System.exit(0);
|
|
151
|
+
}catch(Throwable failure){failure.printStackTrace(System.err);output.println(new Gson().toJson(Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()))));}
|
|
152
|
+
finally{if(project!=null)try{project.close();}catch(Throwable ignored){}}
|
|
153
|
+
System.exit(0);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import insight.nativecheckout.InsightSnapshotFields;
|
|
2
|
+
import insight.nativecheckout.InsightSnapshotInspect;
|
|
3
|
+
import com.google.gson.*;
|
|
4
|
+
import com.xebyte.headless.GhidraServerManager;
|
|
5
|
+
import ghidra.GhidraApplicationLayout;
|
|
6
|
+
import ghidra.framework.*;
|
|
7
|
+
import ghidra.framework.data.OpenMode;
|
|
8
|
+
import ghidra.program.database.ProgramDB;
|
|
9
|
+
import ghidra.util.task.TaskMonitor;
|
|
10
|
+
import db.*;
|
|
11
|
+
import java.nio.file.*;
|
|
12
|
+
import java.util.*;
|
|
13
|
+
|
|
14
|
+
/** Independent read authority, immutable exact-version native database; never checks out. */
|
|
15
|
+
public final class InsightNativeRead {
|
|
16
|
+
public static void main(String[] args){
|
|
17
|
+
var output=System.out;System.setOut(System.err);
|
|
18
|
+
try {
|
|
19
|
+
JsonObject q=JsonParser.parseString(Files.readString(Path.of(args[0]))).getAsJsonObject();
|
|
20
|
+
String repo=q.get("repository").getAsString(),path=q.get("path").getAsString(),sha=q.get("sourceSha").getAsString(),op=q.get("operation").getAsString();
|
|
21
|
+
if(!path.startsWith("/")||path.indexOf('/',1)>=0)throw new SecurityException();String name=path.substring(1);
|
|
22
|
+
Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
|
|
23
|
+
var server=new GhidraServerManager();server.connect();var repository=server.server().getRepository(repo);repository.connect();
|
|
24
|
+
if(!repository.getUser().isReadOnly()||!repository.getUser().getName().equals(System.getenv("GHIDRA_SERVER_USER")))throw new SecurityException();
|
|
25
|
+
var item=repository.getItem("/",name);
|
|
26
|
+
if(item==null&&op.equals("migration-probe")){repository.disconnect();server.disconnect();output.println("{\"state\":\"absent\"}");System.exit(0);}
|
|
27
|
+
if(item==null||repository.isCheckinActive("/",name))throw new IllegalStateException("Native item is absent or busy");
|
|
28
|
+
int version=q.has("version")?q.get("version").getAsInt():item.getVersion();
|
|
29
|
+
if(q.has("fileId")&&!item.getFileID().equals(q.get("fileId").getAsString()))throw new SecurityException("Native item ID changed");
|
|
30
|
+
if(op.equals("verify")){
|
|
31
|
+
var matches=Arrays.stream(repository.getVersions("/",name)).filter(v->q.get("marker").getAsString().equals(v.getComment())).toList();
|
|
32
|
+
if(matches.size()!=1||matches.getFirst().getVersion()!=version)throw new IllegalStateException("Native history marker is unresolved");
|
|
33
|
+
}
|
|
34
|
+
DBHandle db=new DBHandle(repository.openDatabase("/",name,version,-1));Object consumer=new Object();ProgramDB program=null;
|
|
35
|
+
Map<String,Object> result=new LinkedHashMap<>();
|
|
36
|
+
try {
|
|
37
|
+
String fingerprint=InsightNativeFingerprint.of(db);
|
|
38
|
+
program=new ProgramDB(db,OpenMode.IMMUTABLE,TaskMonitor.DUMMY,consumer);
|
|
39
|
+
if(!sha.equals(program.getExecutableSHA256()))throw new SecurityException("Native source changed");
|
|
40
|
+
if(!op.equals("migration-probe")&&!program.getOptions("Insight").getString("Publication Engine","").equals("native-checkout-v1"))throw new InsightNativeMigration.Required();
|
|
41
|
+
if(q.has("fingerprint")&&!fingerprint.equals(q.get("fingerprint").getAsString()))throw new SecurityException("Exact native buffers differ");
|
|
42
|
+
result.put("state","verified");result.put("version",version);result.put("fileId",item.getFileID());result.put("fingerprint",fingerprint);
|
|
43
|
+
if(op.equals("migration-probe")){result.put("content",InsightNativeFingerprint.content(program));result.put("engine",program.getOptions("Insight").getString("Publication Engine",""));result.put("programIdentity",InsightNativeMigration.programIdentity(program));var functions=program.getFunctionManager().getFunctions(true);int samples=0;String sample=null;
|
|
44
|
+
while(functions.hasNext()&&samples++<1000){var f=functions.next();var block=program.getMemory().getBlock(f.getEntryPoint());if(!f.isThunk()&&block!=null&&block.isInitialized()&&block.isExecute()){if(sample==null)sample=f.getEntryPoint().toString();if(program.getReferenceManager().getReferencesTo(f.getEntryPoint()).hasNext()){sample=f.getEntryPoint().toString();break;}}}result.put("sampleFunction",sample);
|
|
45
|
+
result.put("language",program.getLanguageID().toString());result.put("compiler",program.getCompilerSpec().getCompilerSpecID().toString());result.put("imageBase",program.getImageBase().toString());result.put("versions",Arrays.stream(repository.getVersions("/",name)).map(v->Map.of("version",v.getVersion(),"comment",Objects.toString(v.getComment(),""))).toList());}
|
|
46
|
+
else if(op.equals("inspect"))result.put("value",InsightSnapshotInspect.inspect(program,q.getAsJsonObject("parameters")));
|
|
47
|
+
else if(op.equals("fields"))result.put("fields",InsightSnapshotFields.inspect(program,q.getAsJsonArray("selectors")));
|
|
48
|
+
else if(op.equals("export")){program.saveToPackedFile(Path.of(q.get("output").getAsString()).toFile(),TaskMonitor.DUMMY);result.put("output",q.get("output").getAsString());}
|
|
49
|
+
else if(!Set.of("latest","verify","view").contains(op))throw new IllegalArgumentException();
|
|
50
|
+
result.put("checkouts",Arrays.stream(repository.getCheckouts("/",name)).map(c->Map.of("id",c.getCheckoutId(),"version",c.getCheckoutVersion())).toList());
|
|
51
|
+
}finally{if(program!=null)program.release(consumer);else db.close();}
|
|
52
|
+
var after=repository.getItem("/",name);
|
|
53
|
+
if(after==null||!after.getFileID().equals(item.getFileID())||after.getVersion()<version)throw new SecurityException("Native item changed while reading its exact version");
|
|
54
|
+
repository.disconnect();server.disconnect();output.println(new GsonBuilder().serializeNulls().create().toJson(result));System.exit(0);
|
|
55
|
+
}catch(Throwable failure){failure.printStackTrace(System.err);output.println(new Gson().toJson(Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()),"code",failure instanceof InsightNativeMigration.Required?"migration":"unknown")));System.exit(0);}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import insight.nativecheckout.InsightSnapshotFields;
|
|
2
|
+
import insight.nativecheckout.InsightSnapshotInspect;
|
|
3
|
+
import ghidra.app.script.GhidraScript;
|
|
4
|
+
import ghidra.program.database.ProgramDB;
|
|
5
|
+
import com.google.gson.*;
|
|
6
|
+
import java.util.*;
|
|
7
|
+
import db.InsightNativeFingerprint;
|
|
8
|
+
|
|
9
|
+
/** Trusted saved-view inspection in the already owned worker; no repository credentials. */
|
|
10
|
+
public class InsightNativeView extends GhidraScript {
|
|
11
|
+
public void run()throws Exception {
|
|
12
|
+
JsonObject q=JsonParser.parseString(new String(Base64.getDecoder().decode(getScriptArgs()[0]),java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject();
|
|
13
|
+
if(currentProgram==null||currentProgram.isChanged())throw new IllegalStateException("Saved program required");
|
|
14
|
+
String fingerprint=InsightNativeFingerprint.of(currentProgram);
|
|
15
|
+
if(q.has("expected")&&!fingerprint.equals(q.get("expected").getAsString()))throw new IllegalStateException("Saved native view changed");
|
|
16
|
+
Object value;
|
|
17
|
+
switch(q.get("operation").getAsString()) {
|
|
18
|
+
case "fingerprint":
|
|
19
|
+
var c=((ProgramDB)currentProgram).getChanges();
|
|
20
|
+
value=Map.of("fingerprint",fingerprint,"version",currentProgram.getDomainFile().getVersion(),"fileId",currentProgram.getDomainFile().getFileID(),
|
|
21
|
+
"dataTypeChanges",c.getDataTypeChanges(),"dataTypeAdditions",c.getDataTypeAdditions(),"symbolChanges",c.getSymbolChanges(),"symbolAdditions",c.getSymbolAdditions());break;
|
|
22
|
+
case "fields":value=InsightSnapshotFields.inspect((ProgramDB)currentProgram,q.getAsJsonArray("selectors"));break;
|
|
23
|
+
case "inspect":value=InsightSnapshotInspect.inspect((ProgramDB)currentProgram,q.getAsJsonObject("parameters"));break;
|
|
24
|
+
default:throw new IllegalArgumentException();
|
|
25
|
+
}
|
|
26
|
+
if(!fingerprint.equals(InsightNativeFingerprint.of(currentProgram)))throw new IllegalStateException("Native view changed while inspecting");
|
|
27
|
+
println("INSIGHT_NATIVE:"+new GsonBuilder().serializeNulls().create().toJson(Map.of("value",value)));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
package insight.nativecheckout;
|
|
2
|
+
|
|
3
|
+
import ghidra.framework.client.*;
|
|
4
|
+
import ghidra.framework.remote.*;
|
|
5
|
+
import java.net.Authenticator;
|
|
6
|
+
import java.awt.Component;
|
|
7
|
+
import javax.security.auth.callback.*;
|
|
8
|
+
|
|
9
|
+
/** Private program workers never authenticate to the repository, including on project reopen. */
|
|
10
|
+
public final class InsightOfflineAuthenticator implements ClientAuthenticator {
|
|
11
|
+
public static void install(){ClientUtil.setClientAuthenticator(new InsightOfflineAuthenticator());}
|
|
12
|
+
public Authenticator getAuthenticator(){return new Authenticator(){};}
|
|
13
|
+
public boolean processPasswordCallbacks(String a,String b,String c,boolean d,NameCallback n,
|
|
14
|
+
PasswordCallback p,ChoiceCallback choice,AnonymousCallback anon,String e){return false;}
|
|
15
|
+
public boolean promptForReconnect(Component c,String m){return false;}
|
|
16
|
+
public char[] getNewPassword(Component c,String s,String u){return null;}
|
|
17
|
+
public boolean isSSHKeyAvailable(){return false;}
|
|
18
|
+
public boolean processSSHSignatureCallbacks(String s,NameCallback n,SSHSignatureCallback cb){return false;}
|
|
19
|
+
public char[] getKeyStorePassword(String s,boolean b){return null;}
|
|
20
|
+
}
|
|
@@ -97,6 +97,10 @@ class InsightSdkFiles {
|
|
|
97
97
|
if(p.has("image_base")){int tx=program.startTransaction("Initial image base");boolean success=false;
|
|
98
98
|
try{program.setImageBase(program.getAddressFactory().getDefaultAddressSpace().getAddress(new BigInteger(text(p,"image_base"),16).longValue()),true);success=true;}
|
|
99
99
|
finally{program.endTransaction(tx,success);}}
|
|
100
|
+
if(p.has("native_model")&&p.get("native_model").getAsBoolean()){
|
|
101
|
+
int tx=program.startTransaction("Native publication protocol");
|
|
102
|
+
try{program.getOptions("Insight").setString("Publication Engine","native-checkout-v1");}finally{program.endTransaction(tx,true);}
|
|
103
|
+
}
|
|
100
104
|
phase(monitor,"save");program.saveToPackedFile(Path.of(text(p,"output")).toFile(),monitor);monitor.checkCancelled();
|
|
101
105
|
return Map.of("state","imported","loader",loader,"language",program.getLanguageID().toString(),"base_address",program.getImageBase().toString(),
|
|
102
106
|
"compiler",program.getCompilerSpec().getCompilerSpecID().toString(),"sha256",program.getExecutableSHA256(),"auto_analyzed",analyze);
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
package insight.nativecheckout;
|
|
2
|
+
|
|
1
3
|
import com.google.gson.*;
|
|
2
4
|
import db.DBHandle;
|
|
3
5
|
import ghidra.GhidraApplicationLayout;
|
|
@@ -14,20 +16,11 @@ import java.security.MessageDigest;
|
|
|
14
16
|
import java.util.*;
|
|
15
17
|
|
|
16
18
|
/** Read scalar values and conservative dependencies from an immutable saved program. */
|
|
17
|
-
class InsightSnapshotFields {
|
|
19
|
+
public class InsightSnapshotFields {
|
|
18
20
|
static final Map<String,Integer> kinds=Map.of("comment.eol",CodeUnit.EOL_COMMENT,"comment.pre",CodeUnit.PRE_COMMENT,
|
|
19
21
|
"comment.post",CodeUnit.POST_COMMENT,"comment.plate",CodeUnit.PLATE_COMMENT,"comment.repeatable",CodeUnit.REPEATABLE_COMMENT);
|
|
20
|
-
public static
|
|
21
|
-
var output=System.out;System.setOut(System.err);
|
|
22
|
-
try {
|
|
23
|
-
if(args.length!=2)throw new IllegalArgumentException();
|
|
24
|
-
String input=Files.readString(Path.of(args[1]));if(input.length()>1048576)throw new IllegalArgumentException();
|
|
25
|
-
JsonArray requests=JsonParser.parseString(input).getAsJsonArray();if(requests.size()>5000)throw new IllegalArgumentException();
|
|
26
|
-
Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
|
|
27
|
-
DBHandle db=PackedDatabase.getPackedDatabase(Path.of(args[0]).toFile(),true,TaskMonitor.DUMMY).open(TaskMonitor.DUMMY);
|
|
28
|
-
Object consumer=new Object();ProgramDB program=new ProgramDB(db,OpenMode.IMMUTABLE,TaskMonitor.DUMMY,consumer);
|
|
22
|
+
public static Map<String,Object> inspect(ProgramDB program,JsonArray requests) throws Exception {
|
|
29
23
|
Map<String,Object> values=new LinkedHashMap<>();
|
|
30
|
-
try {
|
|
31
24
|
for(JsonElement item:requests) {
|
|
32
25
|
JsonObject request=item.getAsJsonObject();String address=request.get("address").getAsString(),field=request.get("field").getAsString();
|
|
33
26
|
if(!field.equals("function.name")&&!kinds.containsKey(field))throw new IllegalArgumentException();
|
|
@@ -60,6 +53,19 @@ class InsightSnapshotFields {
|
|
|
60
53
|
Map<String,Object> observed=new LinkedHashMap<>();observed.put("value",value);observed.put("exists",exists);observed.put("dependency",anchor);
|
|
61
54
|
values.put(address+"@"+field,observed);
|
|
62
55
|
}
|
|
56
|
+
return values;
|
|
57
|
+
}
|
|
58
|
+
public static void main(String[] args) {
|
|
59
|
+
var output=System.out;System.setOut(System.err);
|
|
60
|
+
try {
|
|
61
|
+
if(args.length!=2)throw new IllegalArgumentException();
|
|
62
|
+
String input=Files.readString(Path.of(args[1]));if(input.length()>1048576)throw new IllegalArgumentException();
|
|
63
|
+
JsonArray requests=JsonParser.parseString(input).getAsJsonArray();if(requests.size()>5000)throw new IllegalArgumentException();
|
|
64
|
+
Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
|
|
65
|
+
DBHandle db=PackedDatabase.getPackedDatabase(Path.of(args[0]).toFile(),true,TaskMonitor.DUMMY).open(TaskMonitor.DUMMY);
|
|
66
|
+
Object consumer=new Object();ProgramDB program=new ProgramDB(db,OpenMode.IMMUTABLE,TaskMonitor.DUMMY,consumer);
|
|
67
|
+
Map<String,Object> values;
|
|
68
|
+
try { values=inspect(program,requests);
|
|
63
69
|
}finally{program.release(consumer);}
|
|
64
70
|
output.println(new GsonBuilder().serializeNulls().create().toJson(Map.of("fields",values)));
|
|
65
71
|
System.exit(0);
|