How do I dump secret text files to the console? - jenkins

I use this script to dump credentials in the script console:
import jenkins.model.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
def showRow = { credentialType, secretId, username = null, password = null, description = null ->
println("${credentialType} : ".padLeft(20) + secretId?.padRight(38)+" | " +username?.padRight(20)+" | " +password?.padRight(40) + " | " +description)
}
domainName = null
credentialsStore = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0]?.getStore()
domain = new Domain(domainName, null, Collections.<DomainSpecification>emptyList())
credentialsStore?.getCredentials(domain).each{
if(it instanceof UsernamePasswordCredentialsImpl)
showRow("user/password", it.id, it.username, it.password?.getPlainText(),it.description)
else if(it instanceof BasicSSHUserPrivateKey)
showRow("ssh priv key", it.id, it.passphrase?.getPlainText(), it.privateKeySource?.getPrivateKey(), it.description )
else if(it instanceof AWSCredentialsImpl)
showRow("aws", it.id, it.accessKey, it.secretKey?.getPlainText(),it.description )
else if(it instanceof StringCredentials)
showRow("secret text", it.id, it.secret?.getPlainText(), it.description, '' )
else
showRow("something else", it.id)
}
return
But it doesnt dump "Secret file" cred types (they fall through to "something else".
How can I also dump the contents of secret files in this script? What is the class for "Secret file"? what instanceof would that be?

Related

Active choices reactive parameter doesn't show desired default branch

I want to use Jenkins' active choices reactive parameter to use Groovy script to show all branches in the repository.
I have the following code sample to get all branches of a repository and since that there are hundreds of branches, I want the default to be master branch.
Even though I specifically inserted the defaultBranch variable, it shows the first item as the default and not the branch I written to.
Code:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import jenkins.model.Jenkins
def git_url ="url"
def getAllBranches(url, credentialID, activeChoice = false, defaultBranch = 'master') {
def jenkinsCredentials = CredentialsProvider.lookupCredentials(
com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey,
Jenkins.instance
);
def key = jenkinsCredentials.findResult { it.id == credentialID ? it.privateKey : null }
if( !key ) {
return 'Error: credentials not found'
}
Process process = ['ssh-agent','bash','-c', "echo '" + key + "' | ssh-add - 2> /dev/null && git ls-remote -t -h " + url].execute()
def out = new StringBuilder()
def err = new StringBuilder()
process.consumeProcessOutput( out, err )
process.waitFor()
if( err.size() > 0 ) return err
if( out.size() > 0 ) {
def branches = out.readLines().collect { it.split()[1].replaceAll('refs/heads/', '') }
if( activeChoice ) {
def defaultBranchIndex = branches.indexOf(defaultBranch)
if( defaultBranchIndex >= 0 ) branches.set(defaultBranchIndex, defaultBranch + ':selected')
}
return branches
}
}
return getAllBranches(git_url, "efa7bed9-56a0-42ac-8fa3-a68fe7700801")
You have set default for activeChoice to false in the getAllBranches method and do not set while calling it, thus the if-branch that adds the :selected is never entered.
I changed activeChoice method's value from false to true and it solved my issue:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import jenkins.model.Jenkins
def git_url ="url"
def getAllBranches(url, credentialID, activeChoice = true, defaultBranch = 'master') {
def jenkinsCredentials = CredentialsProvider.lookupCredentials(
com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey,
Jenkins.instance
);
def key = jenkinsCredentials.findResult { it.id == credentialID ? it.privateKey : null }
if( !key ) {
return 'Error: credentials not found'
}
Process process = ['ssh-agent','bash','-c', "echo '" + key + "' | ssh-add - 2> /dev/null && git ls-remote -t -h " + url].execute()
def out = new StringBuilder()
def err = new StringBuilder()
process.consumeProcessOutput( out, err )
process.waitFor()
if( err.size() > 0 ) return err
if( out.size() > 0 ) {
def branches = out.readLines().collect { it.split()[1].replaceAll('refs/heads/', '') }
if( activeChoice ) {
def defaultBranchIndex = branches.indexOf(defaultBranch)
if( defaultBranchIndex >= 0 ) branches.set(defaultBranchIndex, defaultBranch + ':selected')
}
return branches
}
}
return getAllBranches(git_url, "efa7bed9-56a0-42ac-8fa3-a68fe7700801")

Neo4jRule : Include algorithm plugins (such as randomWalk) to a Neo4j test server

I'm trying to test some procedure I have made with the code given by Neo4j for testing procedure. However my procedure is based on the results from the random walk algorithm which I have to call through 'algo.randomWalk.stream()'.
To do so, I'm instantiating a Neo4j test server. However it doesn't recognize the algo.randomWalk.stream(), because I think it doesn't have the algorithm package in its plugins.
This is the code I'm working on
package example;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Rule;
import org.junit.Test;
import org.neo4j.driver.v1.*;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import static org.neo4j.driver.v1.Values.parameters;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import org.neo4j.harness.junit.Neo4jRule;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;
import static org.neo4j.driver.v1.Values.parameters;
public class ScoringTest {
// This rule starts a Neo4j instance for us
#Rule
public Neo4jRule neo4j = new Neo4jRule()
// This is the Procedure we want to test
.withProcedure( Scoring.class );
//org.neo4j.server.thirdparty_jaxrs_classes=org.neo4j.examples.server.unmanaged=/examples/unmanaged
#Test
public void shouldAllowReturningTheLastValue() throws Throwable
{
// This is in a try-block, to make sure we close the driver after the test
try( Driver driver = GraphDatabase
.driver( neo4j.boltURI() , Config.build().withEncryptionLevel( Config.EncryptionLevel.NONE ).toConfig() ) )
{
System.out.println(neo4j.boltURI().toString());
// Given
neo4j.withExtension(neo4j.boltURI().toString(), "..\\graph-algorithms-algo-3.5.4.0.jar");
Session session = driver.session();
String PATH = "..\\data\\data.json";
File JSON_SOURCE = new File(PATH);
List<HashMap<String,Object>> mss = new ObjectMapper().readValue(JSON_SOURCE, List.class);
session.run("UNWIND {bulk} as row " +
"CREATE (n:Users) " +
"SET n += row.properties", parameters("bulk", mss ));
for(int k = 0; k<9; k++) {
PATH = "..\\data\\"+k+".json";
mss = new ObjectMapper().readValue(JSON_SOURCE, List.class);
JSON_SOURCE = new File(PATH);
session.run("UNWIND {bulk} as row " +
"MATCH (from:Users), (to:Clips) " +
"WHERE ID(from) = toInt(row.from) AND ID(to) = toInt(row.to._key) " +
"CREATE (from)-[rel:hasClipped]->(to) " +
"SET rel += row.properties ", parameters("bulk", mss ));
}
// When
Value result = session.run( "MATCH (n:Clips) WHERE ID(n) = 1038 " +
"CALL algo.randomWalk.stream(ID(n), 2, 1) " +
"YIELD nodeIds " +
"UNWIND nodeIds as nodeId " +
"MATCH (l:Clips)-[r:hasClipped]-(q:Users) " +
"WHERE (ID(l) = nodeId) AND (ID(q) in nodeIds) " +
"WITH collect({relation:r,Clip:l,User:q}) as res " +
"RETURN res").single().get("res");
System.out.println(result);
// Then
assertThat( result, equalTo( 0L ) );
}
}
}
The exact error that I get is : org.neo4j.driver.v1.exceptions.ClientException: There is no procedure with the name algo.randomWalk.stream registered for this database instance. Please ensure you've spelled the procedure name correctly and that the procedure is properly deployed.
Thanks for your time and your future answers,
Syndorik
So I found out a solution for this issue.
There's an option for Neo4jRule object that allows you to change the path to the plugin directory.
For instance, I've just added this config to Neo4jRule and then could call the graphalgo library :
public Neo4jRule neo4j = new Neo4jRule()
// This is the Procedure we want to test
.withProcedure( Scoring.class )
.withConfig(GraphDatabaseSettings.plugin_dir, "PATH_TO_PLUGIN_DIR")
.withConfig(GraphDatabaseSettings.procedure_unrestricted, "algo.*" );

Jenkins RoleBasedAuthorizationStrategy add user to Role Groovy Script

I am trying to find a groovy script to add an existing user to a Role using RoleBasedAuthorizationStrategy. Any help would be greatly appreciated.
I ran into the same need. After doing some web searching and looking at the plugin's code from GitHub, I found one link that provided some insight: https://issues.jenkins-ci.org/browse/JENKINS-23709. Based on that I hacked together a quick Groovy script that assigns a specific user to a specific role. Been awhile since I've done Groovy, so pardon the dust. Feel free to use this as an example for your own needs.
import jenkins.model.*
import hudson.security.*
import java.util.*
import com.michelin.cio.hudson.plugins.rolestrategy.*
import java.lang.reflect.*
def roleName = "guest"
def userName = "bot-release"
def findGuestRoleEntry(grantedRoles, roleName)
{
for (def entry : grantedRoles)
{
Role role = entry.getKey()
if (role.getName().equals(roleName))
{
return entry
}
}
return null
}
def authStrategy = Jenkins.instance.getAuthorizationStrategy()
if(authStrategy instanceof RoleBasedAuthorizationStrategy){
RoleBasedAuthorizationStrategy roleAuthStrategy = (RoleBasedAuthorizationStrategy) authStrategy
// Make constructors available
Constructor[] constrs = Role.class.getConstructors();
for (Constructor<?> c : constrs) {
c.setAccessible(true);
}
// Make the method assignRole accessible
Method assignRoleMethod = RoleBasedAuthorizationStrategy.class.getDeclaredMethod("assignRole", String.class, Role.class, String.class);
assignRoleMethod.setAccessible(true);
def grantedRoles = authStrategy.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL);
if (grantedRoles != null)
{
// println "Got grantedRoles for " + RoleBasedAuthorizationStrategy.GLOBAL
def roleEntry = findGuestRoleEntry(grantedRoles, roleName);
if (roleEntry != null)
{
// println "Found role " + roleName
def sidList = roleEntry.getValue()
if (sidList.contains(userName))
{
println "User " + userName + " already assigned to role " + roleName
} else {
println "Adding user " + userName + " to role " + roleName
roleAuthStrategy.assignRole(RoleBasedAuthorizationStrategy.GLOBAL, roleEntry.getKey(), userName);
println "OK"
}
Jenkins.instance.save()
} else {
println "Unable to find role " + roleName
}
} else {
println "Unable to find grantedRoles for " + RoleBasedAuthorizationStrategy.GLOBAL
}
} else {
println "Role Strategy Plugin not found!"
}

Connection error while connecting wamp server with netbeans8.1

I can't get any output from this program. Do you know why? I am using NetBeans 8.1 and wamp server. I design database named assignments online. Can you also suggest if I am using true drivers?
package managmentSystem;
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/**
*
* #author DiyaBangesh
*/
public class ManagmentSystem {
//PreparedStatement pst = null;
//Statement st= null;
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
try{
ResultSet rs;
Connection conn;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/assignment","root","");
JOptionPane.showMessageDialog(null,"Connection to database is established");
//return conn;
Statement st = conn.createStatement();
String sql ="SELECT * FROM userdetails";
rs = st.executeQuery(sql);
while(rs.next()){
String nam = rs.getString("name");
String uid = rs.getString("user_id");
String pwd = rs.getString("password");
String eid = rs.getString("email_id");
String con = rs.getString("contact");
String ut = rs.getString("usertype");
System.out.println(nam + " " + uid + " " + pwd + " "+ eid + " " + con + " " + ut );
}
conn.close();
}
catch (Exception sqlEx){
System.out.println(sqlEx);
}
}
}
mysql-connector-java-bin.jar is the one needeed and you have already used it. Make sure that you used correct database name & correct password. Replace 'yourpassword' with your database password. And make sure that server is running.
Follow as below.
public class ManagmentSystem {
Connection con;
Statement s;
PreparedStatement ps;
ResultSet rs;
ManagmentSystem()
{
try
{ Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/assignment?user=root&password=yourpassword");
}
catch(SQLException s)
{
System.out.println("Error in DB Connection");
s.printStackTrace();
}
catch(ClassNotFoundException c)
{
System.out.println("Driver not Found");
}
}
}

jenkins cli with checkout Subversion using groovy script

Is there a way to check out any Subversion project using Jenkins-Cli by executing a groovy script on the master? I can get to the point of creating SVN client manager[org.tmatesoft.svn.core.wc.SVNClientManager], but can't really understand how to employ that in checking out an SVN project from the URL.
After a lot of hit and trials I have come up with this, might be useful for someone else:
import jenkins.*;
import jenkins.model.*;
import hudson.*;
import hudson.model.*;
import hudson.slaves.SlaveComputer;
import hudson.scm.SubversionSCM;
import hudson.remoting.Channel;
import hudson.FilePath;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.ISVNDirEntryHandler;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import java.lang.*;
import java.util.ArrayList;
import java.util.List;
private boolean checkNodeExist(String node_Name){
if (Jenkins.getInstance().slaves.find({it.name == node_Name}) == null)
return false;
else
return true;
}
private ISVNAuthenticationProvider createAuthenticationProvider(AbstractProject context) {
return Jenkins.getInstance().getDescriptorByType(SubversionSCM.DescriptorImpl.class)
.createAuthenticationProvider(context);
}
public class SimpleSVNDirEntryHandler implements ISVNDirEntryHandler {
private final List<SVNDirEntry> dirs = new ArrayList<SVNDirEntry>();
public List<String> getDirs() {
List<String> sortedDirs = new ArrayList<String>();
for (SVNDirEntry dirEntry : dirs) {
sortedDirs.add(dirEntry.getName());
}
return sortedDirs;
}
public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException {
dirs.add(dirEntry);
}
}
public void PerfromSVNListOperationOnMaster(SVNURL svnUrl){
try{
SVNRepository repo = SVNRepositoryFactory.create(svnUrl);
SVNClientManager clientManager = SubversionSCM.createSvnClientManager(createAuthenticationProvider())
SVNLogClient logClient = clientManager.getLogClient();
SimpleSVNDirEntryHandler dirEntryHandler = new SimpleSVNDirEntryHandler();
List<String> dirs = new ArrayList<String>();
logClient.doList(repo.getLocation(),SVNRevision.HEAD, SVNRevision.HEAD,false,SVNDepth.INFINITY,SVNDirEntry.DIRENT_KIND,dirEntryHandler)
dirs = dirEntryHandler.getDirs();
println (dirs)
}
catch(SVNException svnEx){
println "#Error: " + svnEx;
throw svnEx
}
}
public void PerfromSVNCheckOutOperation(SVNURL svnUrl,boolean isMaster,String appender,SlaveComputer computer = null){
try{
SVNRepository repo = SVNRepositoryFactory.create(svnUrl);
SVNClientManager clientManager = SubversionSCM.createSvnClientManager(createAuthenticationProvider());
SVNUpdateClient updateClient = clientManager.getUpdateClient();
updateClient.setIgnoreExternals(false);
String destDir = svnUrl.getPath().substring(svnUrl.getPath().lastIndexOf('/')+1);
if (isMaster == true){
updateClient.doCheckout(repo.getLocation(),new java.io.File(System.getProperty("java.io.tmpdir"),destDir + '_' + appender),SVNRevision.HEAD,SVNRevision.HEAD,SVNDepth.INFINITY,false);
}else{
if (computer == null){
throw new IllegalArgumentException("#Error: Argument:computer can't be null when we need to checkout in slave");
}else{
updateClient.doCheckout(repo.getLocation(),new java.io.File(System.getProperty("java.io.tmpdir"),destDir + '_' + appender),SVNRevision.HEAD,SVNRevision.HEAD,SVNDepth.INFINITY,false);
Channel slaveChannel = computer.getChannel();
FilePath fpSrc = new hudson.FilePath(new java.io.File(System.getProperty("java.io.tmpdir"),destDir + '_' + appender));
//println new java.io.File((slave.getWorkspaceRoot().toString()),destDir).toString().replace('\\','/')
FilePath fpDestination = new hudson.FilePath(slaveChannel,new java.io.File((slave.getWorkspaceRoot().toString()),destDir + '_' + appender).toString().replace('\\','/'));
println "Copying files recursively from Temp directory in master to slave";
int files_copied = fpSrc.copyRecursiveTo(fpDestination);
println files_copied
fpSrc.deleteRecursive();
}
}
}
catch (Exception ex){
throw new Exception("#Error:",ex);
}
}
if (args.length == 4){
String url = new String(args[0]);
SVNURL svn_url = null;
try{
svn_url = SVNURL.parseURIDecoded(url);
}
catch(SVNException svnEX){
println "#Error: Check SVN repository Location.";
throw svnEX;
}
String nodeName = new String(args[1]);
String operation = new String(args[2]);
String checkoutAppendString = new String(args[3]);
println args
if (nodeName.equalsIgnoreCase("master")){
println "Executing script on master"
if (operation.equalsIgnoreCase("list")){
PerfromSVNListOperationOnMaster(svn_url);
}else{
PerfromSVNCheckOutOperation(svn_url,true,checkoutAppendString);
}
}else{
if (checkNodeExist(nodeName)){
slave = Jenkins.getInstance().slaves.find({it.name == nodeName});
SlaveComputer computer = slave.getComputer();
if (computer.isOffline()){
println "#Error: $slave is offline."
return
}else{
if (operation.equalsIgnoreCase("list")){
PerfromSVNListOperationOnMaster(svn_url)
}else{
PerfromSVNCheckOutOperation(svn_url,false,checkoutAppendString,computer);
}
}
}else{
println "#Error: $nodeName not found."
return
}
}
}else{
println "Invalid Usage, expecting 3 arguments : 1.RepositoryURL 2.NodeName 3.OperationType"
return
}

Resources