/*
 *(c) 2003, visigoth <visigoth@securitycentric.com>
 * This source code is distributed under a BSD license,
 * please see the LICENSE file for details
 *
 * MssqlRoleAudit.java
 *
 */

import com.securitycentric.metacoretex.interfaces.*;
import com.securitycentric.metacoretex.lib.*;

import java.sql.*;
import java.util.*;

/**
 *
 * @author  visigoth
 */
public class MssqlRoleAudit extends AbstractDatabaseProbe {
    
    /** Creates a new instance of MssqlRoleAudit */
    public MssqlRoleAudit() {
        
        setName("MSSQL Role Audit");
        setFamily("MS SQL");
        setVersion("$Id: MssqlRoleAudit.java,v 1.4 2003/09/21 22:44:11 visigoth_6 Exp $");
        setProbeId(21);
        setCopyright("(c) 2003, visigoth <visigoth@securitycentric.com>");
        
        addDepends("mssql/connection");
        
        setReport("MSSQL Server-Wide Role Members:\n"+
                  "=================================\n");
        
        setHelp("This probe attemtps to enumerate users in system-wide roles. "+
                "It will only be capable of doing so if the JDBC Connection "+
                "stored in mssql/connection has sufficient privelages\n");
    }
    
    public void probe() throws ProbeException {
        
        try {
            
            if (! kbHas("mssql/connection"))
                return;
            
            con = (Connection) kbGet("mssql/connection");
            
            PreparedStatement stmt = con.prepareStatement("SELECT name FROM sysxlogins WHERE (xstatus&?)=?");

            for (int i = 0; i < roles.length; i++) {
                addReport("\nRole "+roles[i]+":");

                stmt.setInt(1,masks[i]);
                stmt.setInt(2,masks[i]);
                res = stmt.executeQuery();

                setReportable(true);
            
                while (res.next()) {
                    if (res.getString("name") != null)
                        addReport("\t"+res.getString("name"));
                }
            }

        } catch (SQLException se) {
            throw(new ProbeException("Lack of Permission? " + se.getMessage()));
        }
    }

    String[] roles = {"sysadmin","securityadmin","serveradmin","setupadmin","processadmin","diskadmin","dbcreator","bulkadmin"};
    // If they didn't skip 2048 i'd do this better ;)
    int[] masks = {16,32,64,128,256,512,1024,4096};
    Connection con;
    ResultSet res;
}
